pax_global_header00006660000000000000000000000064126541021010014502gustar00rootroot0000000000000052 comment=4434bc17ef9d23add533aee81a374309195393ae btrbk-0.22.2/000077500000000000000000000000001265410210100126715ustar00rootroot00000000000000btrbk-0.22.2/COPYING000066400000000000000000001045131265410210100137300ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. 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 them 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 prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. 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. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey 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; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. 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. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 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. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 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 state 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 3 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, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program 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, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU 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. But first, please read . btrbk-0.22.2/ChangeLog000066400000000000000000000137311265410210100144500ustar00rootroot00000000000000btrbk-0.22.2 * Bugfix: fix checks on "btrfs sub show" output, which resulted in breakage on btrfs-progs < 4.1 (close: #68). btrbk-0.22.1 * Support for btrfs-progs v4.4 (close: #66). btrbk-0.22.0 * Bugfix: fix monthly schedule if older than 10 weeks (close: #59). * Bugfix: fix sprintf used by config option "timestamp_format long" when using perl-5.22.0 (close: #57). * Bugfix: fix "--progress" option (close: #64). * Added "clean" command (close: #61). * Added "-n, --dry-run" option. * Added configuration options "raw_target_compress_level", "raw_target_compress_threads" (close: #60). * Added "stats" command (close: #54). * Print "$hostname:$path" instead of "{$hostname}$path" in summary and logs. btrbk-0.21.0 * Added transaction log (configuration option "transaction_log"). * Added configuration option "group". * Allow filtering of all commands by group as well as targets. * Added "list backups|snapshots|latest|config|source|volume|target" commands (while removing "tree" command). * Added "config print" command. * Added "--format=table|long|raw" and "-t,--table" command line options, producing tabular and raw (machine-readable) output for "(dry)run", "tree" and "list" commands. * Print scheduler details if -v option is set on action run/dryrun. * Added configuration option "ssh_cipher_spec" (close: #47). * Added "target raw", with GnuPG and compression support (experimental). * Added configuration option "timestamp_format short|long". * Replaced "info" command with "usage", with tabular output. * Bugfix: correctly handle "incremental no" option. * Bugfix: return exit status 10 instead of 0 if one or more backup tasks aborted. * Better error handling for send/receive commands (close: #33). * Hardened ssh_filter_btrbk.sh script: fine-grained access control, restrict-path option, sudo option (close: #45). * Added example cron script. btrbk-0.20.0 * Added configuration option "ssh_port" (close: #39). * Added configuration option "ssh_compression" (close: #44). * Added command line option "--progress" (close: #42). * Bugfix: correct handling of empty "snapshot_dir" (close: #43). * Accept long options on command line. * Documentation: added FAQ. btrbk-0.19.3 * Bugfix: fix sorting of dates in schedule(). * Bugfix: correct parsing of btrfs subvolume list (close: #28). * Support for btrfs-progs v4.1-rc1. btrbk-0.19.2 * Bugfix: fix crash when using btrfs-progs < 3.17.3 (close: #24). btrbk-0.19.1 * Use "cgen" for snapshot comparison. * Bugfix: fix crash in summary display (close: #22). btrbk-0.19.0 * Added "snapshot_create onchange", which skips snapshot creation if the latest snapshot is up-to-date (i.e. has same generation as the source subvolume). * Improved handling of command line subvolume filter for "run", "dryrun" and "tree" actions (close: #21). * Bugfix: fixed crash in action "diff". btrbk-0.18.0 * MIGRATION - update ssh_filter_btrbk.sh on all remote hosts - update configuration file (/etc/btrbk/btrbk.conf): - "snapshot_create_always yes" -> "snapshot_create always" - "snapshot_create_always no" -> "snapshot_create ondemand" * Set PATH variable instead of using absolute "/sbin/btrfs" for compatibility with all linux distros out there, which all install 'btrfs' in different locations (close: #20). * Added configuration option "snapshot_create", replacing option "snapshot_create_always". This allows setups with multiple btrbk instances on several hosts (close: #18). * Added command line option -r (resume only). * Catch and display errors from "btrfs subvolume show". * Include systemd service and timer unit for daily backups. btrbk-0.17.1 * Bugfix: send/receive: delete possibly left-behind garbled subvolume on failure. Fail with unrecoverable error if stray target subvolume is in the way (close: #17). * Bugfix: assume unreachable target as clean on snapshot creation if snapshot_create_always is set (close: #19). btrbk-0.17.0 * New versioning scheme using more common three-level versions. * Code refactoring: cleanup of data structures and handling of btrfs subvolume tree, as well as security related code parts. * Correct handling of symlinks to btrfs subvolumes (close: #12). * Added configuration option "snapshot_name" (close: #5). * Log messages now go to stderr, only the summary is printed on stdout. * Bugfix: allow "0" as subvolume name (close: #10). * Bugfix: allow "/" as volume name (close: #15). * Bugfix: check source AND targets for determining snapshot postfix (close: #11). * Bugfix: fixed "diff" action (colses: #14). * Allow '+' character for subvolume names. * Filesystems on remote hosts are now printed as "{my.remote-host.com}" in summary and logs. btrbk-0.16 * Bugfix: correctly check retention policy for missing backups. btrbk-0.15 * Added configuration option "btrfs_progs_compat", to be enabled if using btrfs-progs < 3.17 (close: #6). * Added configuration option "resume_missing", for automatic resume of missing backups (close: #8). * Removed configuration option "receive_log" in favor of printing errors from "btrfs receive". * Bugfix: show correct exit code on external command failure. * Bugfix: no crash if "commit_delete" option is set to "no" btrbk-0.14 * Bugfix: correctly handle empty target subvolumes (blocker for all new users; close: #4). btrbk-0.13 * Bugfix: allow '@' character for subvolume names (blocker for ubuntu users, since ubuntu prefixes all subvolumes with '@' in its subvolume layout; close: #3). btrbk-0.12 * Cleaner and more generic parsing of btrfs subvolume list. * Bugfix: subvolumes are also allowed for "snapshot_dir" (close: #1, #2). btrbk-0.11 * Added option -p (preserve backups). * Added optional subvolume argument for run/dryrun actions, for explicit selection of subvolumes to be processed. * Bugfixes btrbk-0.10 * Initial revision. btrbk-0.22.2/Makefile000066400000000000000000000032451265410210100143350ustar00rootroot00000000000000PN = btrbk PREFIX ?= /usr CONFDIR = /etc CRONDIR = /etc/cron.daily BINDIR = $(PREFIX)/sbin DOCDIR = $(PREFIX)/share/doc/$(PN) SCRIPTDIR = $(PREFIX)/share/$(PN)/scripts SYSTEMDDIR = $(PREFIX)/lib/systemd/system MAN1DIR = $(PREFIX)/share/man/man1 MAN5DIR = $(PREFIX)/share/man/man5 all: @echo 'nothing to do for "all"' install-bin: @echo 'installing main script and config...' install -Dm644 btrbk.conf.example "$(DESTDIR)$(CONFDIR)/btrbk/btrbk.conf.example" install -Dm755 $(PN) "$(DESTDIR)$(BINDIR)/$(PN)" install-systemd: @echo 'installing systemd service units...' install -Dm644 contrib/systemd/btrbk.service "$(DESTDIR)$(SYSTEMDDIR)/btrbk.service" install -Dm644 contrib/systemd/btrbk.timer "$(DESTDIR)$(SYSTEMDDIR)/btrbk.timer" install-share: @echo 'installing auxiliary scripts...' install -Dm755 ssh_filter_btrbk.sh "$(DESTDIR)$(SCRIPTDIR)/ssh_filter_btrbk.sh" install -Dm755 contrib/cron/btrbk-mail "$(DESTDIR)$(SCRIPTDIR)/btrbk-mail" install-man: @echo 'installing manpages...' install -Dm644 doc/btrbk.1 "$(DESTDIR)$(MAN1DIR)/btrbk.1" install -Dm644 doc/ssh_filter_btrbk.1 "$(DESTDIR)$(MAN1DIR)/ssh_filter_btrbk.1" install -Dm644 doc/btrbk.conf.5 "$(DESTDIR)$(MAN5DIR)/btrbk.conf.5" gzip -9 "$(DESTDIR)$(MAN1DIR)/btrbk.1" gzip -9 "$(DESTDIR)$(MAN1DIR)/ssh_filter_btrbk.1" gzip -9 "$(DESTDIR)$(MAN5DIR)/btrbk.conf.5" install-doc: @echo 'installing documentation...' install -Dm644 README.md "$(DESTDIR)$(DOCDIR)/README.md" install -Dm644 doc/FAQ.md "$(DESTDIR)$(DOCDIR)/FAQ.md" gzip -9 "$(DESTDIR)$(DOCDIR)/README.md" gzip -9 "$(DESTDIR)$(DOCDIR)/FAQ.md" install: install-bin install-systemd install-share install-man install-doc btrbk-0.22.2/README.md000066400000000000000000000361751265410210100141640ustar00rootroot00000000000000Introduction ============ btrbk is a backup tool for btrfs subvolumes, taking advantage of btrfs specific capabilities to create atomic snapshots and transfer them incrementally to your backup locations. The source and target locations are specified in a config file, which allows to easily configure simple scenarios like "laptop with locally attached backup disks", as well as more complex ones, e.g. "server receiving backups from several hosts via ssh, with different retention policy". Key Features: - Atomic snapshots - Incremental backups - Configurable retention policy - Backups to multiple destinations - Transfer via ssh - Resume of backups (if backup target was not reachable for a while) - Encrypted backups to non-btrfs destinations - Transaction log - Display file changes between two backups btrbk is intended to be run as a cron job. Installation ============ btrbk comes as a single executable file (perl script), without the need of any installation procedures. If you want the package and man-pages properly installed, follow the instructions below. Prerequisites ------------- - [btrfs-progs]: Btrfs filesystem utilities (use "btrfs_progs_compat" option for hosts running version prior to v3.17) - Perl interpreter: probably already installed on your system - [Date::Calc]: Perl module [btrfs-progs]: http://www.kernel.org/pub/linux/kernel/people/kdave/btrfs-progs/ [Date::Calc]: http://search.cpan.org/perldoc?Date::Calc Instructions ------------ In order to install the btrbk executable along with the man-pages and an example configuration file, choose one of the following methods: ### Generic Linux System Download and unpack the newest stable [btrbk source tarball] and type: sudo make install ### Gentoo Linux Grab the digint portage overlay from: `git://dev.tty0.ch/portage/digint-overlay.git` emerge app-backup/btrbk ### Debian Based Distros btrbk is in `stretch (testing) (utils)`: https://packages.debian.org/stretch/btrbk Packages are also available via NeuroDebian: http://neuro.debian.net/pkgs/btrbk.html ### Arch Linux btrbk is in AUR: https://aur.archlinux.org/packages/btrbk/ ### Alpine Linux btrbk is in `testing`, install with: apk add btrbk [btrbk source tarball]: http://www.digint.ch/download/btrbk/releases/ [btrbk debian package]: http://www.digint.ch/download/btrbk/packages/debian/ Synopsis ======== Please consult the [btrbk(1)] man-page provided with this package for a full description of the command line options. [btrbk(1)]: http://www.digint.ch/btrbk/doc/btrbk.html Configuration File ================== Before running `btrbk`, you will need to create a configuration file. You might want to take a look at `btrbk.conf.example` provided with this package. For a detailed description, please consult the [btrbk.conf(5)] man-page. When playing around with config-files, it is highly recommended to check the output using the `dryrun` command before executing the backups: btrbk -c myconfig -v dryrun This will read all btrfs information on the source/target filesystems and show what actions would be performed (without writing anything to the disks). [btrbk.conf(5)]: http://www.digint.ch/btrbk/doc/btrbk.conf.html Example: laptop with usb-disk for backups ----------------------------------------- In this example, we assume you have a laptop with: - a disk having a btrfs volume mounted as `/mnt/btr_pool`, containing a subvolume `rootfs` for the root filesystem and a subvolume `home` for the user data. - a backup disk having a btrfs volume mounted as `/mnt/btr_backup`, containing a subvolume `mylaptop` for the incremental backups. Retention policy: - keep snapshots for 14 days (very handy if you are on the road and the backup disk is not attached) - keep monthly backups forever - keep weekly backups for 10 weeks - keep daily backups for 20 days /etc/btrbk/btrbk-mylaptop.conf: snapshot_preserve_daily 14 snapshot_preserve_weekly 0 snapshot_preserve_monthly 0 target_preserve_daily 20 target_preserve_weekly 10 target_preserve_monthly all snapshot_dir btrbk_snapshots volume /mnt/btr_pool subvolume rootfs target send-receive /mnt/btr_backup/mylaptop subvolume home target send-receive /mnt/btr_backup/mylaptop /etc/cron.daily/btrbk: #!/bin/sh exec /usr/sbin/btrbk -q -c /etc/btrbk/btrbk-mylaptop.conf run - This will create snapshots on a daily basis: - `/mnt/btr_pool/btrbk_snapshots/rootfs.YYYYMMDD` - `/mnt/btr_pool/btrbk_snapshots/home.YYYYMMDD` - And create incremental backups in: - `/mnt/btr_backup/mylaptop/rootfs.YYYYMMDD` - `/mnt/btr_backup/mylaptop/home.YYYYMMDD` If you want the snapshots to be created only if the backup disk is attached, simply add the following line to the config: snapshot_create ondemand Example: host-initiated backup on fileserver -------------------------------------------- Let's say you have a fileserver at "myserver.mydomain.com" where you want to create backups of your laptop disk, the config would look like this: ssh_identity /etc/btrbk/ssh/id_rsa volume /mnt/btr_pool subvolume rootfs target send-receive /mnt/btr_backup/mylaptop target send-receive ssh://myserver.mydomain.com/mnt/btr_backup/mylaptop In addition to the backups on your local usb-disk mounted at `/mnt/btr_backup/mylaptop`, incremental backups would also be pushed to `myserver.mydomain.com`. Example: fileserver-initiated backups from several hosts -------------------------------------------------------- If you're a sysadmin and want to trigger backups directly from your fileserver, the config would be something like: ssh_identity /etc/btrbk/ssh/id_rsa volume ssh://alpha.mydomain.com/mnt/btr_pool subvolume rootfs target send-receive /mnt/btr_backup/alpha subvolume home target send-receive /mnt/btr_backup/alpha volume ssh://beta.mydomain.com/mnt/btr_pool subvolume rootfs target send-receive /mnt/btr_backup/beta subvolume dbdata target send-receive /mnt/btr_backup/beta This will pull backups from alpha/beta.mydomain.com and locally create: - `/mnt/btr_backup/alpha/rootfs.YYYYMMDD` - `/mnt/btr_backup/alpha/home.YYYYMMDD` - `/mnt/btr_backup/beta/rootfs.YYYYMMDD` - `/mnt/btr_backup/beta/dbdata.YYYYMMDD` Example: local time-machine (daily snapshots) --------------------------------------------- If all you want is to create snapshots of your home directory on a regular basis: /etc/btrbk/btrbk.conf: volume /mnt/btr_pool snapshot_dir btrbk_snapshots subvolume home /etc/cron.daily/btrbk: #!/bin/sh exec /usr/sbin/btrbk -q run Note that you can run btrbk more than once a day, e.g. by creating the above script in `/etc/cron.hourly/btrbk`, or by calling `sudo btrbk run` from the command line. Example: multiple btrbk instances --------------------------------- Let's say we have a host (at 192.168.0.42) running btrbk with the setup of the time-machine example above, and we need a backup server to only fetch the snapshots. /etc/btrbk/btrbk.conf (on backup server): volume ssh://192.168.0.42/mnt/btr_pool subvolume home snapshot_dir btrbk_snapshots snapshot_preserve_daily all snapshot_create no resume_missing yes target_preserve_daily 0 target_preserve_weekly 10 target_preserve_monthly all target send-receive /mnt/btr_backup/my-laptop.com If the server runs btrbk with this config, the latest snapshot (which is *always* transferred), 10 weeklies and all monthlies are received from 192.168.0.42. The source filesystem is never altered because of `snapshot_preserve_daily all`. Example: backup from non-btrfs source ------------------------------------- First create a btrfs subvolume on the backup server: # btrfs subvolume create /mnt/btr_backup/myhost_sync In your daily cron script, prior to running btrbk, sync your source to `myhost_sync`, something like: rsync -a --delete -e ssh myhost.mydomain.com://data/ /mnt/btr_backup/myhost_sync/ Then run btrbk, with myhost_sync configured *without any targets* as follows: volume /mnt/btr_backup subvolume myhost_sync snapshot_name myhost snapshot_preserve_daily 14 snapshot_preserve_weekly 20 snapshot_preserve_monthly all This will produce daily snapshots `/mnt/btr_backup/myhost.20150101`, with retention as defined with the snapshot_preserve_* options. Note that the provided script: "contrib/cron/btrbk-mail" has support for this! Example: encrypted backup to non-btrfs target --------------------------------------------- If your backup server does not support btrfs, you can send your subvolumes to a raw file. This is an _experimental_ feature: btrbk supports "raw" targets, meaning that similar to the "send-receive" target the btrfs subvolume is being sent using `btrfs send` (mirroring filesystem level data), but instead of instantly being received (`btrfs receive`) by the target filesystem, it is being redirected to a file, optionally compressed and piped through GnuPG. /etc/btrbk/btrbk.conf: raw_target_compress xz raw_target_encrypt gpg gpg_keyring /etc/btrbk/gpg/pubring.gpg gpg_recipient btrbk@mydomain.com volume /mnt/btr_pool subvolume home target raw ssh://cloud.example.com/backup ssh_user btrbk # incremental no This will create a GnuPG encrypted, compressed files on the target host: - `/backup/home.YYYYMMDD.btrfs_.xz.gpg` for non-incremental images, - `/backup/home.YYYYMMDD.btrfs_@.xz.gpg` for subsequent incremenal images. I you are using raw _incremental_ backups, please make sure you understand the implications (see [btrbk.conf(5)], TARGET TYPES). Setting up SSH ============== Since btrbk needs root access on the remote side, it is *very advisable* to take all the security precautions you can. Usually backups are generated periodically without user interaction, so it is not possible to protect your ssh key with a password. The steps below will give you hints on how to secure your ssh server for a backup scenario. Note that the btrbk executable is not needed on the remote side, but you will need "/sbin/btrfs" from the btrfs-progs package. btrbk comes with a shell script "ssh_filter_btrbk.sh", which restricts ssh access to sane calls to the /sbin/btrfs command needed for snapshot creation and send/receive operations (see [ssh_filter_btrbk(1)]). Here is an example on how it can be used with ssh: **Step 1** (client): Create a ssh key dedicated to btrbk, without password protection: ssh-keygen -t rsa -b 2048 -f /etc/btrbk/ssh/id_rsa -C btrbk@mydomain.com -N "" **Step 2** (server): Copy the "ssh_filter_btrbk.sh" from the btrbk project to "/backup/scripts/". **Step 3** (server): Add contents of the public key (/etc/btrbk/ssh/id_rsa.pub) to "/root/.ssh/authorized_keys", and configure "ssh_filter_btrbk.sh" to be executed whenever this key is used for authentication. Example lines: # example backup source (also allowing deletion of old snapshots) command="/backup/scripts/ssh_filter_btrbk.sh -l --source --delete" ... # example backup target (also allowing deletion of old snapshots) command="/backup/scripts/ssh_filter_btrbk.sh -l --target --delete" ... # example fetch-only backup source (snapshot_preserve_daily=all, snapshot_create=no), # restricted to subvolumes within /home or /data command="/backup/scripts/ssh_filter_btrbk.sh -l --send -p /home -p /data" ... You might also want to restrict ssh access to a static IP address within your network: from="192.168.0.42",command="/backup/scripts/ssh_filter_btrbk.sh [...]" ... Please refer to [ssh_filter_btrbk(1)] for a description of the "ssh_filter_btrbk.sh" options, as well as [sshd(8)] for a description of the "authorized_keys" file format. Also consider setting up ssh access for a user dedicated to btrbk and either set suid root on ssh_filter_btrbk.sh or use the "--sudo" option and configure /etc/sudoers accordingly. For even more security, you can setup a chroot environment in /etc/ssh/sshd_config (see [sshd_config(5)]). [ssh_filter_btrbk(1)]: http://www.digint.ch/btrbk/doc/ssh_filter_btrbk.html [sshd(8)]: http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man8/sshd.8 [sshd_config(5)]: http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man5/sshd_config.5 Restoring Backups ================= btrbk does not provide any mechanism to restore your backups, this has to be done manually. In the examples below, we assume that you have a btrfs volume mounted at `/mnt/btr_pool`, and the subvolume you want to have restored is at `/mnt/btr_pool/data`. Example: Restore a Snapshot ----------------------------- First, pick a snapshot to be restored: btrbk list snapshots From the list, pick the snapshot you want to restore. Let's say it's `/mnt/btr_pool/_btrbk_snap/data.20150101`. If the broken subvolume is still present, move it away: mv /mnt/btr_pool/data /mnt/btr_pool/data.BROKEN Now restore the snapshot: btrfs subvolume snapshot /mnt/btr_pool/_btrbk_snap/data.20150101 /mnt/btr_pool/data That's it; your `data` subvolume is restored. If everything went fine, it's time to nuke the broken subvolume: btrfs subvolume delete /mnt/btr_pool/data.BROKEN Example: Restore a Backup ------------------------- First, pick a backup to be restored: btrbk list backups From the list, pick the backup you want to restore. Let's say it's `/mnt/btr_backup/data.20150101`. If the broken subvolume is still present, move it away: mv /mnt/btr_pool/data /mnt/btr_pool/data.BROKEN Now restore the backup: btrfs send /mnt/btr_backup/data.20150101 | btrfs receive /mnt/btr_pool/ btrfs subvolume snapshot /mnt/btr_pool/data.20150101 /mnt/btr_pool/data btrfs subvolume delete /mnt/btr_pool/data.20150101 Alternatively, if you're restoring data on a remote host, do something like this: btrfs send /mnt/btr_backup/data.20150101 | ssh root@my-remote-host.com btrfs receive /mnt/btr_pool/ If everything went fine, nuke the broken subvolume: btrfs subvolume delete /mnt/btr_pool/data.BROKEN FAQ === Make sure to also read the [btrbk FAQ page](doc/FAQ.md). Help improve it by asking! Development =========== Source Code Repository ---------------------- The source code for btrbk is managed using Git. Check out the source like this: git clone git://dev.tty0.ch/btrbk.git How to Contribute ----------------- Your contributions are welcome! If you would like to contribute or have found bugs: - Visit the [btrbk project page on GitHub] and use the [issues tracker] there. - Talk to us on Freenode in `#btrbk`. - Contact the author via email (the email address can be found in the sources). Any feedback is appreciated! [btrbk project page on GitHub]: http://github.com/digint/btrbk [issues tracker]: http://github.com/digint/btrbk/issues License ======= btrbk is free software, available under the [GNU General Public License, Version 3][GPLv3]. [GPLv3]: http://www.gnu.org/licenses/gpl.html btrbk-0.22.2/btrbk000077500000000000000000004264741265410210100137440ustar00rootroot00000000000000#!/usr/bin/perl -T =head1 NAME btrbk - backup tool for btrfs volumes =head1 SYNOPSIS btrbk --help =head1 DESCRIPTION Backup tool for btrfs subvolumes, taking advantage of btrfs specific send-receive mechanism, allowing incremental backups at file-system level. The full btrbk documentation is available at L. =head1 AUTHOR Axel Burri =head1 COPYRIGHT AND LICENSE Copyright (c) 2014-2016 Axel Burri. All rights reserved. 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 3 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, see . =cut use strict; use warnings FATAL => qw( all ); use Carp qw(confess); use Date::Calc qw(Today_and_Now Delta_Days Day_of_Week); use Getopt::Long qw(GetOptions); use POSIX qw(strftime); use Data::Dumper; our $VERSION = "0.22.2"; our $AUTHOR = 'Axel Burri '; our $PROJECT_HOME = ''; my $version_info = "btrbk command line client, version $VERSION"; my @config_src = ("/etc/btrbk.conf", "/etc/btrbk/btrbk.conf"); my $ip_addr_match = qr/(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])/; my $host_name_match = qr/(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])/; my $file_match = qr/[0-9a-zA-Z_@\+\-\.\/]+/; # note: ubuntu uses '@' in the subvolume layout: my $ssh_prefix_match = qr/ssh:\/\/($ip_addr_match|$host_name_match)/; my $uuid_match = qr/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/; my $timestamp_postfix_match = qr/\.(?[0-9]{4})(?[0-9]{2})(?
[0-9]{2})(T(?[0-9]{2})(?[0-9]{2}))?(_(?[0-9]+))?/; # matches "YYYYMMDD[Thhmm][_NN]" my $raw_postfix_match = qr/--(?$uuid_match)(\@(?$uuid_match))?\.btrfs?(\.(?(gz|bz2|xz)))?(\.(?gpg))?/; # matches ".btrfs_[@][.gz|bz2|xz][.gpg]" my $group_match = qr/[a-zA-Z0-9_:-]+/; my $ssh_cipher_match = qr/[a-z0-9][a-z0-9@.-]+/; my %day_of_week_map = ( monday => 1, tuesday => 2, wednesday => 3, thursday => 4, friday => 5, saturday => 6, sunday => 7 ); my %config_options = ( # NOTE: the parser always maps "no" to undef # NOTE: keys "volume", "subvolume" and "target" are hardcoded # NOTE: files "." and "no" map to timestamp_format => { default => "short", accept => [ "short", "long" ], context => [ "root", "volume", "subvolume" ] }, snapshot_dir => { default => undef, accept_file => { relative => 1 } }, snapshot_name => { default => undef, accept_file => { name_only => 1 }, context => [ "subvolume" ] }, # NOTE: defaults to the subvolume name (hardcoded) snapshot_create => { default => "always", accept => [ "no", "always", "ondemand", "onchange" ] }, incremental => { default => "yes", accept => [ "yes", "no", "strict" ] }, resume_missing => { default => "yes", accept => [ "yes", "no" ] }, preserve_day_of_week => { default => "sunday", accept => [ (keys %day_of_week_map) ] }, snapshot_preserve_daily => { default => "all", accept => [ "all" ], accept_numeric => 1 }, snapshot_preserve_weekly => { default => 0, accept => [ "all" ], accept_numeric => 1 }, snapshot_preserve_monthly => { default => "all", accept => [ "all" ], accept_numeric => 1 }, target_preserve_daily => { default => "all", accept => [ "all" ], accept_numeric => 1 }, target_preserve_weekly => { default => 0, accept => [ "all" ], accept_numeric => 1 }, target_preserve_monthly => { default => "all", accept => [ "all" ], accept_numeric => 1 }, btrfs_commit_delete => { default => undef, accept => [ "after", "each", "no" ] }, ssh_identity => { default => undef, accept_file => { absolute => 1 } }, ssh_user => { default => "root", accept_regexp => qr/^[a-z_][a-z0-9_-]*$/ }, ssh_port => { default => "default", accept => [ "default" ], accept_numeric => 1 }, ssh_compression => { default => undef, accept => [ "yes", "no" ] }, ssh_cipher_spec => { default => "default", accept_regexp => qr/^$ssh_cipher_match(,$ssh_cipher_match)*$/ }, transaction_log => { default => undef, accept_file => { absolute => 1 } }, raw_target_compress => { default => undef, accept => [ "no", "gzip", "bzip2", "xz" ] }, raw_target_compress_level => { default => "default", accept => [ "default" ], accept_numeric => 1 }, raw_target_compress_threads => { default => "default", accept => [ "default" ], accept_numeric => 1 }, raw_target_encrypt => { default => undef, accept => [ "no", "gpg" ] }, gpg_keyring => { default => undef, accept_file => { absolute => 1 } }, gpg_recipient => { default => undef, accept_regexp => qr/^[0-9a-zA-Z_@\+\-\.]+$/ }, btrfs_progs_compat => { default => undef, accept => [ "yes", "no" ] }, group => { default => undef, accept_regexp => qr/^$group_match(\s*,\s*$group_match)*$/, split => qr/\s*,\s*/ }, # deprecated options snapshot_create_always => { default => undef, accept => [ "yes", "no" ], deprecated => { yes => { warn => "Please use \"snapshot_create always\"", replace_key => "snapshot_create", replace_value => "always", }, no => { warn => "Please use \"snapshot_create no\" or \"snapshot_create ondemand\"", replace_key => "snapshot_create", replace_value => "ondemand", } }, }, receive_log => { default => undef, accept => [ "sidecar", "no" ], accept_file => { absolute => 1 }, deprecated => { DEFAULT => { warn => "ignoring" } }, } ); my @config_target_types = qw(send-receive raw); my %table_formats = ( list_volume => { table => [ qw( volume_host volume_path ) ], long => [ qw( volume_host volume_path ) ], raw => [ qw( volume_url volume_host volume_path volume_rsh ) ], }, list_source => { table => [ qw( source_host source_subvol snapshot_path snapshot_name ) ], long => [ qw( source_host source_subvol snapshot_path snapshot_name ) ], raw => [ qw( source_url source_host source_path snapshot_path snapshot_name source_rsh ) ], }, list_target => { table => [ qw( target_host target_subvol ) ], long => [ qw( target_host target_subvol ) ], raw => [ qw( target_url target_host target_path target_rsh ) ], }, list => { table => [ qw( source_host source_subvol snapshot_path snapshot_name target_host target_subvol ) ], long => [ qw( source_host source_subvol snapshot_path snapshot_name snapshot_preserve target_host target_subvol target_preserve ) ], raw => [ qw( source_url source_host source_subvol snapshot_path snapshot_name snapshot_preserve target_url target_host target_subvol target_preserve source_rsh target_rsh ) ], }, resolved => { table => [ qw( source_host source_subvol snapshot_subvol status target_host target_subvol ) ], long => [ qw( type source_host source_subvol snapshot_subvol status target_host target_subvol ) ], raw => [ qw( type source_host source_path snapshot_path snapshot_name status target_host target_path source_rsh ) ], }, schedule => { table => [ qw( action host subvol scheme reason ) ], long => [ qw( action host root_path subvol_path scheme reason ) ], raw => [ qw( topic action url host path dow d m w) ], }, usage => { table => [ qw( host path size used free ) ], long => [ qw( type host path size device_allocated device_unallocated device_missing used free free_min data_ratio metadata_ratio used global_reserve global_reserve_used ) ], raw => [ qw( type host path size device_allocated device_unallocated device_missing used free free_min data_ratio metadata_ratio used global_reserve global_reserve_used ) ], RALIGN => { size=>1, device_allocated=>1, device_unallocated=>1, device_missing=>1, used=>1, free=>1, free_min=>1, data_ratio=>1, metadata_ratio=>1, used=>1, global_reserve=>1, global_reserve_used=>1 }, }, transaction => { table => [ qw( type status target_host target_subvol source_host source_subvol parent_subvol ) ], long => [ qw( localtime type status duration target_host target_subvol source_host source_subvol parent_subvol message ) ], raw => [ qw( time localtime type status duration target_url source_url parent_url message ) ], tlog => [ qw( localtime type status duration target_url source_url parent_url message ) ], }, ); my %root_tree_cache; # map URL to SUBTREE (needed since "btrfs subvolume list" does not provide us with the uuid of the btrfs root node) my %vinfo_cache; # map URL to vinfo my %uuid_info; # map UUID to btr_tree node my %uuid_fs_map; # map UUID to URL my $dryrun; my $loglevel = 1; my $show_progress = 0; my $err = ""; my $output_format; my $tlog_fh; my $current_transaction; my @transaction_log; my %config_override; $SIG{__DIE__} = sub { print STDERR "\nERROR: process died unexpectedly (btrbk v$VERSION)"; print STDERR "\nPlease contact the author: $AUTHOR\n\n"; print STDERR "Stack Trace:\n----------------------------------------\n"; Carp::confess @_; }; $SIG{INT} = sub { print STDERR "\nERROR: Cought SIGINT, dumping transaction log:\n"; action("signal", status => "SIGINT"); print_formatted("transaction", \@transaction_log, output_format => "tlog", outfile => *STDERR); exit 1; }; sub VERSION_MESSAGE { print STDERR $version_info . "\n\n"; } sub HELP_MESSAGE { print STDERR "usage: btrbk [options] [filter...]\n"; print STDERR "\n"; print STDERR "options:\n"; # "--------------------------------------------------------------------------------"; # 80 print STDERR " -h, --help display this help message\n"; print STDERR " --version display version information\n"; print STDERR " -c, --config=FILE specify configuration file\n"; print STDERR " -n, --dry-run perform a trial run with no changes made\n"; print STDERR " -p, --preserve preserve all backups (do not delete any old targets)\n"; print STDERR " -r, --resume-only resume only (do not create new snapshots, only resume\n"; print STDERR " missing backups)\n"; print STDERR " -v, --verbose be verbose (set loglevel=info)\n"; print STDERR " -q, --quiet be quiet (do not print summary for the \"run\" command)\n"; print STDERR " -l, --loglevel=LEVEL set logging level (warn, info, debug, trace)\n"; print STDERR " -t, --table change output to table format\n"; print STDERR " --format=FORMAT change output format, FORMAT=table|long|raw\n"; print STDERR " --progress show progress bar on send-receive operation\n"; print STDERR "\n"; print STDERR "commands:\n"; print STDERR " run perform backup operations as defined in the config file\n"; print STDERR " dryrun don't run btrfs commands; show what would be executed\n"; print STDERR " stats print snapshot/backup statistics\n"; print STDERR " list available subcommands are:\n"; print STDERR " backups all backups and corresponding snapshots\n"; print STDERR " snapshots all snapshots and corresponding backups\n"; print STDERR " latest most recent snapshots and backups\n"; print STDERR " config configured source/snapshot/target relations\n"; print STDERR " source configured source/snapshot relations\n"; print STDERR " volume configured volume sections\n"; print STDERR " target configured targets\n"; print STDERR " clean delete incomplete (garbled) backups\n"; print STDERR " usage print filesystem usage\n"; print STDERR " origin print origin information for subvolume\n"; print STDERR " diff shows new files since subvolume for subvolume \n"; print STDERR "\n"; print STDERR "For additional information, see $PROJECT_HOME\n"; } sub TRACE { my $t = shift; print STDERR "... $t\n" if($loglevel >= 4); } sub DEBUG { my $t = shift; print STDERR "$t\n" if($loglevel >= 3); } sub INFO { my $t = shift; print STDERR "$t\n" if($loglevel >= 2); } sub WARN { my $t = shift; print STDERR "WARNING: $t\n" if($loglevel >= 1); } sub ERROR { my $t = shift; print STDERR "ERROR: $t\n"; } sub ABORTED($$) { my $config = shift; my $t = shift; unless($t eq "USER_SKIP") { $t =~ s/\n/\\\\/g; $t =~ s/\r//g; action("abort_" . ($config->{CONTEXT} || "undef"), status => "ABORT", vinfo_prefixed_keys("target", vinfo($config->{url}, $config)), message => $t, ); } $config->{ABORTED} = $t; } sub init_transaction_log($) { my $file = shift // die; if(open($tlog_fh, ">> $file")) { # print headers and startup message print_formatted("transaction", [ ], output_format => "tlog", outfile => $tlog_fh); INFO "Using transaction log: $file"; } else { $tlog_fh = undef; ERROR "Failed to open transaction log '$file': $!"; } } sub close_transaction_log() { if($tlog_fh) { DEBUG "Closing transaction log"; close $tlog_fh || ERROR "Failed to close transaction log: $!"; } } sub action($@) { my $type = shift // die; my $h = { @_ }; my $time = $h->{time} // time; $h->{type} = $type; $h->{time} = $time; $h->{localtime} = strftime("%FT%T%z", localtime($time)); print_formatted("transaction", [ $h ], output_format => "tlog", no_header => 1, outfile => $tlog_fh) if($tlog_fh); push @transaction_log, $h; return $h; } sub start_transaction($@) { my $type = shift // die; my $time = time; die("start_transaction() while transaction is running") if($current_transaction); my @actions = (ref($_[0]) eq "HASH") ? @_ : { @_ }; # single action is not hashref $current_transaction = []; foreach (@actions) { push @$current_transaction, action($type, %$_, status => "starting", time => $time); } } sub end_transaction($$) { my $type = shift // die; my $status = shift // die; my $time = time; die("end_transaction() while no transaction is running") unless($current_transaction); foreach (@$current_transaction) { die("end_transaction() has different type") unless($_->{type} eq $type); action($type, %$_, status => $status, duration => ($dryrun ? undef : ($time - $_->{time}))); } $current_transaction = undef; } sub run_cmd(@) { # shell-based implementation. # this needs some redirection magic for filter_stderr to work. # NOTE: multiple filters are not supported! my @commands = (ref($_[0]) eq "HASH") ? @_ : { @_ }; die unless(scalar(@commands)); $err = ""; my $destructive = 0; my $catch_stderr = 0; my $filter_stderr = undef; foreach (@commands) { $_->{rsh} //= []; $_->{cmd} = [ @{$_->{rsh}}, @{$_->{cmd}} ]; $_->{cmd_text} = join(' ', map { s/\n/\\n/g; "'$_'" } @{$_->{cmd}}); # ugly escape of \n, do we need to escape others? $catch_stderr = 1 if($_->{catch_stderr}); $filter_stderr = $_->{filter_stderr} if($_->{filter_stderr}); # NOTE: last filter wins! $destructive = 1 unless($_->{non_destructive}); } my $cmd_print = join(' | ', map { $_->{cmd_text} } @commands); my $cmd = $cmd_print; if($catch_stderr) { if(scalar(@commands) == 1) { # no pipes, simply redirect stderr to stdout $cmd .= ' 2>&1'; } else { # pipe chain is more complicated, result is something like this: # { btrfs send 2>&3 | pv | btrfs receive 2>&3 ; } 3>&1 $cmd = "{ "; my $pipe = ""; foreach (@commands) { $cmd .= $pipe . $_->{cmd_text}; $cmd .= ' 2>&3' if($_->{catch_stderr}); $pipe = ' | '; } $cmd .= ' ; } 3>&1'; } } # hide redirection magic from debug output if($dryrun && $destructive) { DEBUG "### (dryrun) $cmd_print"; return ""; } DEBUG "### $cmd_print"; # execute command and parse output TRACE "Executing command: $cmd"; my $ret = ""; $ret = `$cmd`; chomp($ret); TRACE "Command output:\n$ret"; if($?) { my $exitcode= $? >> 8; my $signal = $? & 127; DEBUG "Command execution failed (exitcode=$exitcode" . ($signal ? ", signal=$signal" : "") . "): \"$cmd\""; if($catch_stderr) { $_ = $ret; &{$filter_stderr} ($cmd) if($filter_stderr); ERROR "[$cmd_print] $_" if($_); } return undef; } else { DEBUG "Command execution successful"; } return $ret; } sub vinfo($$) { my $url = shift // die; my $config = shift || die; my $name = $url; $name =~ s/^.*\///; my %info = ( URL => $url, NAME => $name, ); if($url =~ /^ssh:\/\/(\S+?)(\/\S+)$/) { my ($host, $path) = ($1, $2); my $ssh_port = config_key($config, "ssh_port"); my $ssh_user = config_key($config, "ssh_user"); my $ssh_identity = config_key($config, "ssh_identity"); my $ssh_compression = config_key($config, "ssh_compression"); my $ssh_cipher_spec = config_key($config, "ssh_cipher_spec") // "default"; my @ssh_options; push(@ssh_options, '-p', $ssh_port) if($ssh_port ne "default"); push(@ssh_options, '-C') if($ssh_compression); push(@ssh_options, '-c', $ssh_cipher_spec) if($ssh_cipher_spec ne "default"); if($ssh_identity) { push(@ssh_options, '-i', $ssh_identity); } else { WARN "No SSH identity provided (option ssh_identity is not set) for: $url"; } %info = ( %info, HOST => $host, PATH => $path, PRINT => "$host:$path", RSH_TYPE => "ssh", SSH_USER => $ssh_user, SSH_IDENTITY => $ssh_identity, SSH_PORT => $ssh_port, RSH => ['/usr/bin/ssh', @ssh_options, $ssh_user . '@' . $host ], ); } elsif(($url =~ /^\//) && ($url =~ /^$file_match$/)) { %info = ( %info, PATH => $url, PRINT => $url, ); } else { die "Ambiguous vinfo url: $url"; } my $btrfs_progs_compat = config_key($config, "btrfs_progs_compat"); $info{BTRFS_PROGS_COMPAT} = $btrfs_progs_compat if($btrfs_progs_compat); TRACE "vinfo created: $url"; return \%info; } sub vinfo_child($$) { my $parent = shift || die; my $rel_path = shift // die; my $name = $rel_path; $name =~ s/^.*\///; my %info = ( NAME => $name, URL => "$parent->{URL}/$rel_path", PATH => "$parent->{PATH}/$rel_path", PRINT => "$parent->{PRINT}/$rel_path", SUBVOL_PATH => $rel_path, ); foreach (qw( HOST RSH_TYPE SSH_USER SSH_IDENTITY SSH_PORT RSH BTRFS_PROGS_COMPAT ) ) { $info{$_} = $parent->{$_} if(exists $parent->{$_}); } TRACE "vinfo child created from \"$parent->{PRINT}\": $info{PRINT}"; return \%info; } sub vinfo_root($) { my $vol = shift; my $detail = btrfs_subvolume_detail($vol); return undef unless $detail; vinfo_set_detail($vol, $detail); # read (and cache) the subvolume list return undef unless vinfo_subvol_list($vol); TRACE "vinfo root created: $vol->{PRINT}"; return $vol; } sub vinfo_set_detail($$) { my $vol = shift || die; my $detail = shift || die; # add detail data to vinfo hash foreach(keys %$detail) { next if($_ eq "REL_PATH"); next if($_ eq "TOP_LEVEL"); next if($_ eq "SUBTREE"); next if($_ eq "path"); $vol->{$_} = $detail->{$_}; } if($vol->{REAL_PATH}) { if($vol->{RSH_TYPE} && ($vol->{RSH_TYPE} eq "ssh")) { $vol->{REAL_URL} = "ssh://$vol->{HOST}$detail->{REAL_PATH}"; } else { $vol->{REAL_URL} = $vol->{REAL_PATH}; } } # update cache $vinfo_cache{$vol->{URL}} = $vol; $vinfo_cache{$vol->{REAL_URL}} = $vol if($vol->{REAL_URL}); TRACE "vinfo updated for: $vol->{PRINT}"; TRACE(Data::Dumper->Dump([$vol], ["vinfo{$vol->{PRINT}}"])); return $vol; } # returns hash: ( $prefix_{url,path,host,name,subvol_path,rsh} => value, ... ) sub vinfo_prefixed_keys($$) { my $prefix = shift // die; my $vinfo = shift; return () unless($vinfo); my %ret; if($prefix) { $ret{$prefix} = $vinfo->{PRINT}; $prefix .= '_'; } foreach (qw( URL PATH HOST NAME SUBVOL_PATH )) { $ret{$prefix . lc($_)} = $vinfo->{$_}; } $ret{$prefix . "subvol"} = $vinfo->{PATH}; $ret{$prefix . "rsh"} = ($vinfo->{RSH} ? join(" ", @{$vinfo->{RSH}}) : undef), return %ret; } sub config_key($$;@) { my $node = shift || die; my $key = shift || die; my %opts = @_; TRACE "config_key: context=$node->{CONTEXT}, key=$key"; if(exists($config_override{$key})) { TRACE "config_key: forced key=$key to value=" . ($config_override{$key} // ""); return $config_override{$key}; } while(not exists($node->{$key})) { # note: while all config keys exist in root context (at least with default values), # we also allow fake configs (CONTEXT="cmdline") which have no PARENT. return undef unless($node->{PARENT}); $node = $node->{PARENT}; } TRACE "config_key: found value=" . ($node->{$key} // ""); my $retval = $node->{$key}; $retval = $opts{prefix} . $retval if(defined($opts{prefix}) && defined($retval)); $retval .= $opts{postfix} if(defined($opts{postfix}) && defined($retval)); return $retval; } sub config_dump_keys($;@) { my $config = shift || die; my %opts = @_; my @ret; my $maxlen = 0; foreach my $key (sort keys %config_options) { my $val; if($opts{resolve}) { $val = config_key($config, $key); } else { next unless exists($config->{$key}); $val = $config->{$key}; } if($opts{skip_defaults}) { if(defined($config_options{$key}->{default}) && defined($val)) { next if($val eq $config_options{$key}->{default}); } if((not defined($config_options{$key}->{default})) && (not (defined($val)))) { next; # both undef, skip } } if(ref($val) eq "ARRAY") { my $val2 = join(',', @$val); $val = $val2; } $val //= ""; my $len = length($key); $maxlen = $len if($len > $maxlen); push @ret, { key => $key, val => $val, len => $len }; } # print as table return map { ($opts{prefix} // "") . $_->{key} . (' ' x (1 + $maxlen - $_->{len})) . ' ' . $_->{val} } @ret; } sub check_file($$;$$) { my $file = shift // die; my $accept = shift || die; my $key = shift; # only for error text my $config_file = shift; # only for error text if($accept->{ssh} && ($file =~ /^ssh:\/\//)) { unless($file =~ /^$ssh_prefix_match\/$file_match$/) { ERROR "Ambiguous ssh url for option \"$key\" in \"$config_file\" line $.: $file" if($key && $config_file); return undef; } } elsif($file =~ /^$file_match$/) { if($accept->{absolute}) { unless($file =~ /^\//) { ERROR "Only absolute files allowed for option \"$key\" in \"$config_file\" line $.: $file" if($key && $config_file); return undef; } } elsif($accept->{relative}) { if($file =~ /^\//) { ERROR "Only relative files allowed for option \"$key\" in \"$config_file\" line $.: $file" if($key && $config_file); return undef; } } elsif($accept->{name_only}) { if($file =~ /\//) { ERROR "Option \"$key\" is not a valid file name in \"$config_file\" line $.: $file" if($key && $config_file); return undef; } } else { die("accept_type must contain either 'relative' or 'absolute'"); } } else { ERROR "Ambiguous file for option \"$key\" in \"$config_file\" line $.: $file" if($key && $config_file); return undef; } # check directory traversal if(($file =~ /^\.\.$/) || ($file =~ /^\.\.\//) || ($file =~ /\/\.\.\//) || ($file =~ /\/\.\.$/)) { ERROR "Illegal directory traversal for option \"$key\" in \"$config_file\" line $.: $file" if($key && $config_file); return undef; } return 1; } sub check_config_option($$$;$) { my $key = shift; my $value = shift; my $context = shift; my $config_file = shift; # only for error text my $config_file_statement = $config_file ? " in \"$config_file\" line $." : ""; my $opt = $config_options{$key}; # accept only keys listed in %config_options unless($opt) { ERROR "Unknown option \"$key\"" . $config_file_statement; return undef; } if(grep(/^$value$/, @{$opt->{accept}})) { TRACE "option \"$key=$value\" found in accept list"; } elsif($opt->{accept_numeric} && ($value =~ /^[0-9]+$/)) { TRACE "option \"$key=$value\" is numeric, accepted"; } elsif($opt->{accept_file}) { # be very strict about file options, for security sake return undef unless(check_file($value, $opt->{accept_file}, $key, $config_file)); TRACE "option \"$key=$value\" is a valid file, accepted"; $value =~ s/\/+$//; # remove trailing slash $value =~ s/^\/+/\//; # sanitize leading slash $value = "no" if($value eq "."); # maps to undef later } elsif($opt->{accept_regexp}) { my $match = $opt->{accept_regexp}; if($value =~ m/$match/) { TRACE "option \"$key=$value\" matched regexp, accepted"; } else { ERROR "Value \"$value\" failed input validation for option \"$key\"" . $config_file_statement; return undef; } } else { ERROR "Unsupported value \"$value\" for option \"$key\"" . $config_file_statement; return undef; } if($opt->{split}) { $value = [ split($opt->{split}, $value) ]; TRACE "splitted option \"$key\": " . join(',', @$value); } if($opt->{context} && !grep(/^$context$/, @{$opt->{context}})) { ERROR "Option \"$key\" is only allowed in " . join(" or ", map("\"$_\"", @{$opt->{context}})) . " context" . $config_file_statement; return undef; } if($opt->{deprecated}) { WARN "Found deprecated option \"$key $value\"" . $config_file_statement . ": " . ($opt->{deprecated}->{$value}->{warn} // $opt->{deprecated}->{DEFAULT}->{warn}); my $replace_key = $opt->{deprecated}->{$value}->{replace_key}; my $replace_value = $opt->{deprecated}->{$value}->{replace_value}; if(defined($replace_key)) { $key = $replace_key; $value = $replace_value; WARN "Using \"$key $value\""; } } return $value; } sub parse_config_line($$$$$) { my ($file, $root, $cur, $key, $value) = @_; if($key eq "volume") { $cur = $root; TRACE "config: context forced to: $cur->{CONTEXT}"; # be very strict about file options, for security sake return undef unless(check_file($value, { absolute => 1, ssh => 1 }, $key, $file)); $value =~ s/\/+$// unless($value =~ /^\/+$/); # remove trailing slash $value =~ s/^\/+/\//; # sanitize leading slash TRACE "config: adding volume \"$value\" to root context"; my $volume = { CONTEXT => "volume", PARENT => $cur, url => $value, }; $cur->{VOLUME} //= []; push(@{$cur->{VOLUME}}, $volume); $cur = $volume; } elsif($key eq "subvolume") { while($cur->{CONTEXT} ne "volume") { if(($cur->{CONTEXT} eq "root") || (not $cur->{PARENT})) { ERROR "Subvolume keyword outside volume context, in \"$file\" line $."; return undef; } $cur = $cur->{PARENT} || die; TRACE "config: context changed to: $cur->{CONTEXT}"; } # be very strict about file options, for security sake return undef unless(check_file($value, { relative => 1 }, $key, $file)); $value =~ s/\/+$//; # remove trailing slash $value =~ s/^\/+//; # remove leading slash TRACE "config: adding subvolume \"$value\" to volume context: $cur->{url}"; my $snapshot_name = $value; $snapshot_name =~ s/^.*\///; # snapshot_name defaults to subvolume name my $subvolume = { CONTEXT => "subvolume", PARENT => $cur, rel_path => $value, url => $cur->{url} . '/' . $value, snapshot_name => $snapshot_name, }; $cur->{SUBVOLUME} //= []; push(@{$cur->{SUBVOLUME}}, $subvolume); $cur = $subvolume; } elsif($key eq "target") { if($cur->{CONTEXT} eq "target") { $cur = $cur->{PARENT} || die; TRACE "config: context changed to: $cur->{CONTEXT}"; } if($cur->{CONTEXT} ne "subvolume") { ERROR "Target keyword outside subvolume context, in \"$file\" line $."; return undef; } if($value =~ /^(\S+)\s+(\S+)$/) { my ($target_type, $droot) = ($1, $2); unless(grep(/^$target_type$/, @config_target_types)) { ERROR "Unknown target type \"$target_type\" in \"$file\" line $."; return undef; } # be very strict about file options, for security sake return undef unless(check_file($droot, { absolute => 1, ssh => 1 }, $key, $file)); $droot =~ s/\/+$//; # remove trailing slash $droot =~ s/^\/+/\//; # sanitize leading slash TRACE "config: adding target \"$droot\" (type=$target_type) to subvolume context: $cur->{url}"; my $target = { CONTEXT => "target", PARENT => $cur, target_type => $target_type, url => $droot, }; $cur->{TARGET} //= []; push(@{$cur->{TARGET}}, $target); $cur = $target; } else { ERROR "Ambiguous target configuration, in \"$file\" line $."; return undef; } } else { $value = check_config_option($key, $value, $cur->{CONTEXT}, $file); return undef unless(defined($value)); TRACE "config: adding option \"$key=$value\" to $cur->{CONTEXT} context"; $value = undef if($value eq "no"); # we don't want to check for "no" all the time $cur->{$key} = $value; } return $cur; } sub parse_config(@) { my @config_files = @_; my $file = undef; foreach(@config_files) { TRACE "config: checking for file: $_"; if(-r "$_") { $file = $_; last; } } unless($file) { ERROR "Configuration file not found: " . join(', ', @config_files); return undef; } my $root = { CONTEXT => "root", SRC_FILE => $file }; my $cur = $root; # set defaults foreach (keys %config_options) { next if $config_options{$_}->{deprecated}; # don't pollute hash with deprecated options $root->{$_} = $config_options{$_}->{default}; } INFO "Using configuration: $file"; open(FILE, '<', $file) or die $!; while () { chomp; next if /^\s*#/; # ignore comments next if /^\s*$/; # ignore empty lines TRACE "config: parsing line $. with context=$cur->{CONTEXT}: \"$_\""; if(/^(\s*)([a-zA-Z_]+)\s+(.*)$/) { # NOTE: we do not perform checks on indentation! my ($indent, $key, $value) = (length($1), lc($2), $3); $value =~ s/\s*$//; $cur = parse_config_line($file, $root, $cur, $key, $value); unless(defined($cur)) { # error, bail out $root = undef; last; } TRACE "line processed: new context=$cur->{CONTEXT}"; } else { ERROR "Parse error in \"$file\" line $."; $root = undef; last; } } close FILE || ERROR "Failed to close configuration file: $!"; TRACE(Data::Dumper->Dump([$root], ["config{$file}"])) if($root); return $root; } sub btrfs_filesystem_show_all_local() { return run_cmd( cmd => [ qw(btrfs filesystem show) ], non_destructive => 1 ); } sub btrfs_filesystem_show($) { my $vol = shift || die; my $path = $vol->{PATH} // die; return run_cmd( cmd => [ qw(btrfs filesystem show), $path ], rsh => $vol->{RSH}, non_destructive => 1 ); } sub btrfs_filesystem_df($) { my $vol = shift || die; my $path = $vol->{PATH} // die; return run_cmd( cmd => [qw(btrfs filesystem df), $path], rsh => $vol->{RSH}, non_destructive => 1 ); } sub btrfs_filesystem_usage($) { my $vol = shift || die; my $path = $vol->{PATH} // die; my $ret = run_cmd( cmd => [ qw(btrfs filesystem usage), $path ], rsh => $vol->{RSH}, non_destructive => 1 ); return undef unless(defined($ret)); my %detail; foreach (split("\n", $ret)) { if(/^\s+Device size:\s+(\S+)/) { $detail{size} = $1; } elsif(/^\s+Device allocated:\s+(\S+)/) { $detail{device_allocated} = $1; } elsif(/^\s+Device unallocated:\s+(\S+)/) { $detail{device_unallocated} = $1; } elsif(/^\s+Device missing:\s+(\S+)/) { $detail{device_missing} = $1; } elsif(/^\s+Used:\s+(\S+)/) { $detail{used} = $1; } elsif(/^\s+Free \(estimated\):\s+(\S+)\s+\(min: (\S+)\)/) { $detail{free} = $1; $detail{free_min} = $2; } elsif(/^\s+Data ratio:\s+(\S+)/) { $detail{data_ratio} = $1; } elsif(/^\s+Metadata ratio:\s+(\S+)/) { $detail{metadata_ratio} = $1; } elsif(/^\s+Used:\s+(\S+)/) { $detail{used} = $1; } elsif(/^\s+Global reserve:\s+(\S+)\s+\(used: (\S+)\)/) { $detail{global_reserve} = $1; $detail{global_reserve_used} = $2; } else { TRACE "Failed to parse filesystem usage line \"$_\" for: $vol->{PRINT}"; } } DEBUG "Parsed " . scalar(keys %detail) . " filesystem usage detail items: $vol->{PRINT}"; TRACE(Data::Dumper->Dump([\%detail], ["btrfs_filesystem_usage($vol->{URL})"])); return \%detail; } # returns hashref with keys: (name uuid parent_uuid id gen cgen top_level) # for btrfs-progs >= 4.1, also returns key: "received_uuid" sub btrfs_subvolume_detail($) { my $vol = shift || die; my $path = $vol->{PATH} // die; my $ret = run_cmd(cmd => [ qw(btrfs subvolume show), $path], rsh => $vol->{RSH}, non_destructive => 1, catch_stderr => 1, # hack for shell-based run_cmd() filter_stderr => sub { if(/ssh command rejected/) { # catch errors from ssh_filter_btrbk.sh $err = "ssh command rejected (please fix ssh_filter_btrbk.sh)"; } elsif(/^ERROR: (.*)/) { # catch errors from btrfs command $err = $1; } else { DEBUG "Unparsed error: $_"; $err = $_; } # consume stderr line, as $err will be displayed as a user-friendly WARNING $_ = undef; } ); return undef unless(defined($ret)); # workaround for btrfs-progs < 3.17.3 (returns exit status 0 on errors) if($ret =~ /^ERROR: (.*)/) { $err = $1; return undef; } my $real_path; if($ret =~ /^($file_match)/) { $real_path = $1; DEBUG "Real path for subvolume \"$vol->{PRINT}\" is: $real_path" if($real_path ne $path); return undef unless(check_file($real_path, { absolute => 1 })); } else { $real_path = $path; WARN "No real path provided by \"btrfs subvolume show\" for subvolume \"$vol->{PRINT}\", using: $path"; } my %detail = ( REAL_PATH => $real_path ); if($ret =~ /^\Q$real_path\E is (btrfs root|toplevel subvolume)/) { # btrfs-progs < 4.4 prints: " is btrfs root" # btrfs-progs >= 4.4 prints: " is toplevel subvolume" DEBUG "found btrfs root: $vol->{PRINT}"; $detail{id} = 5; $detail{is_root} = 1; } elsif($ret =~ /^$real_path/) { TRACE "btr_detail: found btrfs subvolume: $vol->{PRINT}"; # NOTE: received_uuid is not required here, as btrfs-progs < 4.1 does not give us that information. # no worries, we get this from btrfs_subvolume_list() for all subvols. my @required_keys = qw(name uuid parent_uuid id gen cgen top_level); my %trans = ( "Name" => "name", "uuid" => "uuid", "UUID" => "uuid", # btrfs-progs >= 4.1 "Parent uuid" => "parent_uuid", "Parent UUID" => "parent_uuid", # btrfs-progs >= 4.1 "Received UUID" => "received_uuid", # btrfs-progs >= 4.1 "Creation time" => "creation_time", "Object ID" => "id", "Subvolume ID" => "id", # btrfs-progs >= 4.1 "Generation (Gen)" => "gen", "Generation" => "gen", # btrfs-progs >= 4.1 "Gen at creation" => "cgen", "Parent" => "parent_id", "Parent ID" => "parent_id", # btrfs-progs >= 4.1 "Top Level" => "top_level", "Top level ID" => "top_level", # btrfs-progs >= 4.1 "Flags" => "flags", ); foreach (split("\n", $ret)) { next unless /^\s+(.+):\s+(.*)$/; my ($key, $value) = ($1, $2); if($trans{$key}) { $detail{$trans{$key}} = $value; } else { WARN "Failed to parse subvolume detail \"$key: $value\" for: $vol->{PRINT}"; } } DEBUG "Parsed " . scalar(keys %detail) . " subvolume detail items: $vol->{PRINT}"; TRACE(Data::Dumper->Dump([$vol], ["btrfs_subvolume_detail($vol->{URL})"])); foreach(@required_keys) { unless(defined($detail{$_})) { ERROR "Failed to parse subvolume detail (unsupported btrfs-progs) for: $vol->{PRINT}"; return undef; } } } else { ERROR "Failed to parse subvolume detail (unsupported btrfs-progs) for: $vol->{PRINT}"; return undef; } return \%detail; } sub btrfs_subvolume_list($;@) { my $vol = shift || die; my %opts = @_; my $path = $vol->{PATH} // die; my $btrfs_progs_compat = $vol->{BTRFS_PROGS_COMPAT} || $opts{btrfs_progs_compat}; my @filter_options = ('-a'); push(@filter_options, '-o') if($opts{subvol_only}); my @display_options = ('-c', '-u', '-q'); push(@display_options, '-R') unless($btrfs_progs_compat); my $ret = run_cmd(cmd => [ qw(btrfs subvolume list), @filter_options, @display_options, $path ], rsh => $vol->{RSH}, non_destructive => 1, ); return undef unless(defined($ret)); my @nodes; foreach (split(/\n/, $ret)) { # ID top level path where path is the relative path # of the subvolume to the top level subvolume. The subvolume?s ID may # be used by the subvolume set-default command, or at mount time via # the subvolid= option. If -p is given, then parent is added to # the output between ID and top level. The parent?s ID may be used at # mount time via the subvolrootid= option. # NOTE: btrfs-progs prior to v3.17 do not support the -R flag my %node; if($btrfs_progs_compat) { unless(/^ID ([0-9]+) gen ([0-9]+) cgen ([0-9]+) top level ([0-9]+) parent_uuid ([0-9a-z-]+) uuid ([0-9a-z-]+) path (.+)$/) { ERROR "Failed to parse subvolume list (unsupported btrfs-progs) for: $vol->{PRINT}"; DEBUG "Offending line: $_"; return undef; } %node = ( id => $1, gen => $2, cgen => $3, top_level => $4, parent_uuid => $5, # note: parent_uuid="-" if no parent # received_uuid => $6, uuid => $6, path => $7 # btrfs path, NOT filesystem path ); } else { unless(/^ID ([0-9]+) gen ([0-9]+) cgen ([0-9]+) top level ([0-9]+) parent_uuid ([0-9a-z-]+) received_uuid ([0-9a-z-]+) uuid ([0-9a-z-]+) path (.+)$/) { ERROR "Failed to parse subvolume list (unsupported btrfs-progs) for: $vol->{PRINT}"; DEBUG "Offending line: $_"; return undef; } %node = ( id => $1, gen => $2, cgen => $3, top_level => $4, parent_uuid => $5, # note: parent_uuid="-" if no parent received_uuid => $6, uuid => $7, path => $8 # btrfs path, NOT filesystem path ); } # NOTE: "btrfs subvolume list " prints prefix only if # the subvolume is reachable within . (as of btrfs-progs-3.18.2) # # NOTE: Be prepared for this to change in btrfs-progs! $node{path} =~ s/^\///; # remove "/" portion from "path". push @nodes, \%node; } DEBUG "Parsed " . scalar(@nodes) . " total subvolumes for filesystem at: $vol->{PRINT}"; return \@nodes; } sub btrfs_subvolume_find_new($$;$) { my $vol = shift || die; my $path = $vol->{PATH} // die; my $lastgen = shift // die; my $ret = run_cmd(cmd => [ qw(btrfs subvolume find-new), $path, $lastgen ], rsh => $vol->{RSH}, non_destructive => 1, ); unless(defined($ret)) { ERROR "Failed to fetch modified files for: $vol->{PRINT}"; return undef; } my %files; my $parse_errors = 0; my $transid_marker; foreach (split(/\n/, $ret)) { if(/^inode \S+ file offset (\S+) len (\S+) disk start \S+ offset \S+ gen (\S+) flags (\S+) (.+)$/) { my $file_offset = $1; my $len = $2; my $gen = $3; my $flags = $4; my $name = $5; $files{$name}->{len} += $len; $files{$name}->{new} = 1 if($file_offset == 0); $files{$name}->{gen}->{$gen} = 1; # count the generations if($flags eq "COMPRESS") { $files{$name}->{flags}->{compress} = 1; } elsif($flags eq "COMPRESS|INLINE") { $files{$name}->{flags}->{compress} = 1; $files{$name}->{flags}->{inline} = 1; } elsif($flags eq "INLINE") { $files{$name}->{flags}->{inline} = 1; } elsif($flags eq "NONE") { } else { WARN "unparsed flags: $flags"; } } elsif(/^transid marker was (\S+)$/) { $transid_marker = $1; } else { $parse_errors++; } } return { files => \%files, transid_marker => $transid_marker, parse_errors => $parse_errors, }; } # returns $target, or undef on error sub btrfs_subvolume_snapshot($$) { my $svol = shift || die; my $target_vol = shift // die; my $target_path = $target_vol->{PATH} // die; my $src_path = $svol->{PATH} // die; DEBUG "[btrfs] snapshot (ro):"; DEBUG "[btrfs] host : $svol->{HOST}" if($svol->{HOST}); DEBUG "[btrfs] source: $src_path"; DEBUG "[btrfs] target: $target_path"; INFO ">>> $target_vol->{PRINT}"; start_transaction("snapshot", vinfo_prefixed_keys("target", $target_vol), vinfo_prefixed_keys("source", $svol), ); my $ret = run_cmd(cmd => [ qw(btrfs subvolume snapshot), '-r', $src_path, $target_path ], rsh => $svol->{RSH}, ); end_transaction("snapshot", ($dryrun ? "DRYRUN" : (defined($ret) ? "success" : "ERROR"))); ERROR "Failed to create btrfs subvolume snapshot: $svol->{PRINT} -> $target_path" unless(defined($ret)); return defined($ret) ? $target_path : undef; } sub btrfs_subvolume_delete($@) { my $targets = shift // die; my %opts = @_; my $commit = $opts{commit}; die if($commit && ($commit ne "after") && ($commit ne "each")); $targets = [ $targets ] unless(ref($targets) eq "ARRAY"); return 0 unless(scalar(@$targets)); my $rsh = $targets->[0]->{RSH}; my $rsh_host_check = $targets->[0]->{HOST} || ""; foreach (@$targets) { # make sure all targets share same HOST my $host = $_->{HOST} || ""; die if($rsh_host_check ne $host); } DEBUG "[btrfs] delete" . ($commit ? " (commit-$commit):" : ":"); DEBUG "[btrfs] subvolume: $_->{PRINT}" foreach(@$targets); my @options; @options = ("--commit-$commit") if($commit); my @target_paths = map( { $_->{PATH} } @$targets); start_transaction($opts{type} // "delete", map( { { vinfo_prefixed_keys("target", $_) }; } @$targets) ); my $ret = run_cmd(cmd => [ qw(btrfs subvolume delete), @options, @target_paths ], rsh => $rsh, ); end_transaction($opts{type} // "delete", ($dryrun ? "DRYRUN" : (defined($ret) ? "success" : "ERROR"))); ERROR "Failed to delete btrfs subvolumes: " . join(' ', map( { $_->{PRINT} } @$targets)) unless(defined($ret)); return defined($ret) ? scalar(@$targets) : undef; } sub btrfs_send_receive($$$$) { my $snapshot = shift || die; my $target = shift || die; my $parent = shift; my $ret_vol_received = shift; my $snapshot_path = $snapshot->{PATH} // die; my $target_path = $target->{PATH} // die; my $parent_path = $parent ? $parent->{PATH} : undef; my $vol_received = vinfo_child($target, $snapshot->{NAME}); $$ret_vol_received = $vol_received if(ref $ret_vol_received); INFO ">>> $vol_received->{PRINT}"; print STDOUT "Receiving subvol: $vol_received->{PRINT}\n" if($show_progress && (not $dryrun)); DEBUG "[btrfs] send/receive" . ($parent ? " (incremental)" : " (complete)") . ":"; DEBUG "[btrfs] source: $snapshot->{PRINT}"; DEBUG "[btrfs] parent: $parent->{PRINT}" if($parent); DEBUG "[btrfs] target: $target->{PRINT}"; my @send_options; my @receive_options; push(@send_options, '-p', $parent_path) if($parent_path); # push(@send_options, '-v') if($loglevel >= 3); # push(@receive_options, '-v') if($loglevel >= 3); my @cmd_pipe; push @cmd_pipe, { cmd => [ qw(btrfs send), @send_options, $snapshot_path ], rsh => $snapshot->{RSH}, name => "btrfs send", catch_stderr => 1, # hack for shell-based run_cmd() }; push @cmd_pipe, { cmd => [ '/usr/bin/pv', '-trab' ], } if($show_progress); push @cmd_pipe, { cmd => [ qw(btrfs receive), @receive_options, $target_path . '/' ], rsh => $target->{RSH}, name => "btrfs receive", catch_stderr => 1, # hack for shell-based run_cmd() filter_stderr => sub { $err = $_; $_ = undef } }; my $send_receive_error = 0; start_transaction("send-receive", vinfo_prefixed_keys("target", $vol_received), vinfo_prefixed_keys("source", $snapshot), vinfo_prefixed_keys("parent", $parent), ); my $ret = run_cmd(@cmd_pipe); unless(defined($ret)) { $send_receive_error = 1; $ret = $err; # print the errors below } if(defined($ret)) { # NOTE: if "btrfs send" fails, "btrfs receive" returns 0! so we need to parse the output... foreach(split("\n", $ret)) { if(/^ERROR: /) { ERROR $'; $send_receive_error = 1; } elsif(/^WARNING: /) { WARN "[btrfs send/receive] (send=$snapshot_path, receive=$target_path) $'"; } else { WARN "[btrfs send/receive] (send=$snapshot_path, receive=$target_path) $_" if($send_receive_error); } } } end_transaction("send-receive", ($dryrun ? "DRYRUN" : ($send_receive_error ? "ERROR" : "success"))); if($send_receive_error) { ERROR "Failed to send/receive btrfs subvolume: $snapshot->{PRINT} " . ($parent_path ? "[$parent_path]" : "") . " -> $target->{PRINT}"; # NOTE: btrfs-progs v3.19.1 does not delete garbled received subvolume, # we need to do this by hand. # TODO: remove this as soon as btrfs-progs handle receive errors correctly. DEBUG "send/received failed, deleting (possibly present and garbled) received subvolume: $vol_received->{PRINT}"; my $ret = btrfs_subvolume_delete($vol_received, commit => "after", type => "delete_garbled"); if(defined($ret)) { WARN "Deleted partially received (garbled) subvolume: $vol_received->{PRINT}"; } else { WARN "Deletion of partially received (garbled) subvolume failed, assuming clean environment: $vol_received->{PRINT}"; } return undef; } return 1; } sub btrfs_send_to_file($$$$;@) { my $snapshot = shift || die; my $target = shift || die; my $parent = shift; my $ret_vol_received = shift; my %opts = @_; my $snapshot_path = $snapshot->{PATH} // die; my $target_path = $target->{PATH} // die; my $parent_path = $parent ? $parent->{PATH} : undef; my $parent_uuid = $parent ? $parent->{uuid} : undef ; my $received_uuid = $snapshot->{uuid}; $received_uuid = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" if((not $received_uuid) && $dryrun); die unless($received_uuid); die if($parent && !$parent_uuid); my $target_filename = $snapshot->{NAME} || die; $target_filename .= "--$received_uuid"; $target_filename .= '@' . $parent_uuid if($parent_uuid); $target_filename .= ".btrfs"; my %compress = ( gzip => { name => 'gzip' , cmd => [ 'gzip' ], postfix => '.gz', level_min => 1, level_max => 9 }, bzip2 => { name => 'bzip2', cmd => [ 'bzip2' ], postfix => '.bz2', level_min => 1, level_max => 9 }, xz => { name => 'xz' , cmd => [ 'xz' ], postfix => '.xz', level_min => 0, level_max => 9, threads => '--threads=' }, ); my @send_options; push(@send_options, '-v') if($loglevel >= 3); push(@send_options, '-p', $parent_path) if($parent_path); my @cmd_pipe; push @cmd_pipe, { cmd => [ qw(btrfs send), @send_options, $snapshot_path ], rsh => $snapshot->{RSH}, name => "btrfs send", }; push @cmd_pipe, { cmd => [ '/usr/bin/pv', '-trab' ], } if($show_progress); if($opts{compress}) { die unless($compress{$opts{compress}}); $target_filename .= $compress{$opts{compress}}->{postfix}; my $compress_cmd = $compress{$opts{compress}}->{cmd}; if(defined($opts{compress_level}) && ($opts{compress_level} ne "default")) { my $compress_level = $opts{compress_level}; if($compress_level < $compress{$opts{compress}}->{level_min}) { WARN "Compression level (raw_target_compress_level) capped to minimum for '$opts{compress}': $compress{$opts{compress}}->{level_min}"; $compress_level = $compress{$opts{compress}}->{level_min}; } if($compress_level > $compress{$opts{compress}}->{level_max}) { WARN "Compression level (raw_target_compress_level) capped to maximum for '$opts{compress}': $compress{$opts{compress}}->{level_max}"; $compress_level = $compress{$opts{compress}}->{level_max}; } push @$compress_cmd, '-' . $compress_level; } if(defined($opts{compress_threads}) && ($opts{compress_threads} ne "default")) { my $thread_opt = $compress{$opts{compress}}->{threads}; if($thread_opt) { push @$compress_cmd, $thread_opt . $opts{compress_threads}; } else { WARN "Threading (raw_target_compress_threads) is not supported for '$opts{compress}', ignoring"; } } push @cmd_pipe, { cmd => $compress_cmd, name => $compress{$opts{compress}}->{name} }; } if($opts{encrypt}) { die unless($opts{encrypt}->{type} eq "gpg"); $target_filename .= '.gpg'; my @gpg_options = ( '--batch', '--no-tty', '--trust-model', 'always' ); push(@gpg_options, ( '--no-default-keyring', '--keyring', $opts{encrypt}->{keyring} )) if($opts{encrypt}->{keyring}); push(@gpg_options, ( '--default-recipient', $opts{encrypt}->{recipient} )) if($opts{encrypt}->{recipient}); push @cmd_pipe, { cmd => [ 'gpg', @gpg_options, '--encrypt' ], name => 'gpg', }; } push @cmd_pipe, { cmd => [ 'dd', 'status=none', "of=$target_path/$target_filename" ], rsh => $target->{RSH}, name => 'dd', }; my $vol_received = vinfo_child($target, $target_filename); $$ret_vol_received = $vol_received if(ref $ret_vol_received); INFO ">>> $vol_received->{PRINT}"; print STDOUT "Receiving subvol (raw): $vol_received->{PRINT}\n" if($show_progress && (not $dryrun)); DEBUG "[btrfs] send-to-file" . ($parent ? " (incremental)" : " (complete)") . ":"; DEBUG "[btrfs] source: $snapshot->{PRINT}"; DEBUG "[btrfs] parent: $parent->{PRINT}" if($parent); DEBUG "[btrfs] target: $target->{PRINT}"; start_transaction("send-to-raw", vinfo_prefixed_keys("target", $vol_received), vinfo_prefixed_keys("source", $snapshot), vinfo_prefixed_keys("parent", $parent), ); my $ret = run_cmd(@cmd_pipe); if(defined($ret)) { # Test target file for "exists and size > 0" after writing, # as we can not rely on the exit status of 'dd' DEBUG "Testing target file (non-zero size): $target->{PRINT}"; $ret = run_cmd({ cmd => ['test', '-s', "$target_path/$target_filename"], rsh => $target->{RSH}, name => "test", }); } end_transaction("send-to-raw", ($dryrun ? "DRYRUN" : (defined($ret) ? "success" : "ERROR"))); unless(defined($ret)) { ERROR "Failed to send btrfs subvolume to raw file: $snapshot->{PRINT} " . ($parent_path ? "[$parent_path]" : "") . " -> $vol_received->{PRINT}"; return undef; } return 1; } sub btr_tree($) { my $vol = shift; # return cached info if present return $root_tree_cache{$vol->{URL}} if($vol->{is_root} && $root_tree_cache{$vol->{URL}}); return $root_tree_cache{$vol->{REAL_URL}} if($vol->{is_root} && $vol->{REAL_URL} && $root_tree_cache{$vol->{REAL_URL}}); return $uuid_info{$vol->{uuid}} if($vol->{uuid} && $uuid_info{$vol->{uuid}}); # man btrfs-subvolume: # Also every btrfs filesystem has a default subvolume as its initially # top-level subvolume, whose subvolume id is 5(FS_TREE). my %tree = ( id => 5, SUBTREE => {} ); my %id = ( 5 => \%tree ); my $subvol_list = btrfs_subvolume_list($vol); return undef unless(ref($subvol_list) eq "ARRAY"); TRACE "btr_tree: processing subvolume list of: $vol->{PRINT}"; foreach my $node (@$subvol_list) { $node->{SUBTREE} //= {}; $id{$node->{id}} = $node; $uuid_info{$node->{uuid}} = $node; } # note: it is possible that id < top_level, e.g. after restoring foreach my $node (@$subvol_list) { # set SUBTREE / TOP_LEVEL node die unless exists($id{$node->{top_level}}); my $top_level = $id{$node->{top_level}}; die if exists($top_level->{SUBTREE}->{$node->{id}}); $top_level->{SUBTREE}->{$node->{id}} = $node; $node->{TOP_LEVEL} = $top_level; # "path" always starts with set REL_PATH my $rel_path = $node->{path}; if($node->{top_level} != 5) { die unless($rel_path =~ s/^$top_level->{path}\///); } $node->{REL_PATH} = $rel_path; # relative to {TOP_LEVEL}->{path} } if($vol->{is_root}) { $root_tree_cache{$vol->{URL}} = \%tree; $root_tree_cache{$vol->{REAL_URL}} = \%tree if($vol->{REAL_URL}); return \%tree; } else { die unless($uuid_info{$vol->{uuid}}); return $uuid_info{$vol->{uuid}}; } } sub _subtree_list { my $tree = shift; my $list = shift // []; my $prefix = shift // ""; $tree = $tree->{SUBTREE}; foreach(values %$tree) { my $path = $prefix . $_->{REL_PATH}; push(@$list, { SUBVOL_PATH => $path, node => $_, }); _subtree_list($_, $list, $path . '/'); } return $list; } sub vinfo_subvol_list($) { my $vol = shift || die; return $vol->{SUBVOL_LIST} if($vol->{SUBVOL_LIST}); my $tree_root = btr_tree($vol); return undef unless($tree_root); # recurse into $tree_root, returns list of href: { SUBVOL_PATH, node } my $list = _subtree_list($tree_root); # return a hash of relative subvolume path my %ret; foreach(@$list) { my $subvol_path = $_->{SUBVOL_PATH}; die if exists $ret{$subvol_path}; my $subvol = vinfo_child($vol, $subvol_path); vinfo_set_detail($subvol, $_->{node}); $uuid_fs_map{$subvol->{uuid}}->{$subvol->{URL}} = $subvol; $ret{$subvol_path} = $subvol; } DEBUG "Found " . scalar(keys %ret) . " subvolume children of: $vol->{PRINT}"; TRACE(Data::Dumper->Dump([\%ret], ["vinfo_subvol_list{$vol->{URL}}"])); $vol->{SUBVOL_LIST} = \%ret; return \%ret; } # returns list of uuids for ALL subvolumes in the btrfs filesystem of $vol sub vinfo_fs_list($) { my $vol = shift || die; my $tree_root = btr_tree($vol); return undef unless($tree_root); $tree_root = $tree_root->{TOP_LEVEL} while($tree_root->{TOP_LEVEL}); my $list = _subtree_list($tree_root); my %ret = map { $_->{node}->{uuid} => $_->{node} } @$list; return \%ret; } sub vinfo_subvol($$) { my $vol = shift || die; my $rel_path = shift // die; my $subvols = vinfo_subvol_list($vol); return $subvols->{$rel_path}; } # sets $config->{ABORTED} on failure # sets $config->{SUBVOL_RECEIVED} sub macro_send_receive($@) { my $config_target = shift || die; my %info = @_; my $snapshot = $info{snapshot} || die; my $target = $info{target} || die; my $parent = $info{parent}; my $target_type = $config_target->{target_type} || die; my $incremental = config_key($config_target, "incremental"); INFO "Receiving from snapshot: $snapshot->{PRINT}"; # check for existing target subvolume if(my $err_vol = vinfo_subvol($target, $snapshot->{NAME})) { ABORTED($config_target, "Target subvolume \"$err_vol->{PRINT}\" already exists"); $config_target->{UNRECOVERABLE} = "Please delete stray subvolume (\"btrbk clean\"): $err_vol->{PRINT}"; ERROR $config_target->{ABORTED} . ", aborting send/receive of: $snapshot->{PRINT}"; ERROR $config_target->{UNRECOVERABLE}; $info{ERROR} = 1; return undef; } if($incremental) { # create backup from latest common if($parent) { INFO "Incremental from parent snapshot: $parent->{PRINT}"; } elsif($incremental ne "strict") { INFO "No common parent subvolume present, creating full backup"; } else { WARN "Backup to $target->{PRINT} failed: no common parent subvolume found, and option \"incremental\" is set to \"strict\""; $info{ERROR} = 1; ABORTED($config_target, "No common parent subvolume found, and option \"incremental\" is set to \"strict\""); return undef; } } else { INFO "Option \"incremental\" is not set, creating full backup"; $parent = undef; delete $info{parent}; } my $ret; my $vol_received; if($target_type eq "send-receive") { $ret = btrfs_send_receive($snapshot, $target, $parent, \$vol_received); ABORTED($config_target, "Failed to send/receive subvolume") unless($ret); } elsif($target_type eq "raw") { unless($dryrun) { # make sure we know the snapshot uuid unless($snapshot->{uuid}) { DEBUG "Fetching uuid of new snapshot: $snapshot->{PRINT}"; my $detail = btrfs_subvolume_detail($snapshot); die unless($detail->{uuid}); vinfo_set_detail($snapshot, { uuid => $detail->{uuid} }); } } my $encrypt = undef; my $encrypt_type = config_key($config_target, "raw_target_encrypt"); if($encrypt_type) { die unless($encrypt_type eq "gpg"); $encrypt = { type => $encrypt_type, keyring => config_key($config_target, "gpg_keyring"), recipient => config_key($config_target, "gpg_recipient"), } } $ret = btrfs_send_to_file($snapshot, $target, $parent, \$vol_received, compress => config_key($config_target, "raw_target_compress"), compress_level => config_key($config_target, "raw_target_compress_level"), compress_threads => config_key($config_target, "raw_target_compress_threads"), encrypt => $encrypt ); ABORTED($config_target, "Failed to send subvolume to raw file") unless($ret); } else { die "Illegal target type \"$target_type\""; } # add info to $config->{SUBVOL_RECEIVED} $info{received_type} = $target_type || die; $info{received_subvolume} = $vol_received || die; $config_target->{SUBVOL_RECEIVED} //= []; push(@{$config_target->{SUBVOL_RECEIVED}}, \%info); unless($ret) { $info{ERROR} = 1; return undef; } return 1; } # returns { btrbk_date => [ yyyy, mm, dd, hh, mm, ] } or undef # fixed array length of 6, all individually defaulting to 0 sub parse_filename($$;$) { my $file = shift; my $name_match = shift; my $raw_format = shift || 0; my %raw_info; if($raw_format) { return undef unless($file =~ /^\Q$name_match\E$timestamp_postfix_match$raw_postfix_match$/); die unless($+{YYYY} && $+{MM} && $+{DD}); return { btrbk_date => [ $+{YYYY}, $+{MM}, $+{DD}, ($+{hh} // 0), ($+{mm} // 0), ($+{NN} // 0) ], received_uuid => $+{received_uuid} // die, REMOTE_PARENT_UUID => $+{parent_uuid} // '-', ENCRYPT => $+{encrypt} // "", COMPRESS => $+{compress} // "", }; } else { return undef unless($file =~ /^\Q$name_match\E$timestamp_postfix_match$/); die unless($+{YYYY} && $+{MM} && $+{DD}); return { btrbk_date => [ $+{YYYY}, $+{MM}, $+{DD}, ($+{hh} // 0), ($+{mm} // 0), ($+{NN} // 0) ] }; } } sub get_snapshot_children($$) { my $sroot = shift || die; my $svol = shift // die; my @ret; my $sroot_subvols = vinfo_subvol_list($sroot); foreach (values %$sroot_subvols) { next unless($_->{parent_uuid} eq $svol->{uuid}); TRACE "get_snapshot_children: found: $_->{PRINT}"; push(@ret, $_); } DEBUG "Found " . scalar(@ret) . " snapshot children of: $svol->{PRINT}"; return @ret; } sub get_receive_targets($$) { my $droot = shift || die; my $src_vol = shift || die; my $droot_subvols = vinfo_subvol_list($droot); my @ret; if($droot->{BTRFS_PROGS_COMPAT}) { # guess matches by subvolume name (node->received_uuid is not available if BTRFS_PROGS_COMPAT is set) DEBUG "Fallback to compatibility mode (get_receive_targets)"; foreach my $target (values %$droot_subvols) { if($target->{NAME} eq $src_vol->{NAME}) { TRACE "get_receive_targets: by-name: Found receive target: $target->{SUBVOL_PATH}"; push(@ret, $target); } } } else { # find matches by comparing uuid / received_uuid my $uuid = $src_vol->{uuid}; die("subvolume info not present: $uuid") unless($uuid_info{$uuid}); foreach (values %$droot_subvols) { next unless($_->{received_uuid} eq $uuid); TRACE "get_receive_targets: by-uuid: Found receive target: $_->{SUBVOL_PATH}"; push(@ret, $_); } } DEBUG "Found " . scalar(@ret) . " receive targets in \"$droot->{PRINT}/\" for: $src_vol->{PRINT}"; return @ret; } sub get_latest_common($$$;$) { my $sroot = shift || die; my $svol = shift // die; my $droot = shift || die; my $threshold_gen = shift; # skip all snapshot children with generation (cgen) >= $threshold_gen die("source subvolume info not present: $sroot->{URL}") unless($sroot->{URL}); die("target subvolume info not present: $droot->{URL}") unless($droot->{URL}); my $debug_src = $svol->{URL}; $debug_src .= "#" . $threshold_gen if($threshold_gen); # sort children of svol descending by generation foreach my $child (sort { $b->{cgen} <=> $a->{cgen} } get_snapshot_children($sroot, $svol)) { TRACE "get_latest_common: checking source snapshot: $child->{SUBVOL_PATH}"; if($threshold_gen && ($child->{cgen} >= $threshold_gen)) { TRACE "get_latest_common: skipped gen=$child->{cgen} >= $threshold_gen: $child->{SUBVOL_PATH}"; next; } if($child->{RECEIVE_TARGET_PRESENT} && ($child->{RECEIVE_TARGET_PRESENT} eq $droot->{URL})) { # little hack to keep track of previously received subvolumes DEBUG("Latest common snapshots for: $debug_src: src=$child->{PRINT} target="); return ($child, undef); } foreach (get_receive_targets($droot, $child)) { TRACE "get_latest_common: found receive target: $_->{PRINT}"; DEBUG("Latest common snapshots for: $debug_src: src=$child->{PRINT} target=$_->{PRINT}"); return ($child, $_); } TRACE "get_latest_common: no matching targets found for: $child->{PRINT}"; } DEBUG("No common snapshots of \"$debug_src\" found in src=\"$sroot->{PRINT}/\", target=\"$droot->{PRINT}/\""); return (undef, undef); } sub get_latest_snapshot_child($$) { my $sroot = shift || die; my $svol = shift // die; my $latest = undef; my $gen = -1; foreach (get_snapshot_children($sroot, $svol)) { if($_->{cgen} > $gen) { $latest = $_; $gen = $_->{cgen}; } } if($latest) { DEBUG "Latest snapshot child for \"$svol->{PRINT}#$svol->{gen}\" is: $latest->{PRINT}#$latest->{cgen}"; } else { DEBUG "No latest snapshots found for: $svol->{PRINT}"; } return $latest; } sub _origin_tree { my $prefix = shift; my $uuid = shift; my $lines = shift; my $node = $uuid_info{$uuid}; unless($node) { push(@$lines, ["$prefix", $uuid]); return 0; } if($uuid_fs_map{$uuid}) { push(@$lines, ["$prefix" . join(" === ", sort map { $_->{PRINT} } values %{$uuid_fs_map{$uuid}}), $uuid]); } else { push(@$lines, ["$prefix/$node->{path}", $uuid]); } $prefix =~ s/./ /g; if($node->{received_uuid}) { if($node->{received_uuid} ne '-') { _origin_tree("${prefix}^-- ", $node->{received_uuid}, $lines); } } else { # printed if "btrfs_progs_compat" is set push(@$lines, ["$prefix^-- ", $uuid]); } if($node->{parent_uuid} ne '-') { _origin_tree("${prefix}", $node->{parent_uuid}, $lines); } } sub schedule(@) { my %args = @_; my $schedule = $args{schedule} || die; my @today = @{$args{today}}; my $preserve_day_of_week = $args{preserve_day_of_week} || die; my $preserve_daily = $args{preserve_daily} // die; my $preserve_weekly = $args{preserve_weekly} // die; my $preserve_monthly = $args{preserve_monthly} // die; my $preserve_latest = $args{preserve_latest} || 0; my $results_list = $args{results}; my $result_hints = $args{result_hints} // {}; DEBUG "Filter scheme: preserving all within $preserve_daily days"; DEBUG "Filter scheme: preserving first in week (starting on $preserve_day_of_week), for $preserve_weekly weeks"; DEBUG "Filter scheme: preserving last weekly of month, for $preserve_monthly months"; # sort the schedule, ascending by date my @sorted_schedule = sort { ($a->{btrbk_date}->[0] <=> $b->{btrbk_date}->[0]) || ($a->{btrbk_date}->[1] <=> $b->{btrbk_date}->[1]) || ($a->{btrbk_date}->[2] <=> $b->{btrbk_date}->[2]) || ($a->{btrbk_date}->[3] <=> $b->{btrbk_date}->[3]) || ($a->{btrbk_date}->[4] <=> $b->{btrbk_date}->[4]) || ($a->{btrbk_date}->[5] <=> $b->{btrbk_date}->[5]) } @$schedule; # first, do our calendar calculations # note: our week starts on $preserve_day_of_week my $delta_days_to_eow_from_today = $day_of_week_map{$preserve_day_of_week} - Day_of_Week(@today) - 1; $delta_days_to_eow_from_today = $delta_days_to_eow_from_today + 7 if($delta_days_to_eow_from_today < 0); TRACE "last day before next $preserve_day_of_week is in $delta_days_to_eow_from_today days"; foreach my $href (@sorted_schedule) { my @date = @{$href->{btrbk_date}}[0..2]; # Date::Calc takes: @date = ( yy, mm, dd ) my $delta_days = Delta_Days(@date, @today); my $delta_days_to_eow = $delta_days + $delta_days_to_eow_from_today; { use integer; # do integer arithmetics $href->{delta_days} = $delta_days; $href->{delta_weeks} = $delta_days_to_eow / 7; $href->{err_days} = 6 - ( $delta_days_to_eow % 7 ); $href->{delta_months} = ($today[0] - $date[0]) * 12 + ($today[1] - $date[1]); $href->{month} = "$date[0]-$date[1]"; } } if($preserve_latest && (scalar @sorted_schedule)) { my $href = $sorted_schedule[-1]; $href->{preserve} ||= $preserve_latest; } # filter daily, weekly, monthly my %first_in_delta_weeks; my %last_weekly_in_delta_months; foreach my $href (@sorted_schedule) { if($preserve_daily && (($preserve_daily eq "all") || ($href->{delta_days} <= $preserve_daily))) { $href->{preserve} ||= "preserved daily: $href->{delta_days} days ago"; } $first_in_delta_weeks{$href->{delta_weeks}} //= $href; } foreach (sort {$b <=> $a} keys %first_in_delta_weeks) { my $href = $first_in_delta_weeks{$_} || die; if($preserve_weekly && (($preserve_weekly eq "all") || ($href->{delta_weeks} <= $preserve_weekly))) { $href->{preserve} ||= "preserved weekly: $href->{delta_weeks} weeks ago, " . ($href->{err_days} ? "+$href->{err_days} days after " : "on ") . "$preserve_day_of_week"; } $last_weekly_in_delta_months{$href->{delta_months}} = $href; } foreach (sort {$b <=> $a} keys %last_weekly_in_delta_months) { my $href = $last_weekly_in_delta_months{$_} || die; if($preserve_monthly && (($preserve_monthly eq "all") || ($href->{delta_months} <= $preserve_monthly))) { $href->{preserve} ||= "preserved monthly: " . ($href->{err_days} ? "$href->{err_days} days after " : "") . "last $preserve_day_of_week of month $href->{month} (age: $href->{delta_months} months)"; } } # assemble results my @delete; my @preserve; my %preserve_matrix = ( d => $preserve_daily, w => $preserve_weekly, m => $preserve_monthly, dow => $preserve_day_of_week, ); my %result_base = ( %preserve_matrix, scheme => format_preserve_matrix(%preserve_matrix, format => "short"), %$result_hints, ); foreach my $href (@sorted_schedule) { if($href->{preserve}) { push(@preserve, $href->{value}); DEBUG "=== $href->{name}: $href->{preserve}" if($href->{name}); push @$results_list, { %result_base, # action => "preserve", reason => $href->{preserve}, value => $href->{value}, } if($results_list); } else { push(@delete, $href->{value}); DEBUG "<<< $href->{name}" if($href->{name}); push @$results_list, { %result_base, action => "delete", value => $href->{value}, } if($results_list);; } } DEBUG "Preserving " . @preserve . "/" . @$schedule . " items"; return (\@preserve, \@delete); } sub format_preserve_matrix(@) { my %args = @_; my $dow = $args{dow} // config_key($args{config}, "preserve_day_of_week"); my $d = $args{d} // config_key($args{config}, "$args{prefix}_preserve_daily"); my $w = $args{w} // config_key($args{config}, "$args{prefix}_preserve_weekly"); my $m = $args{m} // config_key($args{config}, "$args{prefix}_preserve_monthly"); my $format = $args{format} // "long"; $d =~ s/^all$/-1/; $w =~ s/^all$/-1/; $m =~ s/^all$/-1/; if($format eq "short") { # short format return sprintf("%2sd %2sw %2sm", $d, $w, $m); } # long format return sprintf("%2sd %2sw %2sm ($dow)", $d, $w, $m); } sub print_header(@) { my %args = @_; my $config = $args{config}; print "--------------------------------------------------------------------------------\n"; print "$args{title} ($version_info)\n\n"; if($args{time}) { print " Date: " . localtime($args{time}) . "\n"; } if($config) { print " Config: $config->{SRC_FILE}\n"; } if($dryrun) { print " Dryrun: YES\n"; } if($config && $config->{CMDLINE_FILTER_LIST}) { my @list = sort @{$config->{CMDLINE_FILTER_LIST}}; my @sorted = ( grep(/^group/, @list), grep(/^volume/, @list), grep(/^subvolume/, @list), grep(/^target/, @list) ); die unless(scalar(@list) == scalar(@sorted)); print " Filter: "; print join("\n ", @sorted); print "\n"; } if($args{info}) { print "\n" . join("\n", grep(defined, @{$args{info}})) . "\n"; } if($args{legend}) { print "\nLegend:\n "; print join("\n ", @{$args{legend}}); print "\n"; } print "--------------------------------------------------------------------------------\n"; } sub print_table($;$) { my $data = shift; my $spacing = shift // " "; my $maxlen = 0; foreach (@$data) { $maxlen = length($_->[0]) if($maxlen < length($_->[0])); } foreach (@$data) { print $_->[0] . ((' ' x ($maxlen - length($_->[0]))) . $spacing) . $_->[1] . "\n"; } } sub print_formatted(@) { my $format_key = shift || die; my $data = shift || die; my $default_format = "table"; my %args = @_; my $title = $args{title}; my $format = $args{output_format} || $output_format || $default_format; my $keys = $table_formats{$format_key}->{$format}; my $ralign = $table_formats{$format_key}->{RALIGN} // {}; my $fh = $args{outfile} // *STDOUT; my $table_spacing = 2; unless($keys) { WARN "Unsupported output format \"$format\", defaulting to \"$default_format\" format."; $keys = $table_formats{$format_key}->{$default_format} || die; $format = $default_format; } print $fh "$title\n" if($title); if($format eq "raw") { # output: key0="value0" key1="value1" ... foreach my $row (@$data) { print $fh "format=\"$format_key\" "; print $fh join(' ', map { "$_=\"" . ($row->{$_} // "") . "\""; } @$keys) . "\n"; } } elsif($format eq "tlog") { # output: value0 value1, ... unless($args{no_header}) { print $fh join(' ', @$keys) . "\n"; } foreach my $row (@$data) { print $fh join(' ', map { ((defined($row->{$_}) && ($_ eq "message")) ? '# ' : '') . ($row->{$_} // "-") } @$keys) . "\n"; } } else { # sanitize and calculate maxlen for each column # NOTE: this is destructive on data! my %maxlen; my @sane_data; foreach my $key (@$keys) { $maxlen{$key} = length($key); # initialize with size of key } foreach my $row (@$data) { foreach my $key (@$keys) { my $val = $row->{$key}; if(ref $val eq "ARRAY") { $val = join(',', @{$val}); } $val //= "-"; $val = "-" if($val eq ""); $row->{$key} = $val; # write back the sanitized value $maxlen{$key} = length($val) if($maxlen{$key} < length($val)); } } # print keys (headings) my $fill = 0; foreach (@$keys) { print $fh ' ' x $fill; $fill = $maxlen{$_} - length($_); if($ralign->{$_}) { print $fh ' ' x $fill; $fill = 0; } print $fh $_; $fill += $table_spacing; } print $fh "\n"; print $fh join(' ' x $table_spacing, map { '-' x ($maxlen{$_}) } @$keys) . "\n"; # print values foreach my $row (@$data) { my $fill = 0; foreach (@$keys) { my $val = $row->{$_}; print $fh ' ' x $fill; $fill = $maxlen{$_} - length($val); if($ralign->{$_}) { print $fh ' ' x $fill; $fill = 0; } print $fh $val; $fill += $table_spacing; } print $fh "\n"; } } } sub exit_status($) { my $config = shift; foreach my $config_vol (@{$config->{VOLUME}}) { return 10 if($config_vol->{ABORTED} && ($config_vol->{ABORTED} ne "USER_SKIP")); foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { return 10 if($config_subvol->{ABORTED} && ($config_subvol->{ABORTED} ne "USER_SKIP")); foreach my $config_target (@{$config_subvol->{TARGET}}) { return 10 if($config_target->{ABORTED} && ($config_target->{ABORTED} ne "USER_SKIP")); } } } return 0; } MAIN: { # set PATH instead of using absolute "/sbin/btrfs" (for now), as # different distros (and even different versions of btrfs-progs) # install the "btrfs" executable to different locations. $ENV{PATH} = '/sbin:/bin:/usr/sbin:/usr/bin'; Getopt::Long::Configure qw(gnu_getopt); $Data::Dumper::Sortkeys = 1; my $start_time = time; my @today_and_now = Today_and_Now(); my @today = @today_and_now[0..2]; my ($config_cmdline, $quiet, $verbose, $preserve_backups, $resume_only); unless(GetOptions( 'help|h' => sub { VERSION_MESSAGE(); HELP_MESSAGE(0); exit 0; }, 'version' => sub { VERSION_MESSAGE(); exit 0; }, 'config|c=s' => \$config_cmdline, 'dry-run|n' => \$dryrun, 'preserve|p' => \$preserve_backups, 'resume-only|r' => \$resume_only, 'quiet|q' => \$quiet, 'verbose|v' => sub { $loglevel = 2; }, 'loglevel|l=s' => \$loglevel, 'progress' => \$show_progress, 'table|t' => sub { $output_format = "table" }, 'format=s' => \$output_format, # 'override=s' => \%config_override, # e.g. --override=incremental=no )) { VERSION_MESSAGE(); HELP_MESSAGE(0); exit 2; } my $command = shift @ARGV; unless($command) { VERSION_MESSAGE(); HELP_MESSAGE(0); exit 2; } # assign command line options if (lc($loglevel) eq "warn") { $loglevel = 1; } elsif(lc($loglevel) eq "info") { $loglevel = 2; } elsif(lc($loglevel) eq "debug") { $loglevel = 3; } elsif(lc($loglevel) eq "trace") { $loglevel = 4; } elsif($loglevel =~ /^[0-9]+$/) { ; } else { $loglevel = 1; } @config_src = ( $config_cmdline ) if($config_cmdline); # check command line options if($show_progress && (not -e '/usr/bin/pv')) { WARN 'found option "--progress", but "pv" is not present: (please install "pv")'; $show_progress = 0; } my ($action_run, $action_usage, $action_resolve, $action_diff, $action_origin, $action_config_print, $action_list, $action_clean); my @filter_args; my $args_allow_group = 1; my $args_expected_min = 0; my $args_expected_max = 9999; if(($command eq "run") || ($command eq "dryrun")) { $action_run = 1; $dryrun = 1 if($command eq "dryrun"); $args_allow_group = 1; @filter_args = @ARGV; } elsif ($command eq "clean") { $action_clean = 1; @filter_args = @ARGV; } elsif ($command eq "usage") { $action_usage = 1; @filter_args = @ARGV; } elsif ($command eq "diff") { $action_diff = 1; $args_expected_min = $args_expected_max = 2; $args_allow_group = 0; @filter_args = @ARGV; } elsif ($command eq "origin") { $action_origin = 1; $args_expected_min = $args_expected_max = 1; $args_allow_group = 0; @filter_args = @ARGV; } elsif($command eq "list") { my $subcommand = shift @ARGV // ""; if(($subcommand eq "config") || ($subcommand eq "volume") || ($subcommand eq "source") || ($subcommand eq "target")) { $action_list = $subcommand; } elsif(($subcommand eq "snapshots") || ($subcommand eq "backups") || ($subcommand eq "latest")) { $action_resolve = $subcommand; } else { $action_list = "config"; unshift @ARGV, $subcommand if($subcommand ne ""); } @filter_args = @ARGV; } elsif($command eq "stats") { $action_resolve = "stats"; @filter_args = @ARGV; } elsif ($command eq "config") { my $subcommand = shift @ARGV // ""; @filter_args = @ARGV; if(($subcommand eq "print") || ($subcommand eq "print-all")) { $action_config_print = $subcommand; } elsif($subcommand eq "list") { $action_list = "config"; } else { ERROR "Unknown subcommand for \"config\" command: $subcommand"; HELP_MESSAGE(0); exit 2; } } else { ERROR "Unrecognized command: $command"; HELP_MESSAGE(0); exit 2; } if(($args_expected_min > scalar(@ARGV)) || ($args_expected_max < scalar(@ARGV))) { ERROR "Incorrect number of arguments"; HELP_MESSAGE(0); exit 2; } # input validation foreach (@filter_args) { s/\/+$//; # remove trailing slash if($args_allow_group && /^($group_match)$/) { # matches group $_ = $1; # untaint argument } elsif(/^(($ssh_prefix_match)?\/$file_match)$/) { # matches ssh statement or absolute file $_ = $1; # untaint argument } elsif(/^(?$ip_addr_match|$host_name_match):\/(?$file_match)$/) { # convert "my.host.com:/my/path" to ssh url $_ = "ssh://$+{host}/$+{file}"; } else { ERROR "Bad argument: not a subvolume" . ($args_allow_group ? "/group" : "") . " declaration: $_"; HELP_MESSAGE(0); exit 2; } } foreach my $key (keys %config_override) { my $value = check_config_option($key, $config_override{$key}, "root"); unless(defined($value)) { HELP_MESSAGE(0); exit 2; } $config_override{$key} = $value; } INFO "$version_info (" . localtime($start_time) . ")"; if($action_diff) { # # print snapshot diff # my $src_url = $filter_args[0] || die; my $target_url = $filter_args[1] || die; # FIXME: allow ssh:// src/dest (does not work since the configuration is not yet read). my $src_vol = vinfo($src_url, { CONTEXT => "cmdline" }); unless(vinfo_root($src_vol)) { ERROR "Failed to fetch subvolume detail for '$src_vol->{PRINT}'" . ($err ? ": $err" : ""); exit 1; } if($src_vol->{is_root}) { ERROR "Subvolume at \"$src_url\" is btrfs root!"; exit 1; } unless($src_vol->{cgen}) { ERROR "Subvolume at \"$src_url\" does not provide cgen"; exit 1; } my $target_vol = vinfo($target_url, { CONTEXT => "cmdline" }); unless(vinfo_root($target_vol)) { ERROR "Failed to fetch subvolume detail for '$target_vol->{PRINT}'" . ($err ? ": $err" : ""); exit 1; } unless($target_vol->{cgen}) { ERROR "Subvolume at \"$target_url\" does not provide cgen"; exit 1; } my $uuid_list = vinfo_fs_list($src_vol); unless($uuid_list->{$target_vol->{uuid}}) { ERROR "Target subvolume is not on the same btrfs filesystem!"; exit 1; } my $lastgen; # check if given src and target share same parent if($src_vol->{parent_uuid} eq $target_vol->{uuid}) { DEBUG "target subvolume is direct parent of source subvolume"; } elsif($src_vol->{parent_uuid} eq $target_vol->{parent_uuid}) { DEBUG "target subvolume and source subvolume share same parent"; } else { # TODO: this rule only applies to snapshots. find a way to distinguish snapshots from received backups # ERROR "Subvolumes \"$target_url\" and \"$src_url\" do not share the same parents"; # exit 1; } # NOTE: in some cases "cgen" differs from "gen", even for read-only snapshots (observed: gen=cgen+1) $lastgen = $src_vol->{cgen} + 1; # dump files, sorted and unique my $ret = btrfs_subvolume_find_new($target_vol, $lastgen); exit 1 unless(ref($ret)); print_header(title => "Subvolume Diff", time => $start_time, info => [ "Showing changed files for subvolume:", " $target_vol->{PRINT} (gen=$target_vol->{gen})", "", "Starting at creation generation of subvolume:", " $src_vol->{PRINT} (cgen=$src_vol->{cgen})", "", "This will show all files modified within generation range: [$lastgen..$target_vol->{gen}]", "Newest file generation (transid marker) was: $ret->{transid_marker}", ($ret->{parse_errors} ? "Parse errors: $ret->{parse_errors}" : undef), ], legend => [ "+.. file accessed at offset 0 (at least once)", ".c. flags COMPRESS or COMPRESS|INLINE set (at least once)", "..i flags INLINE or COMPRESS|INLINE set (at least once)", " file was modified in generations", " file was modified for a total of bytes", ] ); my $files = $ret->{files}; # calculate the character offsets my $len_charlen = 0; my $gen_charlen = 0; foreach (values %$files) { my $len = length($_->{len}); my $gen = length(scalar(keys(%{$_->{gen}}))); $len_charlen = $len if($len > $len_charlen); $gen_charlen = $gen if($gen > $gen_charlen); } # finally print the output foreach my $name (sort keys %$files) { print ($files->{$name}->{new} ? '+' : '.'); print ($files->{$name}->{flags}->{compress} ? 'c' : '.'); print ($files->{$name}->{flags}->{inline} ? 'i' : '.'); # make nice table my $gens = scalar(keys(%{$files->{$name}->{gen}})); my $len = $files->{$name}->{len}; print " " . (' ' x ($gen_charlen - length($gens))) . $gens; print " " . (' ' x ($len_charlen - length($len))) . $len; print " $name\n"; } exit 0; } # # parse config file # my $config = parse_config(@config_src); unless($config) { ERROR "Failed to parse configuration file"; exit 2; } unless(ref($config->{VOLUME}) eq "ARRAY") { ERROR "No volumes defined in configuration file"; exit 2; } # # open transaction log # if(($action_run || $action_clean) && (not $dryrun) && config_key($config, "transaction_log")) { init_transaction_log(config_key($config, "transaction_log")); } action("startup", status => "v$VERSION", message => "$version_info"); # # filter subvolumes matching command line arguments # if(($action_run || $action_clean || $action_resolve || $action_usage || $action_list || $action_config_print) && scalar(@filter_args)) { my %match; foreach my $config_vol (@{$config->{VOLUME}}) { my $vol_url = $config_vol->{url} // die; my $found_vol = 0; foreach my $filter (@filter_args) { if(($vol_url eq $filter) || (map { ($filter eq $_) || () } @{$config_vol->{group}})) { TRACE "filter argument \"$filter\" matches volume: $vol_url\n"; $match{$filter} = ($vol_url eq $filter) ? "volume=" . vinfo($vol_url, $config_vol)->{PRINT} : "group=$filter"; $found_vol = 1; # last; # need to cycle through all filter_args for correct %match } } next if($found_vol); my @filter_subvol; foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { my $subvol_url = $config_subvol->{url} // die; my $found_subvol = 0; foreach my $filter (@filter_args) { if(($subvol_url eq $filter) || (map { ($filter eq $_) || () } @{$config_subvol->{group}})) { TRACE "filter argument \"$filter\" matches subvolume: $subvol_url\n"; $match{$filter} = ($subvol_url eq $filter) ? "subvolume=" . vinfo($subvol_url, $config_subvol)->{PRINT} : "group=$filter"; $found_subvol = 1; $found_vol = 1; # last; # need to cycle through all filter_args for correct %match } } next if($found_subvol); my $snapshot_name = $config_subvol->{snapshot_name} // die; foreach my $config_target (@{$config_subvol->{TARGET}}) { my $target_url = $config_target->{url} // die; my $found_target = 0; foreach my $filter (@filter_args) { if(($filter eq $target_url) || ($filter eq "$target_url/$snapshot_name") || (map { ($filter eq $_) || () } @{$config_target->{group}})) { TRACE "filter argument \"$filter\" matches target: $target_url\n"; $match{$filter} = ($target_url eq $filter) ? "target=" . vinfo($target_url, $config_target)->{PRINT} : "group=$filter"; $found_target = 1; $found_subvol = 1; $found_vol = 1; # last; # need to cycle through all filter_args for correct %match } } unless($found_target) { DEBUG "No match on filter command line argument, skipping target: $target_url"; ABORTED($config_target, "USER_SKIP"); } } unless($found_subvol) { DEBUG "No match on filter command line argument, skipping subvolume: $subvol_url"; ABORTED($config_subvol, "USER_SKIP"); } } unless($found_vol) { DEBUG "No match on filter command line argument, skipping volume: $vol_url"; ABORTED($config_vol, "USER_SKIP"); } } # make sure all args have a match my @nomatch = map { $match{$_} ? () : $_ } @filter_args; if(@nomatch) { foreach(@nomatch) { ERROR "Command line argument does not match any volume, subvolume, target or group declaration: $_"; } exit 2; } $config->{CMDLINE_FILTER_LIST} = [ values %match ]; } if($action_usage) { # # print filesystem information # my @data; my %processed; foreach my $config_vol (@{$config->{VOLUME}}) { next if($config_vol->{ABORTED}); my $sroot = vinfo($config_vol->{url}, $config_vol); unless($processed{$sroot->{URL}}) { my $usage = btrfs_filesystem_usage($sroot) // {}; push @data, { %$usage, type => "source", vinfo_prefixed_keys("", $sroot), }; $processed{$sroot->{URL}} = 1; } } foreach my $config_vol (@{$config->{VOLUME}}) { next if($config_vol->{ABORTED}); my $sroot = vinfo($config_vol->{url}, $config_vol); foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { next if($config_subvol->{ABORTED}); foreach my $config_target (@{$config_subvol->{TARGET}}) { my $droot = vinfo($config_target->{url}, $config_target); unless($processed{$droot->{URL}}) { my $usage = btrfs_filesystem_usage($droot) // {}; push @data, { %$usage, type => "target", vinfo_prefixed_keys("", $droot), }; $processed{$droot->{URL}} = 1; } } } } print_formatted("usage", \@data); exit exit_status($config); } if($action_config_print) { my $resolve = ($action_config_print eq "print-all"); # # print configuration lines, machine readable # my @out; push @out, config_dump_keys($config, skip_defaults => 1); foreach my $config_vol (@{$config->{VOLUME}}) { next if($config_vol->{ABORTED}); my $sroot = vinfo($config_vol->{url}, $config_vol); push @out, "\nvolume $sroot->{URL}"; push @out, config_dump_keys($config_vol, prefix => "\t", resolve => $resolve); foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { next if($config_subvol->{ABORTED}); my $svol = vinfo_child($sroot, $config_subvol->{rel_path}); # push @out, "\n subvolume $svol->{URL}"; push @out, "\n\tsubvolume $svol->{SUBVOL_PATH}"; push @out, config_dump_keys($config_subvol, prefix => "\t\t", resolve => $resolve); foreach my $config_target (@{$config_subvol->{TARGET}}) { next if($config_target->{ABORTED}); my $droot = vinfo($config_target->{url}, $config_target); push @out, "\n\t\ttarget $config_target->{target_type} $droot->{URL}"; push @out, config_dump_keys($config_target, prefix => "\t\t\t", resolve => $resolve); } } } print_header(title => "Configuration Dump", config => $config, time => $start_time, ); print join("\n", @out) . "\n"; exit exit_status($config); } if($action_list) { my @vol_data; my @subvol_data; my @target_data; my @mixed_data; my %target_uniq; # # print configuration lines, machine readable # foreach my $config_vol (@{$config->{VOLUME}}) { next if($config_vol->{ABORTED}); my $sroot = vinfo($config_vol->{url}, $config_vol); my $volh = { vinfo_prefixed_keys("volume", $sroot) }; push @vol_data, $volh; foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { next if($config_subvol->{ABORTED}); my $svol = vinfo_child($sroot, $config_subvol->{rel_path}); my $subvolh = { %$volh, vinfo_prefixed_keys("source", $svol), snapshot_path => $sroot->{PATH} . (config_key($config_subvol, "snapshot_dir", prefix => '/') // ""), snapshot_name => config_key($config_subvol, "snapshot_name"), snapshot_preserve => format_preserve_matrix(config => $config_subvol, prefix => "snapshot"), }; push @subvol_data, $subvolh; my $found = 0; foreach my $config_target (@{$config_subvol->{TARGET}}) { next if($config_target->{ABORTED}); my $droot = vinfo($config_target->{url}, $config_target); my $targeth = { %$subvolh, vinfo_prefixed_keys("target", $droot), target_preserve => format_preserve_matrix(config => $config_target, prefix => "target"), }; if($action_list eq "target") { next if($target_uniq{$droot->{URL}}); $target_uniq{$droot->{URL}} = 1; } push @target_data, $targeth; push @mixed_data, $targeth; $found = 1; } # make sure the subvol is always printed (even if no targets around) push @mixed_data, $subvolh unless($found); } } if($action_list eq "volume") { print_formatted("list_volume", \@vol_data); } elsif($action_list eq "source") { print_formatted("list_source", \@subvol_data); } elsif($action_list eq "target") { print_formatted("list_target", \@target_data); } else { # default format print_formatted("list", \@mixed_data); } exit exit_status($config); } # # fill vinfo hash, basic checks on configuration # my %snapshot_check; my %backup_check; foreach my $config_vol (@{$config->{VOLUME}}) { next if($config_vol->{ABORTED}); my $sroot = vinfo($config_vol->{url}, $config_vol); unless(vinfo_root($sroot)) { ABORTED($config_vol, "Failed to fetch subvolume detail" . ($err ? ": $err" : "")); WARN "Skipping volume \"$sroot->{PRINT}\": $config_vol->{ABORTED}"; next; } $config_vol->{sroot} = $sroot; foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { next if($config_subvol->{ABORTED}); my $svol = vinfo_subvol($sroot, $config_subvol->{rel_path}); unless($svol) { # configured subvolume is not present in btrfs subvolume list. # try to read subvolume detail, as configured subvolume could be a symlink. DEBUG "Subvolume \"$config_subvol->{rel_path}\" not present in btrfs subvolume list for \"$sroot->{PRINT}\""; $svol = vinfo_child($sroot, $config_subvol->{rel_path}); my $detail = btrfs_subvolume_detail($svol); unless($detail) { ABORTED($config_subvol, "Failed to fetch subvolume detail" . ($err ? ": $err" : "")); WARN "Skipping subvolume \"$svol->{PRINT}\": $config_subvol->{ABORTED}"; next; } if($detail->{is_root}) { ABORTED($config_subvol, "Subvolume is btrfs root"); WARN "Skipping subvolume \"$svol->{PRINT}\": $config_subvol->{ABORTED}"; next; } if(grep { $_->{uuid} eq $detail->{uuid} } values %{vinfo_subvol_list($sroot)}) { vinfo_set_detail($svol, $uuid_info{$detail->{uuid}}); } else { ABORTED($config_subvol, "Not a child subvolume of: $sroot->{PRINT}"); WARN "Skipping subvolume \"$svol->{PRINT}\": $config_subvol->{ABORTED}"; next; } } $config_subvol->{svol} = $svol; # check for duplicate snapshot locations my $snapdir = config_key($config_subvol, "snapshot_dir", postfix => '/') // ""; my $snapshot_basename = config_key($config_subvol, "snapshot_name") // die; my $snapshot_target = "$sroot->{REAL_URL}/$snapdir$snapshot_basename"; if(my $prev = $snapshot_check{$snapshot_target}) { ERROR "Subvolume \"$prev\" and \"$svol->{PRINT}\" will create same snapshot: $snapshot_target"; ERROR "Please fix \"snapshot_name\" configuration options!"; exit 1; } $snapshot_check{$snapshot_target} = $svol->{PRINT}; foreach my $config_target (@{$config_subvol->{TARGET}}) { next if($config_target->{ABORTED}); my $droot = vinfo($config_target->{url}, $config_target); my $target_type = $config_target->{target_type} || die; if($target_type eq "send-receive") { unless(vinfo_root($droot)) { ABORTED($config_target, "Failed to fetch subvolume detail" . ($err ? ": $err" : "")); WARN "Skipping target \"$droot->{PRINT}\": $config_target->{ABORTED}"; next; } } elsif($target_type eq "raw") { DEBUG "Creating raw subvolume list: $droot->{PRINT}"; my $ret = run_cmd( # NOTE: check for file size >0, which causes bad (zero-sized) images to be resumed # TODO: fix btrfs_send_to_file() to never create bad images cmd => [ 'find', $droot->{PATH} . '/', '-maxdepth', '1', '-type', 'f', '-size', '+0' ], rsh => $droot->{RSH}, # note: use something like this to get the real (link resolved) path # cmd => [ "find", $droot->{PATH} . '/', "-maxdepth", "1", "-name", "$snapshot_basename.\*.raw\*", '-printf', '%f\0', '-exec', 'realpath', '-z', '{}', ';' ], non_destructive => 1, ); unless(defined($ret)) { ABORTED($config_target, "Failed to list files from: $droot->{PATH}"); WARN "Skipping target \"$droot->{PRINT}\": $config_target->{ABORTED}"; next; } my %subvol_list; my %child_uuid_list; foreach my $file (split("\n", $ret)) { unless($file =~ /^$file_match$/) { DEBUG "Skipping non-parseable file: \"$file\""; next; } unless($file =~ s/^\Q$droot->{PATH}\E\///) { ABORTED($config_target, "Unexpected result from 'find': file \"$file\" is not under \"$droot->{PATH}\""); last; } my $filename_info = parse_filename($file, $snapshot_basename, 1); unless($filename_info) { DEBUG "Skipping file (not btrbk raw): \"$file\""; next; } # Set btrfs subvolume information (received_uuid, parent_uuid) from filename info. # # NOTE: REMOTE_PARENT_UUID in $filename_info is the "parent of the source subvolume", NOT the # "parent of the received subvolume". my $subvol = vinfo_child($droot, $file); $filename_info->{uuid} = "FAKE_UUID:" . $subvol->{URL}; $filename_info->{parent_uuid} = '-'; # correct value gets inserted below vinfo_set_detail($subvol, $filename_info); $uuid_info{$subvol->{uuid}} = $subvol; $uuid_fs_map{$subvol->{uuid}}->{$subvol->{URL}} = $subvol; $subvol_list{$file} = $subvol; if($filename_info->{REMOTE_PARENT_UUID} ne '-') { $child_uuid_list{$filename_info->{REMOTE_PARENT_UUID}} //= []; push @{$child_uuid_list{$filename_info->{REMOTE_PARENT_UUID}}}, $subvol; } } if($config_target->{ABORTED}) { WARN "Skipping target \"$droot->{PRINT}\": $config_target->{ABORTED}"; next; } DEBUG "Found " . scalar(keys %subvol_list) . " raw subvolume backups of: $svol->{PRINT}"; $droot->{SUBVOL_LIST} = \%subvol_list; $droot->{REAL_URL} = $droot->{URL}; # ignore symlinks here # Make sure that incremental backup chains are never broken: foreach my $subvol (values %subvol_list) { # If restoring a backup from raw btrfs images (using "incremental yes|strict"): # "btrfs send -p parent source > svol.btrfs", the backups # on the target will get corrupted (unusable!) as soon as # an any files in the chain gets deleted. # # We need to make sure btrbk will NEVER delete those: # - svol.--.btrfs : root (full) image # - svol.--[@].btrfs : incremental image foreach my $child (@{$child_uuid_list{$subvol->{received_uuid}}}) { $child->{parent_uuid} = $subvol->{uuid}; DEBUG "Found parent/child partners, forcing preserve of: \"$subvol->{PRINT}\", \"$child->{PRINT}\""; $subvol->{FORCE_PRESERVE} = "preserve forced: parent of another raw target"; $child->{FORCE_PRESERVE} ||= "preserve forced: child of another raw target"; } # For now, always preserve all raw files. # TODO: remove this line as soon as incremental rotation is implemented. $subvol->{FORCE_PRESERVE} = "preserve forced: parent of another raw target"; } # TRACE(Data::Dumper->Dump([\%subvol_list], ["vinfo_raw_subvol_list{$droot}"])); } $config_target->{droot} = $droot; # check for duplicate snapshot locations my $snapshot_backup_target = "$droot->{REAL_URL}/$snapshot_basename"; if(my $prev = $backup_check{$snapshot_backup_target}) { ERROR "Subvolume \"$prev\" and \"$svol->{PRINT}\" will create same backup target: $snapshot_target"; ERROR "Please fix \"snapshot_name\" or \"target\" configuration options!"; exit 1; } $backup_check{$snapshot_backup_target} = $svol->{PRINT}; } } } if($action_origin) { # # print origin information # my $url = $filter_args[0] || die; my $dump_uuid = 0; my $vol = $vinfo_cache{$url}; unless($vol) { # specified volume is not in config DEBUG "Subvolume not parsed yet, fetching info: $url"; $vol = vinfo($url, { CONTEXT => "cmdline" }); unless(vinfo_root($vol)) { ERROR "Failed to fetch subvolume detail for: $url" . ($err ? ": $err" : ""); exit 1; } } if($vol->{is_root}) { ERROR "Subvolume is btrfs root: $url\n"; exit 1; } my $lines = []; _origin_tree("", $vol->{uuid}, $lines); print_header(title => "Origin Tree", config => $config, time => $start_time, legend => [ "^-- : received from subvolume", "newline : parent subvolume", "orphaned: subvolume uuid could not be resolved (probably deleted)", ] ); my $len = 0; if($dump_uuid) { $len = (length($_->[0]) > $len ? length($_->[0]) : $len) foreach(@$lines); } foreach(@$lines) { print "$_->[0]"; print ' ' x ($len - length($_->[0]) + 4) . "$_->[1]" if($dump_uuid); print "\n"; } exit 0; } if($action_resolve) { my @data; my @stats_data; my $stats_snapshots_total = 0; my $stats_backups_total = 0; my $stats_backups_total_incomplete = 0; my $stats_backups_total_orphaned = 0; my %droot_compat; if($action_resolve eq "snapshots") { # # print all snapshots and their receive targets # foreach my $config_vol (@{$config->{VOLUME}}) { next if($config_vol->{ABORTED}); my $sroot = $config_vol->{sroot} || die; foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { next if($config_subvol->{ABORTED}); my $svol = $config_subvol->{svol} || die; my $snapshot_name = config_key($config_subvol, "snapshot_name") // die; foreach my $snapshot (sort { $a->{cgen} cmp $b->{cgen} } get_snapshot_children($sroot, $svol)) { my $snapshot_data = { type => "snapshot", status => ($snapshot->{cgen} == $svol->{gen}) ? "up-to-date" : undef, vinfo_prefixed_keys("source", $svol), vinfo_prefixed_keys("snapshot", $snapshot), snapshot_name => $snapshot_name, }; my $found = 0; foreach my $config_target (@{$config_subvol->{TARGET}}) { next if($config_target->{ABORTED}); my $droot = $config_target->{droot} || die; $droot_compat{$droot->{URL}} = 1 if($droot->{BTRFS_PROGS_COMPAT}); foreach (sort { $a->{SUBVOL_PATH} cmp $b->{SUBVOL_PATH} } get_receive_targets($droot, $snapshot)) { push @data, { %$snapshot_data, type => "received", vinfo_prefixed_keys("target", $_), }; $found = 1; } } push @data, $snapshot_data unless($found); } } } } elsif(($action_resolve eq "backups") || ($action_resolve eq "stats")) { # # print all targets and their corresponding source snapshots # foreach my $config_vol (@{$config->{VOLUME}}) { next if($config_vol->{ABORTED}); my $sroot = $config_vol->{sroot} || die; foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { next if($config_subvol->{ABORTED}); my $svol = $config_subvol->{svol} || die; my $snapshot_name = config_key($config_subvol, "snapshot_name") // die; my @snapshot_children = get_snapshot_children($sroot, $svol); my $stats_snapshot_uptodate = ""; foreach my $snapshot (@snapshot_children) { if($snapshot->{cgen} == $svol->{gen}) { $stats_snapshot_uptodate = " (up-to-date)"; last; } } push @stats_data, [ $svol->{PRINT}, sprintf("%4u snapshots$stats_snapshot_uptodate", scalar(@snapshot_children)) ]; $stats_snapshots_total += scalar(@snapshot_children); # NOTE: this adds ALL snaphot children under $sroot (not only the ones created by btrbk!) foreach my $config_target (@{$config_subvol->{TARGET}}) { next if($config_target->{ABORTED}); my $droot = $config_target->{droot} || die; $droot_compat{$droot->{URL}} = 1 if($droot->{BTRFS_PROGS_COMPAT}); my $stats_received = 0; my $stats_orphaned = 0; my $stats_incomplete = 0; foreach my $target_vol (sort { $a->{SUBVOL_PATH} cmp $b->{SUBVOL_PATH} } values %{vinfo_subvol_list($droot)}) { my $parent_snapshot; my $incomplete_backup; foreach (@snapshot_children) { if($droot->{BTRFS_PROGS_COMPAT}) { if($_->{NAME} eq $target_vol->{NAME}) { $parent_snapshot = $_; last; } } else { if($target_vol->{received_uuid} eq '-') { # incomplete received (garbled) subvolumes have no received_uuid (as of btrfs-progs v4.3.1). # a subvolume in droot matching our naming is considered incomplete if received_uuid is not set! $parent_snapshot = undef; $incomplete_backup = 1; last; } if($_->{uuid} eq $target_vol->{received_uuid}) { $parent_snapshot = $_; last; } } } if($parent_snapshot) { $stats_received++; push @data, { type => "received", vinfo_prefixed_keys("target", $target_vol), vinfo_prefixed_keys("snapshot", $parent_snapshot), vinfo_prefixed_keys("source", $svol), status => ($parent_snapshot->{cgen} == $svol->{gen}) ? "up-to-date" : undef, }; } else { # don't display all subvolumes in $droot, only the ones matching snapshot_name if(parse_filename($target_vol->{SUBVOL_PATH}, $snapshot_name, ($config_target->{target_type} eq "raw"))) { if($incomplete_backup) { $stats_incomplete++; } else { $stats_orphaned++; } push @data, { type => "received", status => ($incomplete_backup ? "incomplete" : "orphaned"), vinfo_prefixed_keys("target", $target_vol), vinfo_prefixed_keys("source", $svol), }; } else { DEBUG "ignoring subvolume with non-matching snapshot_name"; } } } my $stats_total = $stats_received + $stats_incomplete + $stats_orphaned; $stats_backups_total += $stats_total; $stats_backups_total_incomplete += $stats_incomplete; $stats_backups_total_orphaned += $stats_orphaned; my @stats_detail; push @stats_detail, "$stats_orphaned orphaned" if($stats_orphaned); push @stats_detail, "$stats_incomplete incomplete" if($stats_incomplete); my $stats_detail_print = join(', ', @stats_detail); $stats_detail_print = " ($stats_detail_print)" if($stats_detail_print); push @stats_data, [ "^-- $droot->{PRINT}/$snapshot_name.*", sprintf("%4u backups$stats_detail_print", $stats_total) ]; } } } } elsif($action_resolve eq "latest") { # # print latest common # foreach my $config_vol (@{$config->{VOLUME}}) { next if($config_vol->{ABORTED}); my $sroot = $config_vol->{sroot} || die; foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { next if($config_subvol->{ABORTED}); my $svol = $config_subvol->{svol} || die; my $found = 0; foreach my $config_target (@{$config_subvol->{TARGET}}) { next if($config_target->{ABORTED}); my $droot = $config_target->{droot} || die; my ($latest_common_src, $latest_common_target) = get_latest_common($sroot, $svol, $droot); if ($latest_common_src && $latest_common_target) { push @data, { type => "latest_common", status => ($latest_common_src->{cgen} == $svol->{gen}) ? "up-to-date" : undef, vinfo_prefixed_keys("source", $svol), vinfo_prefixed_keys("snapshot", $latest_common_src), vinfo_prefixed_keys("target", $latest_common_target), }; $found = 1; } } unless($found) { my $latest_snapshot = get_latest_snapshot_child($sroot, $svol); push @data, { type => "latest_snapshot", status => ($latest_snapshot->{cgen} == $svol->{gen}) ? "up-to-date" : undef, vinfo_prefixed_keys("source", $svol), vinfo_prefixed_keys("snapshot", $latest_snapshot), # all unset if no $latest_snapshot }; } } } } else { die; } if(keys %droot_compat) { WARN "Received subvolumes (backups) are guessed by subvolume name for targets (btrfs_progs_compat=yes):"; WARN " - target: $_" foreach(sort keys %droot_compat); } if($action_resolve eq "stats") { print_header(title => "Statistics", config => $config, time => $start_time, ); print_table(\@stats_data, " "); print "\n"; my $stats_filter = $config->{CMDLINE_FILTER_LIST} ? join("; ", @{$config->{CMDLINE_FILTER_LIST}}) : ""; my @stats_total_detail; push @stats_total_detail, "$stats_backups_total_orphaned orphaned" if($stats_backups_total_orphaned); push @stats_total_detail, "$stats_backups_total_incomplete incomplete" if($stats_backups_total_incomplete); my $stats_total_detail_print = join(', ', @stats_total_detail); $stats_total_detail_print = " ($stats_total_detail_print)" if($stats_total_detail_print); print "Total" . ($stats_filter ? " ($stats_filter)" : "") . ":\n"; my $maxlen = ($stats_snapshots_total > $stats_backups_total) ? length($stats_snapshots_total) : length($stats_backups_total); printf("%" . $maxlen . "u snapshots\n", $stats_snapshots_total); printf("%" . $maxlen . "u backups$stats_total_detail_print\n", $stats_backups_total); } else { print_formatted("resolved", \@data); } exit exit_status($config); } if($action_clean) { # # identify and delete incomplete backups # my @out; foreach my $config_vol (@{$config->{VOLUME}}) { next if($config_vol->{ABORTED}); my $sroot = $config_vol->{sroot} || die; foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { next if($config_subvol->{ABORTED}); my $svol = $config_subvol->{svol} || die; my $snapshot_name = config_key($config_subvol, "snapshot_name") // die; foreach my $config_target (@{$config_subvol->{TARGET}}) { next if($config_target->{ABORTED}); my $droot = $config_target->{droot} || die; if($droot->{BTRFS_PROGS_COMPAT}) { WARN "btrfs_progs_compat is set, skipping cleanup of target: $droot->{PRINT}"; next; } INFO "Cleaning incomplete backups in: $droot->{PRINT}/$snapshot_name.*"; push @out, "$droot->{PRINT}/$snapshot_name.*"; my @delete; foreach my $target_vol (sort { $a->{SUBVOL_PATH} cmp $b->{SUBVOL_PATH} } values %{vinfo_subvol_list($droot)}) { # incomplete received (garbled) subvolumes have no received_uuid (as of btrfs-progs v4.3.1). # a subvolume in droot matching our naming is considered incomplete if received_uuid is not set! if(($target_vol->{received_uuid} eq '-') && parse_filename($target_vol->{SUBVOL_PATH}, $snapshot_name)) { DEBUG "Found incomplete target subvolume: $target_vol->{PRINT}"; push(@delete, $target_vol); push @out, "--- $target_vol->{PRINT}"; } } my $ret = btrfs_subvolume_delete(\@delete, commit => config_key($config_target, "btrfs_commit_delete"), type => "delete_garbled"); if(defined($ret)) { INFO "Deleted $ret incomplete backups in: $droot->{PRINT}/$snapshot_name.*"; $config_target->{SUBVOL_DELETED} = \@delete; } else { ABORTED($config_target, "Failed to delete incomplete target subvolume"); push @out, "!!! Target \"$droot->{PRINT}\" aborted: $config_target->{ABORTED}"; } push(@out, "") unless(scalar(@delete)); push(@out, ""); } } } my $exit_status = exit_status($config); my $time_elapsed = time - $start_time; INFO "Completed within: ${time_elapsed}s (" . localtime(time) . ")"; action("finished", status => $exit_status ? "partial" : "success", duration => $time_elapsed, message => $exit_status ? "At least one delete operation failed" : undef, ); close_transaction_log(); # # print summary # unless($quiet) { $output_format ||= "custom"; if($output_format eq "custom") { print_header(title => "Cleanup Summary", config => $config, time => $start_time, legend => [ "--- deleted subvolume (incomplete backup)", ], ); print join("\n", @out); if($dryrun) { print "\nNOTE: Dryrun was active, none of the operations above were actually executed!\n"; } } else { # print action log (without transaction start messages) my @data = grep { $_->{status} ne "starting" } @transaction_log; print_formatted("transaction", \@data, title => "TRANSACTION LOG"); } } exit $exit_status; } if($action_run) { if($resume_only) { INFO "Skipping snapshot creation (option \"-r\" present)"; } else { # # create snapshots # foreach my $config_vol (@{$config->{VOLUME}}) { next if($config_vol->{ABORTED}); my $sroot = $config_vol->{sroot} || die; foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { next if($config_subvol->{ABORTED}); my $svol = $config_subvol->{svol} || die; my $snapdir = config_key($config_subvol, "snapshot_dir", postfix => '/') // ""; my $snapshot_basename = config_key($config_subvol, "snapshot_name") // die; # check if we need to create a snapshot my $snapshot_create = config_key($config_subvol, "snapshot_create"); if(not $snapshot_create) { DEBUG "Snapshot creation disabled (snapshot_create=no)"; next; } elsif($snapshot_create eq "always") { DEBUG "Snapshot creation enabled (snapshot_create=always)"; } elsif($snapshot_create eq "onchange") { # check if latest snapshot is up-to-date with source subvolume (by generation) my $latest = get_latest_snapshot_child($sroot, $svol); if($latest) { if($latest->{cgen} == $svol->{gen}) { INFO "Snapshot creation skipped: snapshot_create=onchange, snapshot is up-to-date: $latest->{PRINT}"; $config_subvol->{SNAPSHOT_UP_TO_DATE} = $latest; next; } DEBUG "Snapshot creation enabled: snapshot_create=onchange, gen=$svol->{gen} > snapshot_cgen=$latest->{cgen}"; } else { DEBUG "Snapshot creation enabled: snapshot_create=onchange, no snapshots found"; } } elsif($snapshot_create eq "ondemand") { # check if at least one target is present if(scalar grep { not $_->{ABORTED} } @{$config_subvol->{TARGET}}) { DEBUG "Snapshot creation enabled (snapshot_create=ondemand): at least one target is present"; } else { INFO "Snapshot creation skipped: snapshot_create=ondemand, and no target is present for: $svol->{PRINT}"; next; } } else { die "illegal value for snapshot_create configuration option: $snapshot_create"; } # find unique snapshot name my $timestamp = ((config_key($config_subvol, "timestamp_format") eq "short") ? sprintf("%04d%02d%02d", @today) : sprintf("%04d%02d%02dT%02d%02d", @today_and_now[0..4])); my @unconfirmed_target_name; my @lookup = keys %{vinfo_subvol_list($sroot)}; @lookup = grep s/^\Q$snapdir\E// , @lookup; foreach my $config_target (@{$config_subvol->{TARGET}}) { if($config_target->{ABORTED}) { push(@unconfirmed_target_name, vinfo($config_target->{url}, $config_target)); next; } my $droot = $config_target->{droot} || die; push(@lookup, keys %{vinfo_subvol_list($droot)}); } @lookup = grep /^\Q$snapshot_basename.$timestamp\E(_[0-9]+)?$/ ,@lookup; TRACE "Present snapshot names for \"$svol->{PRINT}\": " . join(', ', @lookup); @lookup = map { /_([0-9]+)$/ ? $1 : 0 } @lookup; @lookup = sort { $b <=> $a } @lookup; my $postfix_counter = $lookup[0] // -1; $postfix_counter++; my $snapshot_name = $snapshot_basename . '.' . $timestamp . ($postfix_counter ? "_$postfix_counter" : ""); if(@unconfirmed_target_name) { INFO "Assuming non-present subvolume \"$snapshot_name\" in skipped targets: " . join(", ", map { "\"$_->{PRINT}\"" } @unconfirmed_target_name); } # finally create the snapshot INFO "Creating subvolume snapshot for: $svol->{PRINT}"; my $snapshot = vinfo_child($sroot, "$snapdir$snapshot_name"); if(btrfs_subvolume_snapshot($svol, $snapshot)) { $config_subvol->{SNAPSHOT} = $snapshot; } else { ABORTED($config_subvol, "Failed to create snapshot: $svol->{PRINT} -> $sroot->{PRINT}/$snapdir$snapshot_name"); WARN "Skipping subvolume section: $config_subvol->{ABORTED}"; } } } } # # create backups # foreach my $config_vol (@{$config->{VOLUME}}) { next if($config_vol->{ABORTED}); my $sroot = $config_vol->{sroot} || die; foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { next if($config_subvol->{ABORTED}); my $svol = $config_subvol->{svol} || die; my $snapdir = config_key($config_subvol, "snapshot_dir", postfix => '/') // ""; my $snapshot_basename = config_key($config_subvol, "snapshot_name") // die; my $preserve_latest = $config_subvol->{SNAPSHOT} ? 0 : 1; foreach my $config_target (@{$config_subvol->{TARGET}}) { next if($config_target->{ABORTED}); my $droot = $config_target->{droot} || die; # # resume missing backups (resume_missing) # if(config_key($config_target, "resume_missing")) { INFO "Checking for missing backups of subvolume \"$svol->{PRINT}\" in: $droot->{PRINT}/"; my @schedule; my $resume_total = 0; my $resume_success = 0; foreach my $child (sort { $a->{cgen} <=> $b->{cgen} } get_snapshot_children($sroot, $svol)) { my $filename_info = parse_filename($child->{SUBVOL_PATH}, $snapdir . $snapshot_basename); unless($filename_info) { DEBUG "Resume candidate does not match btrbk filename scheme, skipping: $child->{PRINT}"; next; } if(scalar get_receive_targets($droot, $child)) { DEBUG "Found matching receive target, skipping: $child->{PRINT}"; } else { DEBUG "No matching receive targets found, adding resume candidate: $child->{PRINT}"; if(my $err_vol = vinfo_subvol($droot, $child->{NAME})) { WARN "Target subvolume \"$err_vol->{PRINT}\" exists, but is not a receive target of \"$child->{PRINT}\""; } # check if the target would be preserved push(@schedule, { value => $child, btrbk_date => $filename_info->{btrbk_date}, preserve => $child->{FORCE_PRESERVE}, }); } } if(scalar @schedule) { DEBUG "Checking schedule for resume candidates"; # add all present backups to schedule, with no value # these are needed for correct results of schedule() foreach my $vol (values %{vinfo_subvol_list($droot)}) { my $filename_info = parse_filename($vol->{SUBVOL_PATH}, $snapshot_basename, ($config_target->{target_type} eq "raw")); unless($filename_info) { TRACE "Receive target does not match btrbk filename scheme, skipping: $vol->{PRINT}"; next; } push(@schedule, { value => undef, btrbk_date => $filename_info->{btrbk_date}, preserve => $vol->{FORCE_PRESERVE}, }); } my ($preserve, undef) = schedule( schedule => \@schedule, today => \@today, preserve_day_of_week => config_key($config_target, "preserve_day_of_week"), preserve_daily => config_key($config_target, "target_preserve_daily"), preserve_weekly => config_key($config_target, "target_preserve_weekly"), preserve_monthly => config_key($config_target, "target_preserve_monthly"), preserve_latest => $preserve_latest, ); my @resume = grep defined, @$preserve; # remove entries with no value from list (target subvolumes) $resume_total = scalar @resume; foreach my $child (sort { $a->{cgen} <=> $b->{cgen} } @resume) { INFO "Resuming subvolume backup (send-receive) for: $child->{PRINT}"; my ($latest_common_src, $latest_common_target) = get_latest_common($sroot, $svol, $droot, $child->{cgen}); if(macro_send_receive($config_target, snapshot => $child, target => $droot, parent => $latest_common_src, # this is if no common found resume => 1, # propagated to $config_target->{SUBVOL_RECEIVED} )) { # tag the source snapshot, so that get_latest_common() above can make use of the newly received subvolume $child->{RECEIVE_TARGET_PRESENT} = $droot->{URL}; $resume_success++; } else { # note: ABORTED flag is already set by macro_send_receive() ERROR("Error while resuming backups, aborting"); last; } } } if($resume_total) { INFO "Resumed $resume_success/$resume_total missing backups"; } else { INFO "No missing backups found"; } } # /resume_missing unless($resume_only) { # skip creation if resume_missing failed next if($config_target->{ABORTED}); next unless($config_subvol->{SNAPSHOT}); # finally receive the previously created snapshot INFO "Creating subvolume backup (send-receive) for: $svol->{PRINT}"; my ($latest_common_src, $latest_common_target) = get_latest_common($sroot, $svol, $droot); macro_send_receive($config_target, snapshot => $config_subvol->{SNAPSHOT}, target => $droot, parent => $latest_common_src, # this is if no common found ); } } } } # # remove backups following a preserve daily/weekly/monthly scheme # my $schedule_results = []; if($preserve_backups || $resume_only) { INFO "Preserving all backups (option \"-p\" or \"-r\" present)"; } else { foreach my $config_vol (@{$config->{VOLUME}}) { next if($config_vol->{ABORTED}); my $sroot = $config_vol->{sroot} || die; foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { next if($config_subvol->{ABORTED}); my $svol = $config_subvol->{svol} || die; my $snapdir = config_key($config_subvol, "snapshot_dir", postfix => '/') // ""; my $snapshot_basename = config_key($config_subvol, "snapshot_name") // die; my $preserve_latest_snapshot = $config_subvol->{SNAPSHOT} ? 0 : "preserve forced: latest in list"; my $preserve_latest_backup = $preserve_latest_snapshot; my $target_aborted = 0; foreach my $config_target (@{$config_subvol->{TARGET}}) { if($config_target->{ABORTED}) { if($config_target->{ABORTED} eq "USER_SKIP") { $target_aborted ||= -1; } else { $target_aborted = 1; } next; } my $droot = $config_target->{droot} || die; if($config_target->{target_type} eq "raw") { if(config_key($config_target, "incremental")) { # In incremental mode, the latest backup is most certainly our parent. # (see note on FORCE_PRESERVE above) $preserve_latest_backup ||= "preserve forced: possibly parent of latest backup"; # Note that we could check against $config_subvol->{SNAPSHOT}->{parent_uuid} to be certain, # but this information is not available in $dryrun: # foreach my $vol (values %{vinfo_subvol_list($droot)}) { # $vol->{FORCE_PRESERVE} = 1 if($vol->{received_uuid} eq $config_subvol->{SNAPSHOT}->{parent_uuid}); # } } } # # delete backups # INFO "Cleaning backups of subvolume \"$svol->{PRINT}\": $droot->{PRINT}/$snapshot_basename.*"; my @schedule; foreach my $vol (values %{vinfo_subvol_list($droot)}) { my $filename_info = parse_filename($vol->{SUBVOL_PATH}, $snapshot_basename, ($config_target->{target_type} eq "raw")); unless($filename_info) { TRACE "Receive target does not match btrbk filename scheme, skipping: $vol->{PRINT}"; next; } # NOTE: checking received_uuid does not make much sense, as this received_uuid is propagated to snapshots # if($vol->{received_uuid} && ($vol->{received_uuid} eq '-')) { # INFO "Target subvolume is not a received backup, skipping deletion of: $vol->{PRINT}"; # next; # } push(@schedule, { value => $vol, name => $vol->{PRINT}, # only for logging btrbk_date => $filename_info->{btrbk_date}, preserve => $vol->{FORCE_PRESERVE} }); } my (undef, $delete) = schedule( schedule => \@schedule, today => \@today, preserve_day_of_week => config_key($config_target, "preserve_day_of_week"), preserve_daily => config_key($config_target, "target_preserve_daily"), preserve_weekly => config_key($config_target, "target_preserve_weekly"), preserve_monthly => config_key($config_target, "target_preserve_monthly"), preserve_latest => $preserve_latest_backup, results => $schedule_results, result_hints => { topic => "backup", root_path => $droot->{PATH} }, ); my $ret = btrfs_subvolume_delete($delete, commit => config_key($config_target, "btrfs_commit_delete"), type => "delete_target"); if(defined($ret)) { INFO "Deleted $ret subvolumes in: $droot->{PRINT}/$snapshot_basename.*"; $config_target->{SUBVOL_DELETED} = $delete; } else { ABORTED($config_target, "Failed to delete subvolume"); $target_aborted = -1; } } # # delete snapshots # if($target_aborted) { if($target_aborted == -1) { INFO "Skipping cleanup of snapshots for subvolume \"$svol->{PRINT}\", as at least one target is skipped by command line argument"; } else { WARN "Skipping cleanup of snapshots for subvolume \"$svol->{PRINT}\", as at least one target aborted earlier"; } next; } INFO "Cleaning snapshots: $sroot->{PRINT}/$snapdir$snapshot_basename.*"; my @schedule; foreach my $vol (values %{vinfo_subvol_list($sroot)}) { my $filename_info = parse_filename($vol->{SUBVOL_PATH}, $snapdir . $snapshot_basename); unless($filename_info) { TRACE "Snapshot does not match btrbk filename scheme, skipping: $vol->{PRINT}"; next; } push(@schedule, { value => $vol, name => $vol->{PRINT}, # only for logging btrbk_date => $filename_info->{btrbk_date} }); } my (undef, $delete) = schedule( schedule => \@schedule, today => \@today, preserve_day_of_week => config_key($config_subvol, "preserve_day_of_week"), preserve_daily => config_key($config_subvol, "snapshot_preserve_daily"), preserve_weekly => config_key($config_subvol, "snapshot_preserve_weekly"), preserve_monthly => config_key($config_subvol, "snapshot_preserve_monthly"), preserve_latest => $preserve_latest_snapshot, results => $schedule_results, result_hints => { topic => "snapshot", root_path => $sroot->{PATH} }, ); my $ret = btrfs_subvolume_delete($delete, commit => config_key($config_subvol, "btrfs_commit_delete"), type => "delete_snapshot"); if(defined($ret)) { INFO "Deleted $ret subvolumes in: $sroot->{PRINT}/$snapdir$snapshot_basename.*"; $config_subvol->{SUBVOL_DELETED} = $delete; } else { ABORTED($config_subvol, "Failed to delete subvolume"); } } } } my $exit_status = exit_status($config); my $time_elapsed = time - $start_time; INFO "Completed within: ${time_elapsed}s (" . localtime(time) . ")"; action("finished", status => $exit_status ? "partial" : "success", duration => $time_elapsed, message => $exit_status ? "At least one backup task aborted" : undef, ); close_transaction_log(); unless($quiet) { # # print scheduling results # if($loglevel >= 2) { my @data = map { { %$_, vinfo_prefixed_keys("", $_->{value}) }; } @$schedule_results; my @data_snapshot = grep { $_->{topic} eq "snapshot" } @data; my @data_backup = grep { $_->{topic} eq "backup" } @data; if(scalar(@data_snapshot)) { print_formatted("schedule", \@data_snapshot, title => "SNAPSHOT SCHEDULE"); print "\n"; } if(scalar(@data_backup)) { print_formatted("schedule", \@data_backup, title => "BACKUP SCHEDULE"); print "\n"; } } # # print summary # $output_format ||= "custom"; if($output_format eq "custom") { my @unrecoverable; my @out; foreach my $config_vol (@{$config->{VOLUME}}) { my $sroot = $config_vol->{sroot} || vinfo($config_vol->{url}, $config_vol); foreach my $config_subvol (@{$config_vol->{SUBVOLUME}}) { my @subvol_out; my $svol = $config_subvol->{svol} || vinfo_child($sroot, $config_subvol->{rel_path}); if($config_subvol->{SNAPSHOT_UP_TO_DATE}) { push @subvol_out, "=== $config_subvol->{SNAPSHOT_UP_TO_DATE}->{PRINT}"; } if($config_subvol->{SNAPSHOT}) { push @subvol_out, "+++ $config_subvol->{SNAPSHOT}->{PRINT}"; } if($config_subvol->{SUBVOL_DELETED}) { foreach(sort { $a->{PATH} cmp $b->{PATH} } @{$config_subvol->{SUBVOL_DELETED}}) { push @subvol_out, "--- $_->{PRINT}"; } } foreach my $config_target (@{$config_subvol->{TARGET}}) { my $droot = $config_target->{droot} || vinfo($config_target->{url}, $config_target); foreach(@{$config_target->{SUBVOL_RECEIVED} // []}) { my $create_mode = "***"; $create_mode = ">>>" if($_->{parent}); # substr($create_mode, 0, 1, '%') if($_->{resume}); $create_mode = "!!!" if($_->{ERROR}); push @subvol_out, "$create_mode $_->{received_subvolume}->{PRINT}"; } if($config_target->{SUBVOL_DELETED}) { foreach(sort { $a->{PATH} cmp $b->{PATH} } @{$config_target->{SUBVOL_DELETED}}) { push @subvol_out, "--- $_->{PRINT}"; } } if($config_target->{ABORTED} && ($config_target->{ABORTED} ne "USER_SKIP")) { push @subvol_out, "!!! Target \"$droot->{PRINT}\" aborted: $config_target->{ABORTED}"; } if($config_target->{UNRECOVERABLE}) { push(@unrecoverable, $config_target->{UNRECOVERABLE}); } } if($config_vol->{ABORTED} && ($config_vol->{ABORTED} ne "USER_SKIP")) { # repeat volume errors in subvolume context push @subvol_out, "!!! Volume \"$sroot->{PRINT}\" aborted: $config_vol->{ABORTED}"; } if($config_subvol->{ABORTED} && ($config_subvol->{ABORTED} ne "USER_SKIP")) { push @subvol_out, "!!! Aborted: $config_subvol->{ABORTED}"; } if(@subvol_out) { push @out, "$svol->{PRINT}", @subvol_out, ""; } elsif($config_subvol->{ABORTED} && ($config_subvol->{ABORTED} eq "USER_SKIP")) { # don't print "" on USER_SKIP } else { push @out, "$svol->{PRINT}", "", ""; } } } print_header(title => "Backup Summary", config => $config, time => $start_time, legend => [ "=== up-to-date subvolume (source snapshot)", "+++ created subvolume (source snapshot)", "--- deleted subvolume", "*** received subvolume (non-incremental)", ">>> received subvolume (incremental)", # "%>> received subvolume (incremental, resume_missing)", ], ); print join("\n", @out); if($resume_only) { print "\nNOTE: No snapshots created (option -r present)\n"; } if($preserve_backups || $resume_only) { print "\nNOTE: Preserved all backups (option -p or -r present)\n"; } if($exit_status) { print "\nNOTE: Some errors occurred, which may result in missing backups!\n"; print "Please check warning and error messages above.\n"; print join("\n", @unrecoverable) . "\n" if(@unrecoverable); } if($dryrun) { print "\nNOTE: Dryrun was active, none of the operations above were actually executed!\n"; } } else { # print action log (without transaction start messages) my @data = grep { $_->{status} ne "starting" } @transaction_log; print_formatted("transaction", \@data, title => "TRANSACTION LOG"); } } exit $exit_status if($exit_status); } } 1; btrbk-0.22.2/btrbk.conf.example000066400000000000000000000114071265410210100163010ustar00rootroot00000000000000# # Example btrbk configuration file # # # Please refer to the btrbk.conf(5) man-page for more details. # # Note that the options can be overridden in the # volume/subvolume/target sections. # # Enable transaction log transaction_log /var/log/btrbk.log # Directory in which the btrfs snapshots are created. Relative to # of the volume section. # If not set, the snapshots are created in . # # If you want to set a custom name for the snapshot (and backups), # use the "snapshot_name" option within the subvolume section. # # NOTE: btrbk does not autmatically create this directory, and the # snapshot creation will fail if it is not present. # snapshot_dir _btrbk_snap # Always create snapshots. Set this to "ondemand" to only create # snapshots if the target volume is reachable. Set this to "no" if # snapshot creation is done by another instance of btrbk. #snapshot_create always # Perform incremental backups (set to "strict" if you want to prevent # creation of non-incremental backups if no parent is found). #incremental yes # Resume missing backups (set to "no" if you don't want to resume # missing backups). #resume_missing yes # Specify on which day of week weekly/monthly backups are to be # preserved. #preserve_day_of_week sunday # Preserve matrix for source snapshots: #snapshot_preserve_daily all #snapshot_preserve_weekly 0 #snapshot_preserve_monthly all # Preserve matrix for backup targets: #target_preserve_daily all #target_preserve_weekly 0 #target_preserve_monthly all # Specify SSH private key for "ssh://" volumes / targets: #ssh_identity /etc/btrbk/ssh/id_ed25519 #ssh_user root #ssh_port default #ssh_compression no #ssh_cipher_spec default # Don't wait for transaction commit on deletion. Set this to "after" # or "each" to make sure the deletion of subvolumes is committed to # disk when btrbk terminates. #btrfs_commit_delete no # Set this to "yes" to enable btrfs-progs < 3.17 compatibility. # Set this either globally or in a specific "target" section. #btrfs_progs_compat no # # Volume section: "volume " # # Directory of a btrfs volume (or subvolume) # containing the subvolume to be backuped # (usually the mount-point of a btrfs filesystem # mounted with subvolid=0 option) # # Subvolume section: "subvolume # # Subvolume to be backuped, relative to # in volume section. # # Target section: "target " # # Backup type, currently only "send-receive". # Directory of a btrfs volume (or subvolume) # receiving the backups. # # NOTE: The parser does not care about indentation, this is only for # human readability. The options always apply to the last section # encountered, overriding the corresponding option of the upper # section. This means that the global options must be set before any # "volume" section. # # # Example configuration: # snapshot_preserve_daily 14 snapshot_preserve_weekly 0 snapshot_preserve_monthly 0 target_preserve_daily 20 target_preserve_weekly 10 target_preserve_monthly all # Backup to external disk mounted on /mnt/btr_backup volume /mnt/btr_pool # no action if external disk is not attached snapshot_create ondemand subvolume root_gentoo target send-receive /mnt/btr_backup/_btrbk subvolume kvm # use different preserve matrix for kvm backups target_preserve_daily 7 target_preserve_weekly 4 target send-receive /mnt/btr_backup/_btrbk # Backup to external disk as well as some remote host volume /mnt/btr_data subvolume home # always create snapshot, even if targets are unreachable snapshot_create always target send-receive /mnt/btr_backup/_btrbk target send-receive ssh://backup.my-remote-host.com/mnt/btr_backup # Backup from remote host, with different naming volume ssh://my-remote-host.com/mnt/btr_pool subvolume data_0 snapshot_dir snapshots/btrbk snapshot_name data_main target send-receive /mnt/btr_backup/_btrbk/my-remote-host.com # Resume backups from remote host which runs its own btrbk instance # creating snapshots for "home" in "/mnt/btr_pool/btrbk_snapshots". volume ssh://my-remote-host.com/mnt/btr_pool subvolume home snapshot_dir btrbk_snapshots snapshot_preserve_daily all snapshot_create no resume_missing yes target send-receive /mnt/btr_backup/_btrbk/my-remote-host.com btrbk-0.22.2/contrib/000077500000000000000000000000001265410210100143315ustar00rootroot00000000000000btrbk-0.22.2/contrib/cron/000077500000000000000000000000001265410210100152725ustar00rootroot00000000000000btrbk-0.22.2/contrib/cron/btrbk-mail000077500000000000000000000102561265410210100172500ustar00rootroot00000000000000#!/bin/bash ## Wrapper script running "btrbk" and sending email with results set -uf declare -A rsync_src rsync_dst rsync_log rsync_key rsync_opt now=$(/bin/date +%Y%m%d) ##### start config section ##### # Email recipients, separated by whitespace: mailto=$MAILTO # List of mountpoints to be mounted/unmounted (whitespace-separated) # mount_targets="/mnt/btr_pool /mnt/backup" mount_targets= umount_targets=$mount_targets # btrbk configuration file: config="/etc/btrbk/btrbk.conf" # Uncomment this if you only want to receive error messages: #btrbk_opts="-q" #skip_empty_mail=yes # Email subject: mail_subject_prefix="btrbk <${HOSTNAME:-localhost}>" # rsync declarations (repeat complete block for more declarations): rsync_src[example_data]=user@example.com:/data/ rsync_dst[example_data]=/mnt/backup/example.com/data/ rsync_log[example_data]=/mnt/backup/example.com/data-${now}.log rsync_key[example_data]=/mnt/backup/ssh_keys/id_rsa rsync_opt[example_data]="-az --delete" # Enabled rsync declarations (space separated list) #rsync_enable="example_data" rsync_enable= # Log level (1=error, 2=warn, 3=info) loglevel=2 ##### end config section ##### mail_body="" die() { /bin/echo "$0 FATAL: $1" 1>&2 /bin/echo "$0 FATAL: exiting" 1>&2 exit 1 } log_error() { [ $loglevel -ge 1 ] && /bin/echo "$0 ERROR: $1" 1>&2 ; } log_warning() { [ $loglevel -ge 2 ] && /bin/echo "$0 WARNING: $1" 1>&2 ; } log_info() { [ $loglevel -ge 3 ] && /bin/echo "$0 INFO: $1" 1>&2 ; } # # mount all mountpoints listed in $mount_targets # for mountpoint in $mount_targets; do $(/bin/findmnt -r -n -t btrfs $mountpoint 1>&2) if [ $? = 0 ]; then log_warning "btrfs filesystem already mounted: $mountpoint" else log_info "mount $mountpoint" $(/bin/mount --target $mountpoint 1>&2) [ $? = 0 ] || log_error "mount failed: $mountpoint" fi done # # run rsync for all $rsync_enable # for key in $rsync_enable; do log_info "starting rsync: $key" [ -n "${rsync_src[$key]}" ] || die "rsync_src is not set for \"$key\"" [ -n "${rsync_dst[$key]}" ] || die "rsync_dst is not set for \"$key\"" [ -n "${rsync_log[$key]}" ] || die "rsync_log is not set for \"$key\"" [ -n "${rsync_key[$key]}" ] || die "rsync_key is not set for \"$key\"" [ -n "${rsync_opt[$key]}" ] || die "rsync_opt is not set for \"$key\"" rsync_header="### rsync ${rsync_opt[$key]} ${rsync_src[$key]} ${rsync_dst[$key]}" if [ -d ${rsync_dst[$key]} ]; then /bin/echo "$rsync_header" >> ${rsync_log[$key]} ret=$(/usr/bin/rsync ${rsync_opt[$key]} --info=STATS --log-file=${rsync_log[$key]} -e "/usr/bin/ssh -i ${rsync_key[$key]}" ${rsync_src[$key]} ${rsync_dst[$key]}) if [ $? != 0 ]; then log_error "rsync failed: $key" ret+="\nERROR: rsync failed with exit code $?\n" fi mail_body+="$rsync_header$ret\n\n" else ret="rsync destination directory not found for \"$key\", skipping: ${rsync_dst[$key]}" mail_body+="$rsync_header\n$ret\n\n" log_error "$ret" fi done # # run btrbk # log_info "running btrbk" ret=$(/usr/sbin/btrbk -c "$config" ${btrbk_opts:-} run 2>&1) exitcode=$? case $exitcode in 0) status="All backups successful" ;; 10) status="ERROR: At least one backup task aborted!" ;; *) status="ERROR: $btrbk failed with error code $exitcode" ;; esac mail_body+=$ret if [ "${skip_empty_mail:-no}" = "yes" ] && [ -z "$mail_body" ] && [ $exitcode -eq 0 ]; then : # skip email sending if skip_empty_mail=yes else # send email /bin/echo -e "$mail_body" | /bin/mail -s "$mail_subject_prefix - $status" $mailto if [ $? != 0 ]; then log_error "failed to send btrbk mail to \"$mailto\", dumping mail body:" /bin/echo -e "$mail_body" 1>&2 fi fi # # sync all mountpoints listed in $umount_targets # # exit on failure! #for mountpoint in $umount_targets; do # log_info "btrfs filesystem sync $mountpoint" # $(/sbin/btrfs filesystem sync $mountpoint 1>&2) # [ $? = 0 ] || die "btrfs filesystem sync failed: $mountpoint" # sleep 1 #done # # unmount all mountpoints listed in $umount_targets # for mountpoint in $umount_targets; do log_info "umount $mountpoint" $(/bin/umount $mountpoint 1>&2) [ $? = 0 ] || log_error "umount failed: $mountpoint" done btrbk-0.22.2/contrib/systemd/000077500000000000000000000000001265410210100160215ustar00rootroot00000000000000btrbk-0.22.2/contrib/systemd/btrbk.service000066400000000000000000000001261265410210100205060ustar00rootroot00000000000000[Unit] Description=btrbk backup [Service] Type=oneshot ExecStart=/usr/sbin/btrbk run btrbk-0.22.2/contrib/systemd/btrbk.timer000066400000000000000000000002101265410210100201600ustar00rootroot00000000000000[Unit] Description=btrbk daily backup [Timer] OnCalendar=daily AccuracySec=10min Persistent=true [Install] WantedBy=multi-user.target btrbk-0.22.2/doc/000077500000000000000000000000001265410210100134365ustar00rootroot00000000000000btrbk-0.22.2/doc/FAQ.md000066400000000000000000000162741265410210100144010ustar00rootroot00000000000000btrbk FAQ ========= How can I auto-mount btrfs filesystems used by btrbk? ----------------------------------------------------- Given that the "volume" lines in the btrbk configuration file are valid mount-points, you can loop through the configuration and mount the volumes like this: #!/bin/sh btrbk list volume --format=raw | while read line; do eval $line $volume_rsh mount $volume_path done Note that the `btrbk list` command accepts filters (see [btrbk(1)], FILTER STATEMENTS), which means you can e.g. add "group automount" tags in your configuration and dump only the volumes of this group: `btrbk list volume automount`. [btrbk(1)]: http://www.digint.ch/btrbk/doc/btrbk.html Why is it not possible to backup '/' (btrfs root) ? --------------------------------------------------- or in other words: why does this config not work: /etc/btrbk/btrbk.conf: volume / subvolume / snapshot_name rootfs *ERROR: Only relative files allowed for option "subvolume"*. ### Answer btrbk is designed to never alter your source subvolume. In the config above, the btrbk snapshots would be created *inside* the source subvolume, altering it. The same applies to **any "btrfs root" mount point** (subvolid=0). In the example below, you will **not be able to backup** `/mnt/data` using btrbk: /etc/fstab: /dev/sda1 /mnt/data btrfs subvolid=0 [...] btrbk is designed to operate on the subvolumes *within* `/mnt/data`. The recommended way is to split your data into subvolumes, e.g.: # btrfs subvolume create /mnt/data/www # btrfs subvolume create /mnt/data/mysql # btrfs subvolume create /mnt/data/projectx This way you make full advantage of the btrfs filesystem, as all your data now has a name, which helps organizing things a lot. This gets even more important as soon as you start snapshotting and send/receiving. The btrbk configuration for this would be: volume /mnt/data subvolume www [...] subvolume mysql [...] subvolume projectx [...] ### Tech Answer While *btrfs root* (subvolid=0) is a regular subvolume, it is still special: being the root node, it does not have a "name" inside the subvolume tree. Here, `/mnt/btr_pool` is mounted with `subvolid=0`: # btrfs sub show /mnt/btr_pool/ /mnt/btr_pool is btrfs root # btrfs sub show /mnt/btr_pool/rootfs /mnt/btr_pool/rootfs Name: rootfs uuid: [...] How should I organize my btrfs filesystem? ------------------------------------------ There's lots of ways to do this, and each one of them has its reason to exist. Make sure to read the [btrfs SysadminGuide on kernel.org](https://btrfs.wiki.kernel.org/index.php/SysadminGuide) as a good entry point. ### btrfs root If your linux root filesystem is btrfs, I recommend booting linux from a btrfs subvolume, and use the btrfs root only as a container for subvolumes (i.e. NOT booting from "subvolid=0"). This has the big advantage that you can choose the subvolume in which to boot by simply switching the `rootflags=subvol=` kernel boot option. Example (/boot/grub/grub.cfg): menuentry 'Linux' { linux /boot/vmlinuz root=/dev/sdb3 ro rootflags=subvol=rootfs quiet } menuentry 'Linux (testing)' { linux /boot/vmlinuz root=/dev/sdb3 ro rootflags=subvol=rootfs_testing } Note that btrbk snapshots and backups are read-only, this means you have to create a run-time (rw) snapshot before booting into it: # btrfs subvolume snapshot /mnt/btr_pool/backup/btrbk/rootfs-20150101 /mnt/btr_pool/rootfs_testing How do I convert '/' (subvolid=0) into a subvolume? --------------------------------------------------- There's several ways to achieve this, the solution described below is that it guarantees not to create new files (extents) on disk. ### Step 1: make a snapshot of your root filesystem Assuming that '/' is mounted with `subvolid=0`: # btrfs subvolume snapshot / /rootfs Note that this command does NOT make any physical copy of the files of your subvolumes within "/", it will only add some metadata. ### Step 2: make sure that "/rootfs/etc/fstab" is ok. Add mount point for subvolid=0 to fstab, something like this: /rootfs/etc/fstab: /dev/sda1 /mnt/btr_pool btrfs subvolid=0,noatime 0 0 ### Step 3: boot from the new subvolume "rootfs". Either add `rootflags=subvol=rootfs` to grub.cfg, or set subvolume "rootfs" as default: # btrfs subvolume set-default / ### Step 4: after reboot, check if everything went fine: First check your **system log** for btrfs errors, then: # btrfs subvolume show / Name: rootfs ... Great, this tells us that we just booted into our new snapshot! # mount /mnt/btr_pool # btrfs subvolume show /mnt/btr_pool /mnt/btr_pool is btrfs root This means that the root volume (subvolid=0) is correctly mounted. ### Step 5: delete old (duplicate) files Carefully delete all old files from `/mnt/btr_pool`, except "rootfs" and all other subvolumes within "/". You can list all these by typing: # btrfs subvolume list -a /mnt/btr_pool Make sure you do NOT delete anything within the directories listed here! something like: # cd /mnt/btr_pool # rm -rf bin sbin usr lib var ... What is the most efficient way to clone btrfs storage? ------------------------------------------------------ It is very common (and avisable!) to keep backups on a separate location. In some situations, is is also required to transport the data physically, either to the datacenter or to your safe in the basement. ### Answer 1: Use external storage as "stream-fifo" This example uses a USB disk as "stream-fifo" for transferring (cloning) of btrfs subvolumes: 1. For all source subvolumes (in order of generation): `btrfs send /source/subvolX -p PARENT > /usbdisk/streamN` 2. At the target location, restore the streams (in order of generation): `cat /usbdisk/streamN | btrfs receive /target` This approach has the advantage that you don't need to reformat your USB disk. This works fine, but be aware that you may run into trouble if a single stream gets corrupted, making all subsequent streams unusable. ### Answer 2: Clone btrfs subvolumes A more robust approach is to use the USB disk as secondary backup. This has the advantage that possible errors can already be detected by btrfs on the source side: 1. Initialize USB disk: `mkfs.btrfs /dev/usbX` 2. For all source subvolumes (in order of generation): `btrfs send /source/subvolX -p PARENT | btrfs receive /usbdisk/` 3. At the target location (in order of generation): `btrfs send /usbdisk/subvolX -p PARENT | btrfs receive /target` If you simply want to have a clone of the source disk, skip step 3 and store your USB disk in a safe. You will be able to use it for restoring backups later, or *as a replacement for your backup disks*. **Note that kernels >=4.1 have a bug when re-sending subvolumes**, make sure you run a patched kernel or step 3 will fail. Read [this thread on gmane](http://thread.gmane.org/gmane.comp.file-systems.btrfs/48798) (the patch provided is confirmed working on kernels 4.2.x and 4.3). btrbk-0.22.2/doc/btrbk.1000066400000000000000000000201071265410210100146240ustar00rootroot00000000000000.TH "btrbk" "1" "2016-02-02" "btrbk v0.22.2" "" .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .SH NAME btrbk \- backup tool for btrfs volumes .SH SYNOPSIS .nf \fBbtrbk\fR [\-h|\-\-help] [\-\-version] [\-c|\-\-config ] [\-n|\-\-dry\-run] [\-p|\-\-preserve] [\-r|\-\-resume\-only] [\-v|\-\-verbose] [\-q|\-\-quiet] [\-l|\-\-loglevel ] [\-t|\-\-table] [\-\-format ] [\-\-progress] [] .fi .SH DESCRIPTION \fBbtrbk\fR is a backup tool for btrfs subvolumes, taking advantage of btrfs specific capabilities to create atomic snapshots and transfer them incrementally to target volumes. It is able to perform backups from one source to multiple destinations. .PP Snapshots as well as backup subvolume names are created in form: .PP .RS 4 .[_N] .RE .PP Where is identical to the source subvolume name, unless the configuration option \fIsnapshot_name\fR is set. The is either "YYYYMMDD" or "YYYYMMDDThhmm" (dependent of the \fItimestamp_format\fR configuration option), where "YYYY" is the year, "MM" is the month, "DD" is the day, "hh" is the hour and "mm" is the minute of the creation time (local time of the host running btrbk). If multiple snapshots/backups are created on the same date/time, N will be incremented on each backup, starting at 1. .SH OPTIONS .PP \-h, \-\-help .RS 4 Prints the synopsis and a list of the commands. .RE .PP \-\-version .RS 4 Prints the btrbk version. .RE .PP \-n, \-\-dry\-run .RS 4 Don't run anything that would alter the filesystem, just show the snapshots and backup subvolumes that would be created/deleted by the \fBrun\fR and \fBclean\fR commands. Use in conjunction with \fI\-l debug\fR to see the btrfs commands that would be executed. .RE .PP \-c, \-\-config .RS 4 Read the configuration from . .RE .PP \-p, \-\-preserve .RS 4 Preserve all backups. Skips deletion of old backups, even if specified in the configuration file. .RE .PP \-r, \-\-resume-only .RS 4 Resume only. Skips snapshot creation, only resumes missing backups. This only makes sense if the \fIresume_missing\fR option is set to \[lq]yes\[rq] in the configuration file. .RE .PP \-v, \-\-verbose .RS 4 Verbose output. Sets "\-l info", and prints detailed scheduler information on "run" and "dryrun" commands. .RE .PP \-q, \-\-quiet .RS 4 Quiet operation. If set, btrbk does not print the summary after executing the "run" command. .RE .PP \-l, \-\-loglevel .RS 4 Set the level of verbosity. Accepted levels are warn, info, debug, and trace. .RE .PP \-t, \-\-table .RS 4 Print output in table format (shortcut for "--format=table"). .RE .PP \-\-format table|long|raw .RS 4 Print output in specified format. If set to "raw", prints space-separated key="value" pairs (machine-readable). Affects output format for \fBrun\fR, \fBdryrun\fR, \fBlist\fR and \fBtree\fR commands. Useful for further exporting/scripting. .RE .PP \-\-progress .RS 4 Show progress bar on send-receive operation. .RE .SH COMMANDS .PP .B run [filter...] .RS 4 Perform backup operations as specified in the configuration file. If the optional [filter...] arguments are present, backups are only performed for the subvolumes/targets matching a \fIFILTER STATEMENT\fR (see below). .PP First, btrbk reads information from the source and target btrfs filesystems in order to perform sanity checks and identify parent/child and received-from relationships. .PP If the checks succeed, btrbk creates snapshots for all the source subvolumes specified in the configuration file. .PP Then, for each specified target, btrbk creates the backups as follows: If the \fIresume_missing\fR option is set (the default), btrbk transfers all missing snapshots needed to satisfy the configured \fItarget_preserve_{daily,weekly,monthly}\fR retention policy, always incrementally from the latest common parent subvolume found. If no common parent subvolume is found, a full backup is created for the first transfer. Note that the latest snapshot (the one created in the first step) is always transferred, regardless of the retention policy. .PP As a last step, unless the -p (preserve backups) option is set, snapshots and backup subvolumes that are not preserved by their configured retention policy will be deleted. Note that the latest snapshot as well as the latest backup is always preserved, regardless of the retention policy. .PP Use the \fI\-\-format\fR command line option to switch between different output formats. .RE .PP .B dryrun [filter...] .RS 4 Don't run any btrfs commands that would alter the filesystem, just show the snapshots and backup subvolumes that would be created/deleted by the \fBrun\fR command. Use in conjunction with \fI\-l debug\fR to see the btrfs commands that would be executed. .RE .PP .B stats [filter...] .RS 4 Print statistics of snapshot and backup subvolumes. Optionally filtered by [filter...] arguments (see \fIFILTER STATEMENTS\fR below). .RE .PP .B list [filter...] .RS 4 Print information defined by in a tabular form. Optionally filtered by [filter...] arguments (see \fIFILTER STATEMENTS\fR below). .PP Available subcommands: .TP 11 .B snapshots All snapshots (and corresponding backups). .PD 0 .TP 11 .B backups All backups (and corresponding snapshots). .TP 11 .B latest Most recent snapshots and backups. .TP 11 .B config Configured source/snapshot/target relations. .TP 11 .B source Configured source/snapshot relations. .TP 11 .B volume Configured volume sections. .TP 11 .B target Configured targets. .PD .PP Use the \fI\-\-format\fR command line option to switch between different output formats. .RE .PP .B clean [filter...] .RS 4 Delete incomplete (garbled) backups. Incomplete backups can be left behind on network errors or kill signals while a send/receive operation is ongoing, and are identified by the "received_uuid" flag not being set on a target (backup) subvolume. .RE .PP .B usage [filter...] .RS 4 Print filesystem usage information for all source/target volumes. Optionally filtered by [filter...] arguments (see \fIFILTER STATEMENTS\fR below). .RE .PP .B origin .RS 4 Print origin information for the given backup subvolume, showing the parent-child relationship as well as the received-from information. .RE .PP .B diff .RS 4 Print new files since subvolume for subvolume . .RE .PP .B config print|print-all .RS 4 Prints the parsed configuration file. Use the \fI\-\-format\fR command line option to switch between different output formats. .RE .SH FILTER STATEMENTS Filter arguments are accepted in form: .PP [hostname:] .RS 4 Matches all subvolumes and targets of a \fIvolume\fR configuration section. .RE .PP [hostname:]/ .RS 4 Matches the specified subvolume and all targets of a \fIsubvolume\fR configuration section. .RE .PP [hostname:] .RS 4 Matches all targets of a \fItarget\fR configuration section. .RE .PP [hostname:]/ .RS 4 Matches a single target of a \fItarget\fR section within a \fIsubvolume\fR section with given . .RE .PP .RS 4 Matches the \fIgroup\fR configuration option of a \fIvolume\fR, \fIsubvolume\fR or \fItarget\fR section. .RE .PP For convenience, [hostname:] can be specified as either "hostname:" or "ssh://hostname/". .SH FILES .PP /etc/btrbk.conf .br /etc/btrbk/btrbk.conf .RS 4 Default configuration file. The file format and configuration options are described in .BR btrbk.conf (5). .RE .PD .SH EXIT STATUS \fBbtrbk\fR returns the following error codes: .IP "0" 4 No problems occurred. .IP "1" 4 Generic error code. .IP "2" 4 Parse error: when parsing command-line options or configuration file. .IP "10" 4 Backup abort: At least one backup task aborted. .IP "255" 4 Script error. .SH AVAILABILITY Please refer to the btrbk project page \fBhttp://www.digint.ch/btrbk/\fR for further details. .SH SEE ALSO .BR btrbk.conf (5), .BR btrfs (1) .PP For more information about btrfs and incremental backups, see the web site at https://btrfs.wiki.kernel.org/index.php/Incremental_Backup .SH AUTHOR Axel Burri btrbk-0.22.2/doc/btrbk.conf.5000066400000000000000000000217201265410210100155560ustar00rootroot00000000000000.TH "btrbk.conf" "5" "2016-02-02" "btrbk v0.22.2" "" .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .SH NAME btrbk.conf \- btrbk configuration file .SH SYNOPSIS .B /etc/btrbk.conf .br .B /etc/btrbk/btrbk.conf .SH DESCRIPTION The btrbk configuration file specifies which btrfs subvolumes on the filesystem are to be processed, what target subvolumes should be used to create the backups, and where the snapshots should be generated. The retention policy, as well as most other options can be defined either globally or within a section. .PP The options specified always apply to the last section encountered, superseding the values set in upper-level sections. This means that global options must be set before any sections are defined. .SH SECTIONS .PP \fBvolume\fR | .RS 4 Directory of a btrfs volume containing the source subvolume(s) to be backed up. \fI\fR must be an absolute path and point to a btrfs volume (or subvolume). Usually the mount point of a btrfs filesystem mounted with the \fIsubvolid=0\fR option. .RE .PP \fBsubvolume\fR .RS 4 Subvolume to be backed up, relative to the \fI\fR specified in the \fIvolume\fR section. Multiple \fIsubvolume\fR sections are allowed within \fIvolume\fR sections. .RE .PP \fBtarget\fR | .RS 4 Target type and directory where the backup subvolumes are to be created. See the TARGET TYPES section for supported \fI\fR. Multiple \fItarget\fR sections are allowed within \fIsubvolume\fR sections. .RE .PP For the \fIvolume\fR and \fItarget\fR sections, you can specify a ssh-url instead of a local directory. The syntax for \fI\fR is: .PP .RS 4 .nf ssh://host.xz/path/to/volume .fi .RE .PP Note that btrfs is very picky on file names (mainly for security reasons), only the characters [0-9] [a-z] [A-Z] and "._+-@" are allowed. .RE .SH OPTIONS .PP \fBtransaction_log\fR .RS 4 If set, all transactions (snapshot create, subvolume send-receive, subvolume delete) as well as abort messages are logged to , in a space-separated table format. .RE .PP \fBtimestamp_format\fR short|long .RS 4 Timestamp format used as postfix for new snapshot subvolume names. Defaults to \[lq]short\[rq]. .PP .IP \fBshort\fR YYYYMMDD[_N] (e.g. "20150825", "20150825_1") .IP \fBlong\fR YYYYMMDDhhmm[_N] (e.g. "20150825T1531") .PP Note that a postfix "_N" is only appended to the timestamp if a snapshot/backup already exists with the timestamp of current date/time. .RE .PP \fBsnapshot_dir\fR .RS 4 Directory in which the btrfs snapshots are created, relative to \fI\fR of the \fIvolume\fR section. Note that btrbk does not autmatically create this directory, and the snapshot creation will fail if it is not present. .RE .PP \fBsnapshot_name\fR .RS 4 Base name of the created snapshot (and backup). This option is only valid in the \fIsubvolume\fR section. Defaults to \fI\fR. .RE .PP \fBsnapshot_create\fR always|ondemand|onchange|no .RS 4 If set to \[lq]ondemand\[rq], snapshots are only created if the target subvolume is reachable (useful if you are tight on disk space and you only need btrbk for backups to an external disk which is not always connected). If set to \[lq]onchange\[rq], snapshots are only created if the source subvolume has changed since the last snapshot (more precisely: if the btrfs generation has been increased since the last snapshot). If set to \[lq]always\[rq], snapshots are always created. If set to \[lq]no\[rq], the snapshots are never created (useful in conjunction with the \fIresume_missing\fR option if another instance of btrbk is taking care of snapshot creation). Defaults to \[lq]always\[rq]. .RE .PP \fBincremental\fR yes|no|strict .RS 4 If set, incremental backups are created. If set to \[lq]strict\[rq], non-incremental (initial) backups are never created. Defaults to \[lq]yes\[rq]. .RE .PP \fBresume_missing\fR yes|no .RS 4 If set, the backups in the target directory are compared to the source snapshots, and missing backups are created if needed (complying to the target preserve matrix). Defaults to \[lq]yes\[rq]. .RE .PP \fBtarget_preserve_daily\fR all| .RS 4 How many days of backups should be preserved. Defaults to \[lq]all\[rq]. .RE .PP \fBtarget_preserve_weekly\fR all| .RS 4 Defines for how many weeks back weekly backups should be preserved. Every backup created at \fIpreserve_day_of_week\fR (or the next backup in this week if none was made on the exact day) is considered as a weekly backup. Defaults to \[lq]0\[rq]. .RE .PP \fBtarget_preserve_monthly\fR all| .RS 4 Defines for how many months back monthly backups should be preserved. Every last weekly backup in a month is considered a monthly backup. Defaults to \[lq]all\[rq]. .RE .PP \fBsnapshot_preserve_daily\fR .PD 0 .PP \fBsnapshot_preserve_weekly\fR .PP \fBsnapshot_preserve_monthly\fR .RS 4 Defines retention policy for the snapshots, with same semantics as the \fItarget_preserve_*\fR options. .RE .PD .PP \fBpreserve_day_of_week\fR monday|tuesday|...|sunday .RS 4 Defines on what day a backup/snapshot is considered as a weekly backup. Defaults to \[lq]sunday\[rq]. .RE .PP \fBgroup\fR [,]... .RS 4 Add the current section (volume, subvolume or target) to a user-defined group, which can be used as filter for several btrbk commands. .RE .PP \fBssh_identity\fR .RS 4 Absolute path to a ssh identity file (private key). Note that if the private key is password protected, btrbk will prompt for user input, which is usually not desired. .RE .PP \fBssh_user\fR .RS 4 Remote username for ssh. Defaults to \[lq]root\[rq]. Note that you will have to make sure that the remote user is able to run /sbin/btrfs (which needs root privileges). .RE .PP \fBssh_port\fR .RS 4 Port to connect to on the remote host. Defaults to \[lq]default\[rq] (the port specified in \fIssh_config\fR, which defaults to 22). .RE .PP \fBssh_compression\fR yes|no .RS 4 Enables or disables the compression of ssh connections. Defaults to \[lq]no\[rq]. .RE .PP \fBssh_cipher_spec\fR .RS 4 Selects the cipher specification for encrypting the session (comma-separated list of ciphers in order of preference). See the "-c cipher_spec" option in ssh(1) for more information. Defaults to \[lq]default\[rq] (the ciphers specified in \fIssh_config\fR). .RE .PP \fBbtrfs_commit_delete\fR after|each|no .RS 4 If set, make sure the deletion of snapshot and backup subvolumes are committed to disk when btrbk terminates. Defaults to \[lq]no\[rq]. .RE .PP \fBbtrfs_progs_compat\fR yes|no \fI*experimental*\fR .RS 4 Enable compatibility mode for btrfs-progs < 3.17 (\fIbtrfs --version\fR). This option can be set either globally or within a \fItarget\fR section. If enabled, the latest common snapshots are determined by subvolume names instead of \fIreceived_uuid\fR, which can lead to false guesses if the snapshot or target subvolumes are manipulated by hand (moved, deleted). .RE .PP Lines that contain a hash character (#) in the first column are treated as comments. .SH TARGET TYPES .PP \fBsend-receive\fR .RS 4 Backup to a btrfs filesystem, using "btrfs send/receive". This is the recommended (standard) target type. The \fI\fR must be an absolute path and point to a btrfs volume (or subvolume). See btrfs-send(8), btrfs-receive(8). .RE .PP \fBraw\fR \fI*experimental*\fR .RS 4 Backup to a raw (filesystem independent) file from the output of btrfs-send(8), with optional compression and encryption. .PP Note that the target preserve mechanism is currently disabled for raw backups (btrbk does not delete any raw files)! .PP Additional options for raw targets: .PP .RS 4 raw_target_compress gzip|bzip2|xz|no .PD 0 .PP raw_target_compress_level default| .PP raw_target_compress_threads default| .PP raw_target_encrypt gpg|no .PP gpg_keyring .PP gpg_recipient .RE .PD .PP Target file name syntax: .PP .RS 4 --[@].btrfs[.gz|.bz2|.xz][.gpg] .RE .PP The is only set on \fIincremental\fR backups, and points to the of the previous backup in a incremental backup chain. .PP For \fIincremental\fR backups ("incremental yes"), please note that: .IP 1. 4 As soon as a single \fIincremental\fR backup file is lost or corrupted, all later incremental backups become invalid, as there is no common parent for the subsequent incremental images anymore. This might be a good compromise for a vacation backup plan, but for the long term make sure that a non-incremental backup is triggered from time to time. .IP 2. 4 There is currently no support for rotation of incremental backups: if \fIincremental\fR is set, a full backup must be triggered manually from time to time in order to be able to delete old backups. .RE .SH AVAILABILITY Please refer to the btrbk project page \fBhttp://www.digint.ch/btrbk/\fR for further details. .SH SEE ALSO .BR btrbk (1) .SH AUTHOR Axel Burri btrbk-0.22.2/doc/ssh_filter_btrbk.1000066400000000000000000000046211265410210100170510ustar00rootroot00000000000000.TH "ssh_filter_btrbk" "1" "2016-02-02" "btrbk v0.22.2" "" .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .SH NAME ssh_filter_btrbk.sh \- ssh command filter script for btrbk .SH SYNOPSIS .nf \fBssh_filter_btrbk.sh\fR [\-s|\-\-source] [\-t|\-\-target] [\-d|\-\-delete] [\-i|\-\-info] [\-p|\-\-restrict\-path ] [\-l|\-\-log] [\-\-sudo] .fi .SH DESCRIPTION \fBssh_filter_btrbk.sh\fR restricts SSH commands to \fIbtrfs\fR commands used by \fIbtrbk\fR. It examines the SSH_ORIGINAL_COMMAND environment variable (set by sshd) and executes it only if it matches commands used by \fIbtrbk\fR. The accepted commands are specified by the "\-\-source", "\-\-target", "\-\-delete" and "\-\-info" options. .PP Note that the following btrfs commands are always allowed: "btrfs subvolume show", "btrfs subvolume list". .PP Example line in /root/.ssh/authorized_keys on a backup target host: .PP .RS 4 .nf command="ssh_filter_btrbk.sh \-\-target \-\-delete \-\-restrict\-path /mnt/btr_backup" ssh\-rsa AAAAB3NzaC1...hwumXFRQBL btrbk@mydomain.com .fi .RE .SH OPTIONS .PP \-s, \-\-source .RS 4 Allow commands for backup source: "btrfs subvolume snapshot", "btrfs send". Equivalent to "\-\-snapshot \-\-send". .RE .PP \-t, \-\-target .RS 4 Allow commands for backup target: "btrfs receive". Equivalent to "\-\-receive". .RE .PP \-d, \-\-delete .RS 4 Allow commands for subvolume deletion: "btrfs subvolume delete". This is used for backup source if \fIsnapshot_preserve_daily\fR is not set to \[lq]all\[rq], and for backup targets if \fItarget_preserve_daily\fR is not set to \[lq]all\[rq]. .RE .PP \-i, \-\-info .RS 4 Allow informative commands: "btrfs subvolume find-new", "btrfs filesystem usage". This is used by btrbk \fIinfo\fR and \fIdiff\fR commands. .RE .PP \-\-snapshot .RS 4 Allow btrfs snapshot command: "btrfs subvolume snapshot". .RE .PP \-\-send .RS 4 Allow btrfs send command: "btrfs send". .RE .PP \-\-receive .RS 4 Allow btrfs receive command: "btrfs receive". .RE .PP \-p, \-\-restrict\-path .RS 4 Restrict btrfs commands to . .RE .PP \-l, \-\-log .RS 4 Log ACCEPT and REJECT messages to the system log. .RE .PP \-\-sudo .RS 4 Call SSH_ORIGINAL_COMMAND using sudo. .RE .SH AVAILABILITY Please refer to the btrbk project page \fBhttp://www.digint.ch/btrbk/\fR for further details. .SH SEE ALSO .BR btrbk (1), .BR btrbk.conf (5), .BR btrfs (1) .SH AUTHOR Axel Burri btrbk-0.22.2/ssh_filter_btrbk.sh000077500000000000000000000065321265410210100165640ustar00rootroot00000000000000#!/bin/bash set -e set -u export PATH=/sbin:/bin:/usr/sbin:/usr/bin enable_log= use_sudo= restrict_path_list= allow_list= log_cmd() { if [[ -n "$enable_log" ]]; then logger -p $1 -t ssh_filter_btrbk.sh "$2 (Name: ${LOGNAME:-}; Remote: ${SSH_CLIENT:-})${3:+: $3}: $SSH_ORIGINAL_COMMAND" fi } allow_cmd() { allow_list="${allow_list}|$1" } reject_and_die() { local reason=$1 log_cmd "auth.err" "btrbk REJECT" "$reason" echo "ERROR: ssh_filter_btrbk.sh: ssh command rejected: $reason: $SSH_ORIGINAL_COMMAND" 1>&2 exit 1 } run_cmd() { log_cmd "auth.info" "btrbk ACCEPT" $use_sudo $SSH_ORIGINAL_COMMAND } reject_filtered_cmd() { # note that the backslash is NOT a metacharacter in a POSIX bracket expression! option_match='-[a-zA-Z-]+' # matches short as well as long options file_match='[0-9a-zA-Z_@+./-]+' # matches file path (equal to $file_match in btrbk) if [[ -n "$restrict_path_list" ]]; then # match any of restrict_path_list with or without trailing slash, # or any file/directory (matching file_match) below restrict_path path_match="(${restrict_path_list})(/|/${file_match})?" else # match any absolute file/directory (matching file_match) path_match="/${file_match}" fi # allow multiple paths (e.g. "btrfs subvolume snapshot ") btrfs_cmd_match="^(${allow_list})( ${option_match})*( $path_match)+$" if [[ ! $SSH_ORIGINAL_COMMAND =~ $btrfs_cmd_match ]] ; then reject_and_die "disallowed command${restrict_path_list:+ (restrict-path: \"${restrict_path_list//|/\", \"}\")}" fi } allow_cmd "btrfs subvolume show"; # subvolume queries are always allowed allow_cmd "btrfs subvolume list"; # subvolume queries are always allowed while [[ "$#" -ge 1 ]]; do key="$1" case $key in -l|--log) enable_log=1 ;; --sudo) use_sudo="sudo" ;; -p|--restrict-path) restrict_path_list="${restrict_path_list}|${2%/}" # add to list while removing trailing slash shift # past argument ;; -s|--source) allow_cmd "btrfs subvolume snapshot" allow_cmd "btrfs send" ;; -t|--target) allow_cmd "btrfs receive" ;; -d|--delete) allow_cmd "btrfs subvolume delete" ;; -i|--info) allow_cmd "btrfs subvolume find-new" allow_cmd "btrfs filesystem usage" ;; --snapshot) allow_cmd "btrfs subvolume snapshot" ;; --send) allow_cmd "btrfs send" ;; --receive) allow_cmd "btrfs receive" ;; *) echo "ERROR: ssh_filter_btrbk.sh: failed to parse command line option: $key" 1>&2 exit 1 ;; esac shift done # remove leading "|" on alternation lists allow_list=${allow_list#\|} restrict_path_list=${restrict_path_list#\|} case "$SSH_ORIGINAL_COMMAND" in *\$*) reject_and_die "unsafe character" ;; *\&*) reject_and_die "unsafe character" ;; *\(*) reject_and_die "unsafe character" ;; *\{*) reject_and_die "unsafe character" ;; *\;*) reject_and_die "unsafe character" ;; *\<*) reject_and_die "unsafe character" ;; *\>*) reject_and_die "unsafe character" ;; *\`*) reject_and_die "unsafe character" ;; *\|*) reject_and_die "unsafe character" ;; *\.\./*) reject_and_die "directory traversal" ;; *) reject_filtered_cmd run_cmd ;; esac