├── .github ├── FUNDING.yml └── workflows │ └── ci-ubuntu-latest.yml ├── LICENSE ├── README.md ├── libqmpbackup ├── __init__.py ├── fs.py ├── image.py ├── lib.py ├── qa.py ├── qaclient.py ├── qmpcommon.py ├── version.py └── vm.py ├── qmpbackup ├── qmpbackup.jpg ├── qmprestore ├── requirements.txt ├── setup.py └── t ├── agent.py └── runtest /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: abbbi 2 | buy_me_a_coffee: abbbi 3 | -------------------------------------------------------------------------------- /.github/workflows/ci-ubuntu-latest.yml: -------------------------------------------------------------------------------- 1 | name: CI on ubuntu-latest 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v2 12 | - uses: abbbi/github-actions-tune@v1 13 | - name: Run codespell 14 | run: | 15 | sudo apt-get update 16 | sudo apt-get install codespell -y 17 | codespell README.md 18 | codespell qmpbackup 19 | codespell qmprestore 20 | codespell libqmpbackup/ 21 | - name: Python code format test 22 | run: | 23 | sudo pip3 install black==25.1.0 24 | black --check qmprestore 25 | black --check qmpbackup 26 | black --check . 27 | - name: Install QEMU 28 | run: | 29 | sudo apt-get update 30 | sudo apt-get install -y qemu-system-x86 libguestfs-tools 31 | - name: Install qmpbackup and requirements 32 | run: | 33 | sudo pip3 install -r requirements.txt 34 | sudo python3 setup.py install 35 | - name: Execute testscript 36 | run: cd t && sudo sh runtest 37 | - name: Execute 38 | run: | 39 | qmpbackup -h 40 | qmprestore -h 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![ci](https://github.com/abbbi/qmpbackup/actions/workflows/ci-ubuntu-latest.yml/badge.svg) 2 | 3 | qmpbackup 4 | ========= 5 | 6 | qmpbackup is designed to create live full and incremental backups of running 7 | qemu virtual machines via QMP protocol. It makes use of the dirty-bitmap 8 | feature introduced in later QEMU versions. It works with standalone QEMU 9 | processes. 10 | 11 | ![ScreenShot](https://raw.githubusercontent.com/abbbi/qmpbackup/refs/heads/master/qmpbackup.jpg) 12 | 13 | If you want to backup QEMU virtual machines managed by `libvirt`, see this 14 | project: 15 | 16 | https://github.com/abbbi/virtnbdbackup 17 | 18 | 19 | 20 | 21 | **Table of Contents** 22 | 23 | - [Installation](#installation) 24 | - [Prerequisites](#prerequisites) 25 | - [Usage](#usage) 26 | - [Backup](#backup) 27 | - [Backup chains / unique bitmap names](#backup-chains--unique-bitmap-names) 28 | - [Monthly Backups](#monthly-backups) 29 | - [Excluding disks from backup](#excluding-disks-from-backup) 30 | - [Filesystem Freeze](#filesystem-freeze) 31 | - [Offline virtual machines](#offline-virtual-machines) 32 | - [UEFI / BIOS (pflash devices)](#uefi--bios-pflash-devices) 33 | - [Restore](#restore) 34 | - [Regular Rebase](#regular-rebase) 35 | - [Rebase with commit](#rebase-with-commit) 36 | - [Rebase into a new image](#rebase-into-a-new-image) 37 | - [Rebase with adding snapshots](#rebase-with-adding-snapshots) 38 | - [Misc commands and options](#misc-commands-and-options) 39 | - [Compressing backups](#compressing-backups) 40 | - [List devices suitable for backup](#list-devices-suitable-for-backup) 41 | - [Including raw devices (lvm, zfs, ceph)](#including-raw-devices-lvm-zfs-ceph) 42 | - [List existing bitmaps](#list-existing-bitmaps) 43 | - [Cleanup bitmaps](#cleanup-bitmaps) 44 | - [Speed limit](#speed-limit) 45 | - [Hypervisors](#hypervisors) 46 | - [Proxmox](#proxmox) 47 | - [Limitations](#limitations) 48 | 49 | 50 | 51 | # Installation 52 | 53 | *qmpbackup* makes use of [qemu.qmp](https://gitlab.com/jsnow/qemu.qmp) 54 | 55 | ``` 56 | python3 -m venv venv 57 | source venv/bin/activate 58 | pip3 install -r requirements.txt 59 | python3 setup.py install (alternatively use: `python -m pip install .` on systems deprecating setuptools) 60 | ``` 61 | 62 | # Prerequisites 63 | 64 | The virtual machine must be reachable via QMP protocol on a unix socket, 65 | usually this happens by starting the virtual machine via: 66 | 67 | ``` 68 | qemu-system- -qmp unix:/path/to/socket,server,nowait 69 | ``` 70 | 71 | *qmpbackup* uses this socket to pass required commands to the virtual machine. 72 | 73 | `Note:` Use a dedicated socket for backup operations if possible, as qmp 74 | sockets only allow one connection at a time. 75 | 76 | # Usage 77 | 78 | In order to create a full backup use the following command: 79 | 80 | ``` 81 | # remove already existent bitmaps from prior full backups: 82 | qmpbackup --socket /path/to/socket cleanup --remove-bitmaps 83 | # create a new full backup to an empty directory: 84 | qmpbackup --socket /path/to/socket backup --level full --target /tmp/backup/ 85 | ``` 86 | 87 | the command will create a new unique dirty bitmap and backup the virtual 88 | machines disks to ```/tmp/backup//FULL-```. It ensures 89 | consistency by creating the bitmap and backup within one QMP transaction. 90 | 91 | Multiple disks attached to the virtual machine are backed up concurrently. 92 | 93 | During full and incremental backup, bitmaps will be created with `persistent 94 | option flag`. This means QEMU attempts to store them in the QCOW images, so 95 | they are available between virtual machine shutdowns. The attached QCOW images 96 | must be in qcow(v3) format, for this to work. 97 | 98 | If you can't convert your QCOW images to newer formats, you still can use the 99 | backup mode `copy`: it allows to execute a complete full backup but no further 100 | incremental backups. 101 | 102 | Second step is to change some data within your virtual machine and let 103 | *qmpbackup* create an incremental backup for you, this works by: 104 | 105 | ``` 106 | qmpbackup --socket /path/to/socket backup --level inc --target /tmp/backup/ 107 | ``` 108 | 109 | The changed delta since your last full (or inc) backup will be dumped to 110 | `/tmp/backup//INC-`, the dirty-bitmap is automatically 111 | cleared after this and you can continue creating further incremental backups by 112 | re-issuing the command likewise. 113 | 114 | There is also the `auto` backup level which combines the `full` and `inc` 115 | backup levels. If there's no existing bitmap for the VM, `full` will run. If a 116 | bitmap exists, `inc` will be used. 117 | 118 | # Backup 119 | 120 | ## Backup chains / unique bitmap names 121 | 122 | By default a new full backup to an empty directory will create a new unique id 123 | for the bitmap that is used to start a new backup chain. 124 | 125 | This way you can create multiple backup chains, each of them using an 126 | unique bitmap to track the changes. 127 | 128 | The `qmpbackup` utility will not cleanup those bitmaps by default if you can 129 | cleanup bitmaps that are not required via: 130 | 131 | ``` 132 | qmpbackup --socket /path/to/socket cleanup --remove-bitmaps 133 | qmpbackup --socket /path/to/socket cleanup --remove-bitmaps --uuid 134 | ``` 135 | 136 | Alternatively you can specify the uuid to be used for the bitmap names during 137 | the first full backup you create. This way the bitmaps will be re-used and must 138 | not be cleaned: 139 | 140 | ``` 141 | qmpbackup --socket /path/to/socket backup -l full -t /tmp/backup --uuid testme 142 | qmpbackup --socket /path/to/socket backup -l inc -t /tmp/backup 143 | ``` 144 | 145 | ## Monthly Backups 146 | 147 | Using the `--monthly` flag with the `backup` command, backups will be placed in 148 | monthly folders in a YYYY-MM format. The above combined with the `auto` backup 149 | level, backups will be created in monthly backup chains. 150 | 151 | Executing the backup and the date being 2021-11, the following command: 152 | 153 | `qmpbackup --socket /path/to/socket backup --level auto --monthly --target /tmp/backup` 154 | 155 | will place backups in the following backup path: `/tmp/backup/2021-11/` 156 | 157 | When the date changes to 2021-12 and *qmpbackup* is executed, backups will be 158 | placed in `/tmp/backup/2021-12/` and a new full backup will be created. 159 | 160 | ## Excluding disks from backup 161 | 162 | Disks can be excluded from the backup by using the *--exclude* option, the name 163 | must match the devices "node" name (use the *info --show blockdev* option to 164 | get a list of attached block devices considered for backup) 165 | 166 | If only specific disks should be saved, use the *--include* option. 167 | 168 | ## Filesystem Freeze 169 | 170 | In case the virtual machine has an guest agent installed you can set the QEMU 171 | Guest Agent socket (*--agent-socket*) and request filesystem quiesce via 172 | *--quiesce* option: 173 | 174 | ``` 175 | qmpbackup --socket /path/to/socket --agent-socket /tmp/qga.sock backup --level full --target /tmp/ --quisce 176 | ``` 177 | 178 | Use the following options to QEMU to enable an guest agent socket: 179 | 180 | ``` 181 | -chardev socket,path=/tmp/qga.sock,server,nowait,id=qga0 \ 182 | -device virtio-serial \ 183 | -device "virtserialport,chardev=qga0,name=org.qemu.guest_agent.0" \ 184 | ``` 185 | 186 | ## Offline virtual machines 187 | 188 | If you want to backup virtual machines without the virtual machine being in 189 | fully operational state, it is sufficient to bring up the QEMU process in 190 | `prelaunch` mode (The QEMU blocklayer is operational but no code is executed): 191 | 192 | ``` 193 | qemu-system- -S 194 | ``` 195 | 196 | ## UEFI / BIOS (pflash devices) 197 | 198 | If the virtual machine uses UEFI, it usually has attached `pflash` devices 199 | pointing to the UEFI firmware and variables files. These will be included in 200 | the backup by default. 201 | 202 | 203 | # Restore 204 | 205 | Restoring your data is a matter of rebasing the created qcow images by using 206 | standard tools such as *qemu-img* or *qmprestore*. There are three major 207 | features implemented within the restore command: rebase, merge and 208 | snapshotrebase. 209 | 210 | The `rebase` and `snapshotrebase` commands will alter the directory 211 | in-place: this means your backup files will be changed. 212 | 213 | The `merge` functionality will merge the data into a separate, new qcow file 214 | outside of your backup folder. 215 | 216 | A image backup based on a backup folder containing the following backups: 217 | 218 | ``` 219 | /tmp/backup/ide0-hd0/ 220 | ├── FULL-1706260639-disk1.qcow2 221 | ├── INC-1706260646-disk1.qcow2 222 | └── INC-1706260647-disk1.qcow2 223 | ``` 224 | 225 | can be recovered the following ways: 226 | 227 | ## Regular Rebase 228 | 229 | 230 | A regular rebase will update the backing image for each backup file in-place: 231 | 232 | ``` 233 | qmprestore rebase --dir /tmp/backup/ide0-hd0 234 | ``` 235 | 236 | After rebase you will find an symlink `/tmp/backup/image`, which points to the 237 | latest image to use with qemu or other tools. 238 | 239 | `Note:` It makes sense to copy the existing backup directory to a temporary 240 | folder before rebasing, if you do not want to alter your existing backups. 241 | 242 | Using the `--until` option rollback to a specific incremental point in 243 | time is possible: 244 | 245 | ``` 246 | qmprestore rebase --dir /tmp/backup/ide0-hd0 --until INC-1480542701 247 | ``` 248 | 249 | ## Rebase with commit 250 | 251 | If you want to rebase and actually commit back the changes to the images use: 252 | 253 | ``` 254 | qmprestore commit --dir /tmp/backup/ide0-hd0 255 | ``` 256 | 257 | After rebase you will find the merged image file with all changes committed 258 | in the target folder. 259 | 260 | `Note:` It makes sense to copy the existing backup directory to a temporary 261 | folder before rebasing, if you do not want to alter your existing backups. 262 | 263 | 264 | ## Rebase into a new image 265 | 266 | It is also possible to restore and rebase the backup files into a new target 267 | file image, without altering the original backup files: 268 | 269 | ``` 270 | qmprestore merge --dir /tmp/backup/ide0-hd0/ --targetfile /tmp/restore/disk1.qcow2 271 | ``` 272 | 273 | ## Rebase with adding snapshots 274 | 275 | Using the `snapshotrebase` functionality it is possible to rebase/commit the 276 | images back into an full backup, but additionally the rebase process will 277 | create an internal snapshot for the qemu image, for each incremental backup 278 | applied. 279 | 280 | This way it is easily possible to switch between the backup states after 281 | rebasing. 282 | 283 | ``` 284 | qmprestore snapshotrebase --dir /tmp/backup/ide0-hd0/ 285 | [..] 286 | qemu-img snapshot -l /tmp/backup/ide0-hd0/FULL-1706260639-disk1.qcow2 287 | Snapshot list: 288 | ID TAG VM SIZE DATE VM CLOCK ICOUNT 289 | 1 FULL-BACKUP 0 B 2024-10-21 12:50:45 00:00:00.000 0 290 | 2 2024-10-21-12:42:48 0 B 2024-10-22 09:23:39 00:00:00.000 0 291 | 3 2024-10-21-12:42:49 0 B 2024-10-22 09:23:39 00:00:00.000 0 292 | ``` 293 | 294 | # Misc commands and options 295 | 296 | ## Compressing backups 297 | 298 | The `--compress` option can be used to enable compression for target files 299 | during the `blockdev-backup` operation. This can save quite some storage space on 300 | the created target images, but may slow down the backup operation. 301 | 302 | ``` 303 | qmpbackup --socket /path/to/socket backup [..] --compress 304 | ``` 305 | 306 | ## List devices suitable for backup 307 | 308 | ``` 309 | qmpbackup --socket /path/to/socket info --show blockdev 310 | ``` 311 | 312 | ## Including raw devices (lvm, zfs, ceph) 313 | 314 | Attached raw devices (format: raw) do not support incremental backup. The 315 | only way to create backups for these devices is to create a complete full 316 | or copy backup. 317 | 318 | By default `qmpbackup` will ignore such devices, but you can use the 319 | `--include-raw` option to create a backup for those devices too. 320 | 321 | Of course, if you create an incremental backup for these devices, the complete 322 | image will be backed up. 323 | 324 | ## List existing bitmaps 325 | 326 | To query existing bitmaps information use: 327 | 328 | ``` 329 | qmpbackup --socket /path/to/socket info --show bitmaps 330 | ``` 331 | 332 | ## Cleanup bitmaps 333 | 334 | In order to remove existing dirty-bitmaps use: 335 | 336 | ``` 337 | qmpbackup --socket /path/to/socket cleanup --remove-bitmaps 338 | ``` 339 | 340 | If you create a new backup chain (new full backup to an empty 341 | directory) you should cleanup old bitmaps before. 342 | 343 | ## Speed limit 344 | 345 | You can set an speed limit (bytes per second) for all backup operations to 346 | limit throughput: 347 | 348 | ``` 349 | qmpbackup --socket /path/to/socket backup [..] --speed-limit 2000000 350 | ``` 351 | 352 | # Hypervisors 353 | 354 | ## Proxmox 355 | 356 | To backup virtual machines running on Proxmox hypervisors it is recommended to 357 | re-configure the virtual machines to provide a second dedicated qmp socket. 358 | This can be done using the `qm` command. 359 | 360 | First, show the command line that is used to start the vm (id 110 in this 361 | example): 362 | 363 | ``` 364 | qm stop 110 365 | qm showcmd 110 366 | /usr/bin/kvm -id 110 -name [..] -chardev 'socket,id=qmp,path=/var/run/qemu-server/110.qmp,server=on,wait=off' 367 | ``` 368 | 369 | Now add an additional command line parameter to the VM configuration: 370 | 371 | ``` 372 | qm set 110 --args "-chardev 'socket,id=qmp-backup,path=/var/run/qemu-server/110-backup.qmp,server=on,wait=off' -mon 'chardev=qmp-backup,mode=control'" 373 | update VM 110: -args -chardev 'socket,id=qmp-backup,path=/var/run/qemu-server/110-backup.qmp,server=on,wait=off' -mon 'chardev=qmp-backup,mode=control' 374 | qm start 110 375 | ``` 376 | 377 | After the VM has started, a new qmp socket is available for backup: 378 | 379 | ``` 380 | ls -ah /var/run/qemu-server/110-backup.qmp 381 | /var/run/qemu-server/110-backup.qmp 382 | qmpbackup --socket /var/run/qemu-server/110-backup.qmp backup [..] 383 | ``` 384 | 385 | 386 | # Limitations 387 | 388 | 1) Using the QMP protocol it cannot be used together with libvirt as libvirt 389 | exclusively uses the virtual machines monitor socket. See 390 | [virtnbdbackup](https://github.com/abbbi/virtnbdbackup). 391 | 392 | 2) QEMUs ```drive-backup``` function does currently not support dumping 393 | data as a stream, it also cannot work with fifo pipes as the blockdriver 394 | expects functions like ftruncate and fseek to work on the target file, so the 395 | backup target must be a directory. 396 | -------------------------------------------------------------------------------- /libqmpbackup/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abbbi/qmpbackup/6f3a7767361fd4e4ccd10c00ce09a17600426ea2/libqmpbackup/__init__.py -------------------------------------------------------------------------------- /libqmpbackup/fs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | qmpbackup: Full an incremental backup using Qemus 4 | dirty bitmap feature 5 | 6 | Copyright (C) 2024 Michael Ablassmeier 7 | 8 | Authors: 9 | Michael Ablassmeier 10 | 11 | This work is licensed under the terms of the GNU GPL, version 3. See 12 | the LICENSE file in the top-level directory. 13 | """ 14 | import logging 15 | 16 | log = logging.getLogger(__name__) 17 | 18 | 19 | def get_state(qga): 20 | """Return filesystem state""" 21 | try: 22 | reply = qga.fsfreeze("status") 23 | return reply 24 | except RuntimeError as errmsg: 25 | log.warning("Unable to get Filesystem status: %s", errmsg) 26 | 27 | return None 28 | 29 | 30 | def quiesce(qga): 31 | """Quiesce VM filesystem""" 32 | fsstate = get_state(qga) 33 | if fsstate == "frozen": 34 | log.warning("Filesystem is already frozen") 35 | return True 36 | 37 | try: 38 | reply = qga.fsfreeze("freeze") 39 | log.info('"%s" Filesystem(s) freezed', reply) 40 | return True 41 | except RuntimeError as errmsg: 42 | log.warning('Unable to freeze: "%s"', errmsg) 43 | 44 | return False 45 | 46 | 47 | def thaw(qga): 48 | """Thaw filesystems""" 49 | fsstate = get_state(qga) 50 | if fsstate == "thawed": 51 | log.info("Filesystem is already thawed, skipping.") 52 | return True 53 | try: 54 | reply = qga.fsfreeze("thaw") 55 | log.info('"%s" filesystem(s) thawed', reply) 56 | return True 57 | except RuntimeError as errmsg: 58 | log.warning('Unable to thaw filesystem: "%s"', errmsg) 59 | 60 | return False 61 | -------------------------------------------------------------------------------- /libqmpbackup/image.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | qmpbackup: Full an incremental backup using Qemus 4 | dirty bitmap feature 5 | 6 | Copyright (C) 2022 Michael Ablassmeier 7 | 8 | Authors: 9 | Michael Ablassmeier 10 | 11 | This work is licensed under the terms of the GNU GPL, version 3. See 12 | the LICENSE file in the top-level directory. 13 | """ 14 | import os 15 | import json 16 | import logging 17 | import subprocess 18 | import datetime 19 | from time import time 20 | from libqmpbackup import lib 21 | 22 | log = logging.getLogger(__name__) 23 | 24 | 25 | def get_info(filename): 26 | """Query original qemu image information, can be used to re-create 27 | the image during backup operation with the same options as the 28 | original one.""" 29 | try: 30 | return subprocess.check_output( 31 | ["qemu-img", "info", f"{filename}", "--output", "json", "--force-share"] 32 | ) 33 | except subprocess.CalledProcessError as errmsg: 34 | raise RuntimeError from errmsg 35 | 36 | 37 | def save_info(backupdir, blockdev): 38 | """Save qcow image information""" 39 | for dev in blockdev: 40 | infofile = os.path.join(backupdir, f"{os.path.basename(dev.filename)}.config") 41 | 42 | if dev.driver == "rbd": 43 | log.info("Skip saving image information for RBD device: [%s]", dev.filename) 44 | continue 45 | 46 | info = get_info(dev.filename) 47 | try: 48 | with open(infofile, "wb+") as info_file: 49 | info_file.write(info) 50 | log.info("Saved image info: [%s]", infofile) 51 | except IOError as errmsg: 52 | raise RuntimeError(f"Unable to store qcow config: [{errmsg}]") from errmsg 53 | except Exception as errmsg: 54 | raise RuntimeError(errmsg) from errmsg 55 | 56 | 57 | def _get_options_cmd(backupdir, dev): 58 | """Read options to apply for backup target image from 59 | qcow image info json output""" 60 | opt = [] 61 | with open( 62 | os.path.join(backupdir, f"{os.path.basename(dev.filename)}.config"), "rb" 63 | ) as config_file: 64 | qcow_config = json.loads(config_file.read().decode()) 65 | 66 | try: 67 | opt.append("-o") 68 | opt.append(f"compat={qcow_config['format-specific']['data']['compat']}") 69 | except KeyError as errmsg: 70 | log.warning("Unable apply QCOW specific compat option: [%s]", errmsg) 71 | 72 | try: 73 | opt.append("-o") 74 | opt.append(f"cluster_size={qcow_config['cluster-size']}") 75 | except KeyError as errmsg: 76 | log.warning("Unable apply QCOW specific cluster_size option: [%s]", errmsg) 77 | 78 | try: 79 | if qcow_config["format-specific"]["data"]["lazy-refcounts"]: 80 | opt.append("-o") 81 | opt.append("lazy_refcounts=on") 82 | except KeyError as errmsg: 83 | log.warning("Unable apply QCOW specific lazy_refcounts option: [%s]", errmsg) 84 | 85 | return opt 86 | 87 | 88 | def create(argv, backupdir, blockdev): 89 | """Create target image used by qmp blockdev-backup image to dump 90 | data and returns a list of target images per-device, which will 91 | be used as parameter for QMP drive-backup operation""" 92 | opt = [] 93 | backup_targets = {} 94 | fleece_targets = {} 95 | timestamp = int(time()) 96 | for dev in blockdev: 97 | 98 | nodname = dev.node 99 | if dev.node.startswith("#block"): 100 | log.warning( 101 | "No node name set for [%s], falling back to device name: [%s]", 102 | dev.filename, 103 | dev.device, 104 | ) 105 | nodname = dev.device 106 | 107 | if argv.no_subdir is True: 108 | targetdir = backupdir 109 | else: 110 | targetdir = os.path.join(backupdir, nodname) 111 | os.makedirs(targetdir, exist_ok=True) 112 | if argv.no_timestamp and argv.level in ("copy", "full"): 113 | filename = f"{os.path.basename(dev.filename)}.partial" 114 | else: 115 | filename = f"{argv.level.upper()}-{timestamp}-{os.path.basename(dev.filename)}.partial" 116 | target = os.path.join(targetdir, filename) 117 | if dev.format != "raw": 118 | opt = opt + _get_options_cmd(backupdir, dev) 119 | 120 | cmd = [ 121 | "qemu-img", 122 | "create", 123 | "-f", 124 | f"{dev.format}", 125 | f"{target}", 126 | "-o", 127 | f"size={dev.virtual_size}", 128 | ] 129 | if dev.format != "raw": 130 | cmd = cmd + opt 131 | 132 | fleece_filename = ( 133 | f"{argv.level.upper()}-{timestamp}-{nodname}.fleece.{dev.format}" 134 | ) 135 | fleece_targetfile = os.path.join(dev.path, fleece_filename) 136 | fleece_cmd = [ 137 | "qemu-img", 138 | "create", 139 | "-f", 140 | f"{dev.format}", 141 | f"{fleece_targetfile}", 142 | "-o", 143 | f"size={dev.virtual_size}", 144 | ] 145 | 146 | try: 147 | log.info( 148 | "Create target backup image: [%s], virtual size: [%s]", 149 | target, 150 | dev.virtual_size, 151 | ) 152 | log.debug(cmd) 153 | subprocess.check_output(cmd) 154 | backup_targets[dev.node] = target 155 | 156 | log.info( 157 | "Create fleece image: [%s], virtual size: [%s]", 158 | fleece_targetfile, 159 | dev.virtual_size, 160 | ) 161 | log.debug(fleece_cmd) 162 | subprocess.check_output(fleece_cmd) 163 | fleece_targets[dev.node] = fleece_targetfile 164 | 165 | except subprocess.CalledProcessError as errmsg: 166 | raise RuntimeError from errmsg 167 | 168 | return backup_targets, fleece_targets 169 | 170 | 171 | def clone(image, targetfile): 172 | """Copy base image for restore into new image file""" 173 | if os.path.exists(targetfile): 174 | log.error("Target file [%s] already exists, won't overwrite", targetfile) 175 | return False 176 | 177 | log.info("Copy source image [%s] to image file: [%s]", image, targetfile) 178 | 179 | try: 180 | lib.copyfile(image, targetfile) 181 | except RuntimeError as errmsg: 182 | log.error(errmsg) 183 | return False 184 | 185 | return True 186 | 187 | 188 | def _check(image, argv): 189 | """before rebase we check consistency of all files""" 190 | if argv.skip_check is True: 191 | log.info("Skipping image check") 192 | return 193 | check_cmd = f"qemu-img check '{image}'" 194 | try: 195 | log.info(check_cmd) 196 | subprocess.check_output(check_cmd, shell=True) 197 | except subprocess.CalledProcessError as errmsg: 198 | raise RuntimeError(f"Consistency check failed: {errmsg}") from errmsg 199 | 200 | 201 | def _snapshot_exists(snapshot, image): 202 | """before rebase we check if an snapshot already exists""" 203 | check_cmd = f"qemu-img snapshot -l '{image}'" 204 | try: 205 | log.info(check_cmd) 206 | output = subprocess.check_output(check_cmd, shell=True) 207 | except subprocess.CalledProcessError as errmsg: 208 | raise RuntimeError(f"Consistency check failed: {errmsg}") from errmsg 209 | 210 | if snapshot in output.decode(): 211 | return True 212 | 213 | return False 214 | 215 | 216 | def merge(argv): 217 | """Merge all files into new base image""" 218 | try: 219 | images, images_flat = lib.get_images(argv) 220 | except RuntimeError as errmsg: 221 | log.error(errmsg) 222 | return False 223 | 224 | idx = len(images) - 1 225 | if argv.until is not None: 226 | sidx = images_flat.index(argv.until) 227 | 228 | targetdir = os.path.dirname(argv.targetfile) 229 | if not clone(images[0], argv.targetfile): 230 | return False 231 | images[0] = argv.targetfile 232 | 233 | for image in reversed(images): 234 | idx = idx - 1 235 | if argv.until is not None and idx >= sidx: 236 | log.info("Skipping checkpoint: %s as requested with --until option", image) 237 | continue 238 | 239 | if images.index(image) == 0 or argv.targetfile in images[images.index(image)]: 240 | log.info( 241 | "Rollback of latest [FULL]<-[INC] chain complete, ignoring older chains" 242 | ) 243 | break 244 | 245 | log.debug('"%s" is based on "%s"', image, images[idx]) 246 | 247 | tgtfile = os.path.join(targetdir, os.path.basename(image)) 248 | if not os.path.exists(tgtfile): 249 | if not clone(image, tgtfile): 250 | return False 251 | 252 | tgtfile = os.path.join(targetdir, os.path.basename(images[idx])) 253 | if not os.path.exists(tgtfile): 254 | if not clone(images[idx], tgtfile): 255 | return False 256 | 257 | try: 258 | rebase_cmd = ( 259 | "qemu-img rebase -f qcow2 -F qcow2 -b " 260 | f'"{targetdir}/{os.path.basename(images[idx])}" ' 261 | f'"{targetdir}/{os.path.basename(image)}" -u' 262 | ) 263 | log.info(rebase_cmd) 264 | subprocess.check_output(rebase_cmd, shell=True) 265 | commit_cmd = ( 266 | "qemu-img commit -b " 267 | f'"{targetdir}/{os.path.basename(images[idx])}" ' 268 | f'"{targetdir}/{os.path.basename(image)}"' 269 | ) 270 | if argv.rate_limit != 0: 271 | commit_cmd = f"{commit_cmd} -r {argv.rate_limit}" 272 | log.info(commit_cmd) 273 | subprocess.check_output(commit_cmd, shell=True) 274 | if image != argv.targetfile: 275 | fname = os.path.join(targetdir, os.path.basename(image)) 276 | log.info( 277 | "Removing temporary file after merge: [%s]", 278 | fname, 279 | ) 280 | os.unlink(fname) 281 | except subprocess.CalledProcessError as errmsg: 282 | log.error("Rebase or commit command failed: [%s]", errmsg) 283 | return False 284 | 285 | return True 286 | 287 | 288 | def rebase(argv): 289 | """Rebase all images in a directory without merging 290 | the data back into the base image""" 291 | link = os.path.join(argv.dir, "image") 292 | if os.path.exists(link): 293 | log.error("Directory has already been rebased: [%s]", link) 294 | return False 295 | 296 | try: 297 | images, images_flat = lib.get_images(argv) 298 | except RuntimeError as errmsg: 299 | log.error(errmsg) 300 | return False 301 | 302 | if "FULL-" in images[-1]: 303 | log.error("No incremental images found, nothing to rebase.") 304 | return False 305 | 306 | idx = len(images) - 1 307 | 308 | try: 309 | _check(images[0], argv) 310 | except RuntimeError as errmsg: 311 | log.error(errmsg) 312 | return False 313 | 314 | if argv.until is not None: 315 | sidx = images_flat.index(argv.until) 316 | 317 | for image in reversed(images): 318 | idx = idx - 1 319 | if argv.until is not None and idx >= sidx: 320 | log.info("Skipping checkpoint: %s as requested with --until option", image) 321 | continue 322 | 323 | if images.index(image) == 0 or "FULL-" in images[images.index(image)]: 324 | log.info( 325 | "Rollback of latest [FULL]<-[INC] chain complete, ignoring older chains" 326 | ) 327 | log.info("You can use [%s] to access the latest image data.", link) 328 | break 329 | 330 | log.debug('"%s" is based on "%s"', image, images[idx]) 331 | 332 | try: 333 | _check(image, argv) 334 | except RuntimeError as errmsg: 335 | log.error(errmsg) 336 | return False 337 | 338 | try: 339 | rebase_cmd = ( 340 | f'qemu-img rebase -f qcow2 -F qcow2 -b "{images[idx]}" "{image}" -u' 341 | ) 342 | log.info(rebase_cmd) 343 | if not argv.dry_run: 344 | subprocess.check_output(rebase_cmd, shell=True) 345 | except subprocess.CalledProcessError as errmsg: 346 | log.error("Rebase command failed: [%s]", errmsg) 347 | return False 348 | 349 | if not argv.dry_run: 350 | try: 351 | os.symlink(images[-1], "image") 352 | except OSError as errmsg: 353 | logging.warning("Unable to create symlink to latest image: [%s]", errmsg) 354 | 355 | return True 356 | 357 | 358 | def snapshot_rebase(argv): 359 | """Rebase the images, commit all changes but create a snapshot 360 | prior""" 361 | try: 362 | images, _ = lib.get_images(argv) 363 | except RuntimeError as errmsg: 364 | log.error(errmsg) 365 | return False 366 | 367 | if "FULL-" in images[-1] or len(images) == 1: 368 | log.error("No incremental images found, nothing to rebase.") 369 | return False 370 | 371 | try: 372 | _check(images[0], argv) 373 | except RuntimeError as errmsg: 374 | log.error(errmsg) 375 | return False 376 | 377 | if not _snapshot_exists("FULL-BACKUP", images[0]): 378 | snapshot_cmd = f'qemu-img snapshot -c "FULL-BACKUP" "{images[0]}"' 379 | log.info(snapshot_cmd) 380 | try: 381 | if not argv.dry_run: 382 | subprocess.check_output(snapshot_cmd, shell=True) 383 | except subprocess.CalledProcessError as errmsg: 384 | log.error("Rebase command failed: [%s]", errmsg) 385 | return False 386 | else: 387 | log.info("Skip creation of already existent full backup snapshot") 388 | 389 | for image in images[1:]: 390 | try: 391 | _check(image, argv) 392 | except RuntimeError as errmsg: 393 | log.error(errmsg) 394 | return False 395 | 396 | imagebase = os.path.basename(image) 397 | if imagebase.startswith("INC"): 398 | log.info("Using timestamp as provided by from image name") 399 | timestamp = int(imagebase.split("-")[1]) 400 | else: 401 | log.info( 402 | "No timestamp provided in image name, use timestamp from filesystem" 403 | ) 404 | timestamp = int(os.path.getctime(image)) 405 | 406 | snapshot_name = datetime.datetime.fromtimestamp(timestamp).strftime( 407 | "%Y-%m-%d-%H:%M:%S" 408 | ) 409 | 410 | try: 411 | snapshot_cmd = f'qemu-img snapshot -c "{snapshot_name}" "{images[0]}"' 412 | log.info(snapshot_cmd) 413 | rebase_cmd = ( 414 | f'qemu-img rebase -f qcow2 -F qcow2 -b "{images[0]}" "{image}" -u' 415 | ) 416 | log.info(rebase_cmd) 417 | commit_cmd = "qemu-img commit -b " f'"{images[0]}" ' f'"{image}"' 418 | if argv.rate_limit != 0: 419 | commit_cmd = f"{commit_cmd} -r {argv.rate_limit}" 420 | log.info(commit_cmd) 421 | if not argv.dry_run: 422 | subprocess.check_output(rebase_cmd, shell=True) 423 | subprocess.check_output(commit_cmd, shell=True) 424 | subprocess.check_output(snapshot_cmd, shell=True) 425 | except subprocess.CalledProcessError as errmsg: 426 | log.error("Rebase command failed: [%s]", errmsg) 427 | return False 428 | 429 | if not argv.dry_run: 430 | log.info("Removing: [%s]", image) 431 | os.remove(image) 432 | 433 | if argv.until is not None and os.path.basename(image) == argv.until: 434 | log.info( 435 | "Stopping at checkpoint: %s as requested with --until option", image 436 | ) 437 | break 438 | 439 | return True 440 | 441 | 442 | def commit(argv): 443 | """Rebase and commit all changes""" 444 | try: 445 | images, _ = lib.get_images(argv) 446 | except RuntimeError as errmsg: 447 | log.error(errmsg) 448 | return False 449 | 450 | if "FULL-" in images[-1] or len(images) == 1: 451 | log.error("No incremental images found, nothing to rebase.") 452 | return False 453 | 454 | try: 455 | _check(images[0], argv) 456 | except RuntimeError as errmsg: 457 | log.error(errmsg) 458 | return False 459 | 460 | for image in images[1:]: 461 | try: 462 | _check(image, argv) 463 | except RuntimeError as errmsg: 464 | log.error(errmsg) 465 | return False 466 | 467 | try: 468 | rebase_cmd = ( 469 | f'qemu-img rebase -f qcow2 -F qcow2 -b "{images[0]}" "{image}" -u' 470 | ) 471 | log.info(rebase_cmd) 472 | commit_cmd = f"qemu-img commit '{image}'" 473 | if argv.rate_limit != 0: 474 | commit_cmd = f"{commit_cmd} -r {argv.rate_limit}" 475 | log.info(commit_cmd) 476 | if not argv.dry_run: 477 | subprocess.check_output(rebase_cmd, shell=True) 478 | subprocess.check_output(commit_cmd, shell=True) 479 | except subprocess.CalledProcessError as errmsg: 480 | log.error("Rebase command failed: [%s]", errmsg) 481 | return False 482 | 483 | if not argv.dry_run: 484 | log.info("Removing: [%s]", image) 485 | os.remove(image) 486 | 487 | if argv.until is not None and os.path.basename(image) == argv.until: 488 | log.info( 489 | "Stopping at checkpoint: %s as requested with --until option", image 490 | ) 491 | break 492 | 493 | return True 494 | -------------------------------------------------------------------------------- /libqmpbackup/lib.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | qmpbackup: Full an incremental backup using Qemus 4 | dirty bitmap feature 5 | 6 | Copyright (C) 2022 Michael Ablassmeier 7 | 8 | Authors: 9 | Michael Ablassmeier 10 | 11 | This work is licensed under the terms of the GNU GPL, version 3. See 12 | the LICENSE file in the top-level directory. 13 | """ 14 | import os 15 | import sys 16 | import shutil 17 | import uuid 18 | from json import dumps as json_dumps 19 | from glob import glob 20 | import logging 21 | import logging.handlers 22 | import colorlog 23 | from libqmpbackup.qaclient import QemuGuestAgentClient 24 | 25 | log = logging.getLogger(__name__) 26 | 27 | 28 | def has_full(directory, filename): 29 | """Check if directory contains full backup, either by searching 30 | for files beginning with FULL* or the file name of the disk 31 | itself (if --no-symlink/--no-subdir is used) 32 | """ 33 | if len(glob(f"{directory}/FULL*")) == 0 and not os.path.exists( 34 | os.path.join(directory, os.path.basename(filename)) 35 | ): 36 | return False 37 | 38 | return True 39 | 40 | 41 | def setup_log(argv): 42 | """setup logging""" 43 | log_format_colored = ( 44 | "%(green)s[%(asctime)s]%(reset)s%(blue)s %(log_color)s%(levelname)7s%(reset)s " 45 | "- %(funcName)s" 46 | ":%(log_color)s %(message)s" 47 | ) 48 | log_format = "[%(asctime)-15s] %(levelname)7s - %(funcName)s %(message)s" 49 | if argv.debug: 50 | loglevel = logging.DEBUG 51 | else: 52 | loglevel = logging.INFO 53 | stdout = logging.StreamHandler(stream=sys.stdout) 54 | handler = [] 55 | formatter = colorlog.ColoredFormatter( 56 | log_format_colored, 57 | log_colors={ 58 | "WARNING": "yellow", 59 | "ERROR": "red", 60 | "DEBUG": "cyan", 61 | "CRITICAL": "red", 62 | }, 63 | ) 64 | stdout.setFormatter(formatter) 65 | handler.append(stdout) 66 | if argv.syslog is True: 67 | handler.append(logging.handlers.SysLogHandler(address="/dev/log")) 68 | if argv.logfile != "": 69 | logpath = os.path.dirname(argv.logfile) 70 | if logpath != "": 71 | os.makedirs(logpath, exist_ok=True) 72 | handler.append(logging.FileHandler(argv.logfile, mode="a")) 73 | logging.basicConfig(format=log_format, level=loglevel, handlers=handler) 74 | return logging.getLogger(__name__) 75 | 76 | 77 | def json_pp(json): 78 | """human readable json output""" 79 | return json_dumps(json, indent=4, sort_keys=True) 80 | 81 | 82 | def has_partial(backupdir): 83 | """Check if partial backup exists in target directory""" 84 | if os.path.exists(backupdir): 85 | if len(glob(f"{backupdir}/*.partial")) > 0: 86 | return True 87 | 88 | return False 89 | 90 | 91 | def check_bitmap_uuid(bitmaps, backup_uuid): 92 | """Check if the UUID of the backup target folder matches the 93 | bitmap uuid""" 94 | for bitmap in bitmaps: 95 | if bitmap["name"].endswith(backup_uuid): 96 | return True 97 | 98 | return False 99 | 100 | 101 | def check_bitmap_state(node, bitmaps): 102 | """Check if the bitmap state is ready for backup 103 | 104 | active -> Ready for backup 105 | frozen -> backup in progress 106 | disabled-> migration might be going on 107 | """ 108 | status = False 109 | for bitmap in bitmaps: 110 | log.debug("Bitmap information: %s", json_pp(bitmap)) 111 | try: 112 | status = "active" in bitmap["status"] 113 | except KeyError: 114 | status = bitmap["recording"] 115 | 116 | if bitmap["name"] == f"qmpbackup-{node}" and status is True: 117 | return True 118 | 119 | return status 120 | 121 | 122 | def connect_qaagent(socket): 123 | """Setup Qemu Agent connection""" 124 | try: 125 | qga = QemuGuestAgentClient(socket) 126 | log.info("Guest Agent socket connected") 127 | except QemuGuestAgentClient.error as errmsg: 128 | log.warning('Unable to connect guest agent socket: "%s"', errmsg) 129 | return False 130 | 131 | log.info("Trying to ping guest agent") 132 | if not qga.ping(5): 133 | log.warning("Unable to reach Guest Agent: can't freeze file systems.") 134 | return False 135 | 136 | qga_info = qga.info() 137 | log.info("Guest Agent is reachable") 138 | if "guest-fsfreeze-freeze" not in qga_info: 139 | log.warning("Guest agent does not support required commands.") 140 | return False 141 | 142 | return qga 143 | 144 | 145 | def get_images(argv): 146 | """get images within backup folder""" 147 | os.chdir(argv.dir) 148 | image_files = filter(os.path.isfile, os.listdir(argv.dir)) 149 | images = [ 150 | os.path.join(argv.dir, f) 151 | for f in image_files 152 | if not (f.endswith(".config") or f == "uuid") 153 | ] 154 | images_flat = [os.path.basename(f) for f in images] 155 | if argv.until is not None and argv.until not in images_flat: 156 | raise RuntimeError( 157 | "Image file specified by --until option " 158 | f"[{argv.until}] does not exist in backup directory" 159 | ) 160 | 161 | # sort files by creation date 162 | images.sort(key=os.path.getmtime) 163 | images_flat.sort(key=os.path.getmtime) 164 | 165 | if len(images) == 0: 166 | raise RuntimeError("No image files found in specified directory") 167 | 168 | if ".partial" in " ".join(images_flat): 169 | raise RuntimeError( 170 | "Partial backup file found, backup chain might be broken. " 171 | "Consider removing file before attempting to rebase." 172 | ) 173 | if argv.filter == "": 174 | if "FULL-" not in images[0]: 175 | raise RuntimeError("Unable to find base FULL image in target folder.") 176 | 177 | if argv.filter != "": 178 | images = [x for x in images if argv.filter in x] 179 | images_flat = [x for x in images_flat if argv.filter in x] 180 | 181 | return images, images_flat 182 | 183 | 184 | def copyfile(src, target): 185 | """Copy file""" 186 | try: 187 | shutil.copyfile(src, target) 188 | except shutil.Error as errmsg: 189 | raise RuntimeError( 190 | f"Failed to copy file [{src}] to [{target}]: {errmsg}" 191 | ) from errmsg 192 | 193 | 194 | def save_uuid(target, use_uuid=""): 195 | """Create an unique uuid that is written to the backup target file and 196 | added to the generated bitmap name. So later incremental backups can 197 | check if the backup target directory is matching the backup chain""" 198 | uuidfile = os.path.join(target, "uuid") 199 | if use_uuid == "": 200 | backup_uuid = uuid.uuid4() 201 | else: 202 | backup_uuid = use_uuid 203 | try: 204 | with open(uuidfile, "w+", encoding="utf-8") as info_file: 205 | info_file.write(str(backup_uuid)) 206 | log.info("Backup UUID: [%s]", backup_uuid) 207 | except IOError as errmsg: 208 | raise RuntimeError(f"Unable to store uuid: [{errmsg}]") from errmsg 209 | except Exception as errmsg: 210 | raise RuntimeError(errmsg) from errmsg 211 | 212 | return str(backup_uuid) 213 | 214 | 215 | def get_uuid(target): 216 | """Read UUID to check if current existing bitmap chain matches the 217 | backup target folder during incremental backup""" 218 | uuidfile = os.path.join(target, "uuid") 219 | try: 220 | with open(uuidfile, "r", encoding="utf-8") as uuid_file: 221 | backup_uuid = uuid_file.read() 222 | log.info( 223 | "Current Backup UUID: [%s] for folder [%s]", 224 | backup_uuid, 225 | target, 226 | ) 227 | except IOError as errmsg: 228 | raise RuntimeError(f"Failed to read file [{uuidfile}]") from errmsg 229 | except Exception as errmsg: 230 | raise RuntimeError(errmsg) from errmsg 231 | 232 | return str(backup_uuid) 233 | -------------------------------------------------------------------------------- /libqmpbackup/qa.py: -------------------------------------------------------------------------------- 1 | """ 2 | QEMU Monitor Protocol Python class 3 | 4 | Copyright (C) 2022 Michael Ablassmeier 5 | Copyright (C) 2009, 2010 Red Hat Inc. 6 | 7 | Authors: 8 | Michael Ablassmeier 9 | Luiz Capitulino 10 | 11 | Based on work by: 12 | Luiz Capitulino 13 | 14 | This work is licensed under the terms of the GNU GPL, version 2. See 15 | the COPYING file in the top-level directory. 16 | """ 17 | 18 | import json 19 | import errno 20 | import socket 21 | 22 | 23 | class QMPError(Exception): 24 | """Error Exception""" 25 | 26 | 27 | class QMPConnectError(QMPError): 28 | """Error Exception""" 29 | 30 | 31 | class QMPCapabilitiesError(QMPError): 32 | """Error Exception""" 33 | 34 | 35 | class QMPTimeoutError(QMPError): 36 | """Error Exception""" 37 | 38 | 39 | class QEMUMonitorProtocol: 40 | """Qemu QMP protocol Monitor""" 41 | 42 | def __init__(self, address): 43 | """ 44 | Create a QEMUMonitorProtocol class. 45 | 46 | @param address: QEMU address, can be either a unix socket path (string) 47 | or a tuple in the form ( address, port ) for a TCP 48 | connection 49 | @param server: server mode listens on the socket (bool) 50 | @raise socket.error on socket connection errors 51 | @note No connection is established, this is done by the connect() or 52 | accept() methods 53 | """ 54 | self.__address = address 55 | self.__sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 56 | self.__sockfile = None 57 | 58 | def __json_read(self): 59 | """Read reply""" 60 | while True: 61 | data = self.__sockfile.readline() 62 | if not data: 63 | return None 64 | resp = json.loads(data) 65 | return resp 66 | 67 | error = socket.error 68 | 69 | def connect(self): 70 | """ 71 | Connect to the QMP Monitor and perform capabilities negotiation. 72 | 73 | @return QMP greeting dict 74 | @raise socket.error on socket connection errors 75 | @raise QMPConnectError if the greeting is not received 76 | @raise QMPCapabilitiesError if fails to negotiate capabilities 77 | """ 78 | self.__sock.connect(self.__address) 79 | self.__sockfile = self.__sock.makefile() 80 | 81 | def cmd_obj(self, qmp_cmd): 82 | """ 83 | Send a QMP command to the QMP Monitor. 84 | 85 | @param qmp_cmd: QMP command to be sent as a Python dict 86 | @return QMP response as a Python dict or None if the connection has 87 | been closed 88 | """ 89 | try: 90 | self.__sock.sendall(json.dumps(qmp_cmd).encode()) 91 | except OSError as err: 92 | if err.errno == errno.EPIPE: 93 | return err 94 | raise socket.error(err) 95 | resp = self.__json_read() 96 | return resp 97 | 98 | def cmd(self, name, args=None): 99 | """ 100 | Build a QMP command and send it to the QMP Monitor. 101 | 102 | @param name: command name (string) 103 | @param args: command arguments (dict) 104 | @param id: command id (dict, list, string or int) 105 | """ 106 | qmp_cmd = {"execute": name} 107 | if args: 108 | qmp_cmd["arguments"] = args 109 | return self.cmd_obj(qmp_cmd) 110 | 111 | def command(self, cmd, **kwds): 112 | """Execute command""" 113 | ret = self.cmd(cmd, kwds) 114 | if "error" in ret: 115 | raise RuntimeError(ret["error"]["desc"]) 116 | return ret["return"] 117 | 118 | def close(self): 119 | """Close handle""" 120 | self.__sock.close() 121 | self.__sockfile.close() 122 | 123 | timeout = socket.timeout 124 | 125 | def settimeout(self, timeout): 126 | """Set socket timeout""" 127 | self.__sock.settimeout(timeout) 128 | -------------------------------------------------------------------------------- /libqmpbackup/qaclient.py: -------------------------------------------------------------------------------- 1 | """ 2 | QEMU Guest Agent Client 3 | 4 | Copyright (C) 2022 Michael Ablassmeier 5 | Copyright (C) 2012 Ryota Ozaki 6 | 7 | This work is licensed under the terms of the GNU GPL, version 2. See 8 | the COPYING file in the top-level directory. 9 | 10 | """ 11 | 12 | import random 13 | import libqmpbackup.qa as qmp 14 | 15 | 16 | class QemuGuestAgent(qmp.QEMUMonitorProtocol): 17 | """Wrap functions""" 18 | 19 | def __getattr__(self, name): 20 | def wrapper(**kwds): 21 | return self.command("guest-" + name.replace("_", "-"), **kwds) 22 | 23 | return wrapper 24 | 25 | 26 | class QemuGuestAgentClient: 27 | """Guest Agent functions""" 28 | 29 | error = QemuGuestAgent.error 30 | 31 | def __init__(self, address): 32 | self.qga = QemuGuestAgent(address) 33 | self.qga.connect() 34 | 35 | def sync(self, timeout=3): 36 | """Avoid being blocked forever""" 37 | if not self.ping(timeout): 38 | raise EnvironmentError("Agent seems not alive") 39 | uid = random.randint(0, (1 << 32) - 1) 40 | while True: 41 | ret = self.qga.sync(id=uid) 42 | if isinstance(ret, int) and int(ret) == uid: 43 | break 44 | 45 | def info(self): 46 | """Return supported commands""" 47 | info = self.qga.info() 48 | return [c["name"] for c in info["supported_commands"] if c["enabled"]] 49 | 50 | def ping(self, timeout): 51 | """Ping the guest agent, see if its alive""" 52 | self.qga.settimeout(timeout) 53 | try: 54 | self.qga.ping() 55 | except self.qga.timeout: 56 | return False 57 | return True 58 | 59 | def fsfreeze(self, cmd): 60 | """Freeze / thaw filesystem""" 61 | if cmd not in ["status", "freeze", "thaw"]: 62 | raise RuntimeError("Invalid command: " + cmd) 63 | 64 | return getattr(self.qga, "fsfreeze" + "_" + cmd)() 65 | -------------------------------------------------------------------------------- /libqmpbackup/qmpcommon.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Copyright (C) 2022 Michael Ablassmeier 4 | 5 | Authors: 6 | Michael Ablassmeier 7 | 8 | This work is licensed under the terms of the GNU GPL, version 3. See 9 | the LICENSE file in the top-level directory. 10 | """ 11 | import os 12 | import logging 13 | from time import sleep 14 | import asyncio 15 | from qemu.qmp import EventListener, qmp_client 16 | from libqmpbackup import fs 17 | from libqmpbackup.lib import json_pp 18 | 19 | 20 | class QmpCommon: 21 | """Common functions""" 22 | 23 | def __init__(self, qmp): 24 | self.qmp = qmp 25 | self.log = logging.getLogger(__name__) 26 | 27 | async def show_vm_state(self): 28 | """Show and check if virtual machine is in required 29 | state""" 30 | status = await self.qmp.execute("query-status") 31 | if status["running"] is False and not status["status"] in ( 32 | "prelaunch", 33 | "paused", 34 | ): 35 | raise RuntimeError(f"VM not ready for backup, state: [{status}]") 36 | self.log.info("VM is in state: [%s]", status["status"]) 37 | 38 | async def show_name(self): 39 | """Show qemu version""" 40 | name = await self.qmp.execute("query-name") 41 | if name: 42 | self.log.info("VM Name: [%s]", name["name"]) 43 | 44 | def show_version(self): 45 | """Show name of VM; if setn""" 46 | hv_version = self.qmp._greeting._raw["QMP"] # pylint: disable=W0212 47 | qemu = hv_version["version"]["qemu"] 48 | self.log.info( 49 | "Qemu version: [%s.%s.%s] [%s]", 50 | qemu["major"], 51 | qemu["micro"], 52 | qemu["minor"], 53 | hv_version["version"]["package"], 54 | ) 55 | 56 | @staticmethod 57 | def transaction_action(action, **kwargs): 58 | """Return transaction action object""" 59 | return { 60 | "type": action, 61 | "data": dict((k.replace("_", "-"), v) for k, v in kwargs.items()), 62 | } 63 | 64 | def transaction_bitmap_clear(self, node, name, **kwargs): 65 | """Return transaction action object for bitmap clear""" 66 | return self.transaction_action( 67 | "block-dirty-bitmap-clear", node=node, name=name, **kwargs 68 | ) 69 | 70 | def transaction_bitmap_add(self, node, name, **kwargs): 71 | """Return transaction action object for bitmap add""" 72 | return self.transaction_action( 73 | "block-dirty-bitmap-add", node=node, name=name, **kwargs 74 | ) 75 | 76 | async def prepare_target_devices(self, argv, devices, target_files): 77 | """Create the required target devices for blockev-backup 78 | operation""" 79 | self.log.info("Attach backup target devices to virtual machine") 80 | for device in devices: 81 | target = target_files[device.node] 82 | targetdev = f"qmpbackup-{device.node_safe}" 83 | 84 | args = { 85 | "driver": device.format, 86 | "node-name": targetdev, 87 | "file": { 88 | "driver": "file", 89 | "filename": target, 90 | "aio": argv.blockdev_aio, 91 | }, 92 | } 93 | 94 | if argv.blockdev_disable_cache is True: 95 | nocache = {"cache": {"direct": False, "no-flush": False}} 96 | args = args | nocache 97 | args["file"] = args["file"] | nocache 98 | 99 | await self.qmp.execute( 100 | "blockdev-add", 101 | arguments=args, 102 | ) 103 | 104 | async def prepare_fleece_devices(self, devices, target_files): 105 | """Create the required fleece devices for blockev-backup 106 | operation""" 107 | self.log.info("Attach fleece devices to virtual machine") 108 | for device in devices: 109 | target = target_files[device.node] 110 | targetdev = f"qmpbackup-{device.node_safe}-fleece" 111 | 112 | args = { 113 | "driver": device.format, 114 | "node-name": targetdev, 115 | "file": { 116 | "driver": "file", 117 | "filename": target, 118 | }, 119 | } 120 | 121 | await self.qmp.execute( 122 | "blockdev-add", 123 | arguments=args, 124 | ) 125 | 126 | async def add_snapshot_access_devices(self, devices): 127 | """Prepare snapshot-access devices required for backup using 128 | image fleecing technique""" 129 | self.log.info("Add snapshot-access devices.") 130 | for device in devices: 131 | snap = { 132 | "driver": "snapshot-access", 133 | "file": f"qmpbackup-{device.node_safe}-cbw", 134 | "node-name": f"qmpbackup-{device.node_safe}-snap", 135 | } 136 | await self.qmp.execute( 137 | "blockdev-add", 138 | arguments=snap, 139 | ) 140 | 141 | async def remove_snapshot_access_devices(self, devices): 142 | """Cleanup named devices after executing blockdev-backup 143 | operation""" 144 | self.log.info("Removing cbw devices from virtual machine") 145 | for device in devices: 146 | targetdev = f"qmpbackup-{device.node_safe}-snap" 147 | 148 | await self.qmp.execute( 149 | "blockdev-del", 150 | arguments={ 151 | "node-name": targetdev, 152 | }, 153 | ) 154 | 155 | async def remove_target_devices(self, devices): 156 | """Cleanup named devices after executing blockdev-backup 157 | operation""" 158 | self.log.info("Removing backup target devices from virtual machine") 159 | for device in devices: 160 | targetdev = f"qmpbackup-{device.node_safe}" 161 | 162 | await self.qmp.execute( 163 | "blockdev-del", 164 | arguments={ 165 | "node-name": targetdev, 166 | }, 167 | ) 168 | 169 | async def remove_fleece_devices(self, devices): 170 | """Cleanup named devices after executing blockdev-backup 171 | operation""" 172 | self.log.info("Removing fleece devices from virtual machine") 173 | for device in devices: 174 | targetdev = f"qmpbackup-{device.node_safe}-fleece" 175 | 176 | await self.qmp.execute( 177 | "blockdev-del", 178 | arguments={ 179 | "node-name": targetdev, 180 | }, 181 | ) 182 | 183 | async def remove_cbw_devices(self, devices): 184 | """Cleanup named devices after executing blockdev-backup 185 | operation""" 186 | self.log.info("Removing cbw devices from virtual machine") 187 | for device in devices: 188 | targetdev = f"qmpbackup-{device.node_safe}-cbw" 189 | 190 | await self.qmp.execute( 191 | "blockdev-del", 192 | arguments={ 193 | "node-name": targetdev, 194 | }, 195 | ) 196 | 197 | async def blockdev_replace(self, devices, action): 198 | """Issue qom command to switch disk device to copy-before-write filter""" 199 | self.log.info("Activate copy-before-write filter") 200 | if action == "disable": 201 | self.log.info("Disable copy-before-write filter") 202 | else: 203 | self.log.info("Disable copy-before-write filter") 204 | for device in devices: 205 | target = f"qmpbackup-{device.node_safe}-cbw" 206 | if action == "disable": 207 | target = device.node 208 | await self.qmp.execute( 209 | "qom-set", 210 | arguments={ 211 | "path": device.qdev, 212 | "property": "drive", 213 | "value": target, 214 | }, 215 | ) 216 | 217 | async def add_cbw_device(self, argv, devices, uuid): 218 | """Add copy-before-write device operation""" 219 | self.log.info("Adding cbw devices to virtual machine") 220 | bitmap_prefix = "qmpbackup" 221 | if argv.level == "copy": 222 | bitmap_prefix = f"qmpbackup-{argv.level}" 223 | for device in devices: 224 | cbwopt = { 225 | "driver": "copy-before-write", 226 | "node-name": f"qmpbackup-{device.node_safe}-cbw", 227 | "file": device.node, 228 | "target": f"qmpbackup-{device.node_safe}-fleece", 229 | "on-cbw-error": "break-snapshot", 230 | "cbw-timeout": 45, 231 | } 232 | if device.has_bitmap and argv.level in ("inc", "diff"): 233 | bitmap = f"{bitmap_prefix}-{device.node_safe}-{uuid}" 234 | cbwopt["bitmap"] = { 235 | "node": device.node, 236 | "name": bitmap, 237 | } 238 | 239 | await self.qmp.execute("blockdev-add", arguments=cbwopt) 240 | 241 | def prepare_transaction(self, argv, devices, uuid): 242 | """Prepare transaction steps""" 243 | sync = "full" 244 | if argv.level == "inc": 245 | sync = "incremental" 246 | 247 | bitmap_prefix = "qmpbackup" 248 | persistent = True 249 | if argv.level == "copy": 250 | self.log.info("Copy backup: no persistent bitmap will be created.") 251 | bitmap_prefix = f"qmpbackup-{argv.level}" 252 | persistent = False 253 | 254 | actions = [] 255 | for device in devices: 256 | targetdev = f"qmpbackup-{device.node_safe}" 257 | bitmap = f"{bitmap_prefix}-{device.node_safe}-{uuid}" 258 | job_id = f"qmpbackup.{device.node_safe}.{os.path.basename(device.filename)}" 259 | 260 | if ( 261 | not device.has_bitmap 262 | and device.format != "raw" 263 | and argv.level in ("full", "copy") 264 | or device.has_bitmap 265 | and argv.level in ("copy") 266 | ): 267 | self.log.info( 268 | "Creating new bitmap: [%s] for device [%s]", bitmap, device.node 269 | ) 270 | actions.append( 271 | self.transaction_bitmap_add( 272 | device.node, bitmap, persistent=persistent 273 | ) 274 | ) 275 | 276 | if device.has_bitmap and argv.level in ("full") and device.format != "raw": 277 | self.log.info( 278 | "Clearing existing bitmap [%s] for device: [%s:%s]", 279 | bitmap, 280 | device.node, 281 | os.path.basename(device.filename), 282 | ) 283 | actions.append(self.transaction_bitmap_clear(device.node, bitmap)) 284 | 285 | compress = argv.compress 286 | if device.format == "raw" and compress: 287 | compress = False 288 | self.log.info("Disabling compression for raw device: [%s]", device.node) 289 | 290 | if argv.level in ("full", "copy") or ( 291 | argv.level == "inc" and device.format == "raw" 292 | ): 293 | actions.append( 294 | self.transaction_action( 295 | "blockdev-backup", 296 | device=f"qmpbackup-{device.node_safe}-snap", 297 | target=targetdev, 298 | sync=sync, 299 | job_id=job_id, 300 | speed=argv.speed_limit, 301 | compress=compress, 302 | ) 303 | ) 304 | else: 305 | actions.append( 306 | self.transaction_bitmap_add( 307 | f"qmpbackup-{device.node_safe}-snap", bitmap 308 | ) 309 | ) 310 | 311 | bm_source = { 312 | "name": bitmap, 313 | "node": device.node, 314 | } 315 | merge_bitmap = { 316 | "node": f"qmpbackup-{device.node_safe}-snap", 317 | "target": bitmap, 318 | "bitmaps": [bm_source], 319 | } 320 | actions.append( 321 | self.transaction_action( 322 | "block-dirty-bitmap-merge", 323 | **merge_bitmap, 324 | ) 325 | ) 326 | actions.append( 327 | self.transaction_action( 328 | "blockdev-backup", 329 | bitmap=bitmap, 330 | device=f"qmpbackup-{device.node_safe}-snap", 331 | target=targetdev, 332 | sync=sync, 333 | job_id=job_id, 334 | speed=argv.speed_limit, 335 | compress=argv.compress, 336 | ) 337 | ) 338 | actions.append(self.transaction_bitmap_clear(device.node, bitmap)) 339 | 340 | self.log.debug("Created transaction: %s", json_pp(actions)) 341 | 342 | return actions 343 | 344 | async def backup(self, argv, devices, qga, uuid): 345 | """Start backup transaction, while backup is active, 346 | watch for block status""" 347 | 348 | def job_filter(event) -> bool: 349 | event_data = event.get("data", {}) 350 | event_job_id = event_data.get("id") 351 | return event_job_id.startswith("qmpbackup") 352 | 353 | listener = EventListener( 354 | ( 355 | "BLOCK_JOB_COMPLETED", 356 | job_filter, 357 | "BLOCK_JOB_CANCELLED", 358 | job_filter, 359 | "BLOCK_JOB_ERROR", 360 | job_filter, 361 | "BLOCK_JOB_READY", 362 | job_filter, 363 | "BLOCK_JOB_PENDING", 364 | job_filter, 365 | "JOB_STATUS_CHANGE", 366 | job_filter, 367 | ) 368 | ) 369 | 370 | finished = 0 371 | actions = self.prepare_transaction(argv, devices, uuid) 372 | with self.qmp.listen(listener): 373 | await self.qmp.execute("transaction", arguments={"actions": actions}) 374 | _ = asyncio.create_task(self.progress(), name="progress") 375 | if qga is not False: 376 | fs.thaw(qga) 377 | async for event in listener: 378 | if event["event"] in ("BLOCK_JOB_CANCELLED", "BLOCK_JOB_ERROR"): 379 | raise RuntimeError( 380 | "Block job failed for device " 381 | f"[{event['data']['device']}]: [{event['event']}]", 382 | ) 383 | if event["event"] == "BLOCK_JOB_COMPLETED": 384 | finished += 1 385 | self.log.info("Block job [%s] finished", event["data"]["device"]) 386 | if len(devices) == finished: 387 | self.log.info("All backups finished") 388 | break 389 | 390 | async def do_query_block(self): 391 | """Return list of attached block devices""" 392 | return await self.qmp.execute("query-block") 393 | 394 | async def remove_bitmaps(self, blockdev, prefix="qmpbackup", uuid=""): 395 | """Remove existing bitmaps for block devices""" 396 | for dev in blockdev: 397 | if not dev.has_bitmap: 398 | self.log.info("No bitmap set for device %s", dev.node) 399 | continue 400 | 401 | for bitmap in dev.bitmaps: 402 | bitmap_name = bitmap["name"] 403 | self.log.debug("Bitmap name: %s", bitmap_name) 404 | if prefix not in bitmap_name: 405 | self.log.debug( 406 | "Ignoring bitmap: [%s] not matching prefix [%s]", 407 | prefix, 408 | bitmap_name, 409 | ) 410 | continue 411 | if uuid != "" and not bitmap_name.endswith(uuid): 412 | self.log.debug( 413 | "Ignoring bitmap: [%s] not matching uuid [%s]", 414 | bitmap_name, 415 | uuid, 416 | ) 417 | continue 418 | self.log.info("Removing bitmap: %s", bitmap_name) 419 | await self.qmp.execute( 420 | "block-dirty-bitmap-remove", 421 | arguments={"node": dev.node, "name": bitmap_name}, 422 | ) 423 | 424 | async def progress(self): 425 | """Report progress for active block job""" 426 | while True: 427 | sleep(1) 428 | try: 429 | jobs = await self.qmp.execute("query-block-jobs") 430 | except qmp_client.ExecInterruptedError: 431 | return 432 | if len(jobs) == 0: 433 | return 434 | for job in jobs: 435 | if not job["device"].startswith("qmpbackup"): 436 | continue 437 | if job["status"] != "running": 438 | continue 439 | prog = [ 440 | round(job["offset"] / job["len"] * 100) if job["offset"] != 0 else 0 441 | ] 442 | self.log.info( 443 | "[%s] Wrote Offset: %s%% (%s of %s)", 444 | job["device"], 445 | prog[0], 446 | job["offset"], 447 | job["len"], 448 | ) 449 | -------------------------------------------------------------------------------- /libqmpbackup/version.py: -------------------------------------------------------------------------------- 1 | """ 2 | qmpbackup: Full an incremental backup using Qemus 3 | dirty bitmap feature 4 | 5 | Copyright (C) 2022 Michael Ablassmeier 6 | 7 | Authors: 8 | Michael Ablassmeier 9 | 10 | This work is licensed under the terms of the GNU GPL, version 3. See 11 | the LICENSE file in the top-level directory. 12 | """ 13 | 14 | VERSION = "0.47" 15 | -------------------------------------------------------------------------------- /libqmpbackup/vm.py: -------------------------------------------------------------------------------- 1 | """ 2 | qmpbackup: Full an incremental backup using Qemus 3 | dirty bitmap feature 4 | 5 | Copyright (C) 2022 Michael Ablassmeier 6 | 7 | Authors: 8 | Michael Ablassmeier 9 | 10 | This work is licensed under the terms of the GNU GPL, version 3. See 11 | the LICENSE file in the top-level directory. 12 | """ 13 | 14 | import os 15 | import json 16 | import logging 17 | from dataclasses import dataclass 18 | 19 | log = logging.getLogger(__name__) 20 | 21 | 22 | @dataclass 23 | class BlockDev: 24 | """Block device information""" 25 | 26 | device: str 27 | format: str 28 | filename: str 29 | backing_image: str 30 | has_bitmap: bool 31 | bitmaps: list 32 | virtual_size: int 33 | driver: str 34 | node: str 35 | node_safe: str 36 | path: str 37 | qdev: str 38 | 39 | 40 | def get_block_devices(blockinfo, argv, excluded_disks, included_disks, uuid): 41 | """Get a list of block devices that we can create a bitmap for, 42 | currently we only get inserted qcow based images 43 | """ 44 | blockdevs = [] 45 | for device in blockinfo: 46 | bitmaps = None 47 | has_bitmap = False 48 | backing_image = False 49 | driver = None 50 | if "inserted" not in device: 51 | log.debug("Ignoring non-inserted device: %s", device) 52 | continue 53 | 54 | inserted = device["inserted"] 55 | if ( 56 | inserted["drv"] == "raw" 57 | and not argv.include_raw 58 | and not device["device"].startswith("pflash") 59 | ): 60 | log.warning( 61 | "Excluding device with raw format from backup: [%s:%s]", 62 | device["device"], 63 | inserted["image"]["filename"], 64 | ) 65 | continue 66 | 67 | bitmaps = [] 68 | if "dirty-bitmaps" in inserted: 69 | bitmaps = inserted["dirty-bitmaps"] 70 | 71 | if "dirty-bitmaps" in device: 72 | bitmaps = device["dirty-bitmaps"] 73 | 74 | if len(bitmaps) > 0 and uuid is not None: 75 | for bmap in bitmaps: 76 | try: 77 | if bmap["name"].endswith(uuid): 78 | has_bitmap = True 79 | break 80 | except KeyError: 81 | log.warning( 82 | "Qemu returned bitmap without name, ignoring entry: [%s]", bmap 83 | ) 84 | continue 85 | else: 86 | if len(bitmaps) > 0: 87 | has_bitmap = True 88 | 89 | try: 90 | backing_image = inserted["image"]["backing-image"] 91 | backing_image = True 92 | filename = inserted["image"]["backing-image"]["filename"] 93 | diskformat = inserted["image"]["backing-image"]["format"] 94 | except KeyError: 95 | filename = inserted["image"]["filename"] 96 | diskformat = inserted["image"]["format"] 97 | 98 | if filename.startswith("json:"): 99 | log.debug("Filename setting is json encoded..") 100 | try: 101 | encoded_name = json.loads(filename[5:]) 102 | try: 103 | log.debug("Check if device is an RBD backed device.") 104 | driver = encoded_name["file"]["driver"] 105 | if driver == "rbd": 106 | log.info("Ceph device found, using image name") 107 | filename = encoded_name["file"]["image"] 108 | log.debug("RBD image name: [%s]", filename) 109 | else: 110 | raise KeyError 111 | except KeyError: 112 | log.debug("Non RBD Device detected, use filename setting.") 113 | try: 114 | filename = encoded_name["file"]["next"]["filename"] 115 | log.debug("Filename detected: [%s]", filename) 116 | except KeyError: 117 | log.warning( 118 | "Json encoded setting found but no filename property set for device: [%s]", 119 | device["device"], 120 | ) 121 | continue 122 | except json.decoder.JSONDecodeError as errmsg: 123 | log.warning( 124 | "Unable to decode filename json for device [%s]: %s", 125 | errmsg, 126 | device["device"], 127 | ) 128 | continue 129 | 130 | if device["device"] == "": 131 | try: 132 | log.info( 133 | "Device for file [%s] has empty device setting, attempt fallback to node name.", 134 | filename, 135 | ) 136 | device["device"] = device["inserted"]["node-name"] 137 | log.info("Using node name: [%s]", device["device"]) 138 | except KeyError: 139 | log.error( 140 | "Unable to get device node name for disk: [%s], skipping.", filename 141 | ) 142 | continue 143 | 144 | if included_disks and not ( 145 | device["device"] in included_disks 146 | or inserted["node-name"] in included_disks 147 | ): 148 | log.info( 149 | "Device not in included disk list, ignoring: [%s:%s]", 150 | device["device"], 151 | filename, 152 | ) 153 | continue 154 | 155 | if excluded_disks and ( 156 | device["device"] in excluded_disks 157 | or inserted["node-name"] in excluded_disks 158 | ): 159 | logging.info( 160 | "Excluding device from backup: [%s:%s]", 161 | device["device"], 162 | filename, 163 | ) 164 | continue 165 | 166 | try: 167 | qdev = device["qdev"] 168 | except KeyError: 169 | log.warning( 170 | "Device [%s] has no qdev required for CBW set, skipping.", 171 | device["device"], 172 | ) 173 | continue 174 | 175 | log.debug("Adding device to device list: %s", device) 176 | blockdevs.append( 177 | BlockDev( 178 | device["device"], 179 | diskformat, 180 | filename, 181 | backing_image, 182 | has_bitmap, 183 | bitmaps, 184 | inserted["image"]["virtual-size"], 185 | driver, 186 | inserted["node-name"], 187 | inserted["node-name"].replace("#", ""), 188 | os.path.dirname(os.path.abspath(filename)), 189 | qdev, 190 | ) 191 | ) 192 | 193 | if len(blockdevs) == 0: 194 | return None 195 | 196 | return blockdevs 197 | -------------------------------------------------------------------------------- /qmpbackup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | qmpbackup: Full an incremental backup using Qemus 4 | dirty bitmap feature 5 | 6 | Copyright (C) 2022 Michael Ablassmeier 7 | 8 | Authors: 9 | Michael Ablassmeier 10 | 11 | This work is licensed under the terms of the GNU GPL, version 3. See 12 | the LICENSE file in the top-level directory. 13 | """ 14 | import os 15 | import sys 16 | import asyncio 17 | import signal 18 | import argparse 19 | from time import sleep 20 | from datetime import datetime 21 | from dataclasses import asdict 22 | from qemu.qmp import protocol, QMPClient, qmp_client 23 | from qemu.qmp.error import QMPError 24 | 25 | from libqmpbackup.qmpcommon import QmpCommon 26 | from libqmpbackup import lib 27 | from libqmpbackup import fs 28 | from libqmpbackup import vm 29 | from libqmpbackup import image 30 | from libqmpbackup import version 31 | 32 | SIGNAL_CATCHED = False 33 | 34 | 35 | async def stop_jobs(blockdev, log, qmp, signal): 36 | """Catch signal: for some reason, cancelling the 37 | running block jobs with block-job-cancel issues 38 | a regular BLOCK_JOB_COMPLETED in the event loop, 39 | for some reason. Thus exit with different exit code 40 | by using global variable :/ 41 | """ 42 | global SIGNAL_CATCHED 43 | log.error("Caught signal: %s", signal) 44 | log.error("Stopping backup jobs") 45 | SIGNAL_CATCHED = True 46 | jobs = await qmp.execute("query-block-jobs") 47 | if len(jobs) == 0: 48 | log.info("No running jobs found") 49 | for job in jobs: 50 | if job["type"] != "backup" or not job["device"].startswith("qmpbackup"): 51 | continue 52 | try: 53 | await qmp.execute( 54 | "block-job-cancel", 55 | arguments={ 56 | "device": job["device"], 57 | "force": True, 58 | }, 59 | ) 60 | except qmp_client.ExecuteError as err: 61 | log.info(err) 62 | 63 | 64 | async def main(): 65 | """qmpbackup""" 66 | parser = argparse.ArgumentParser( 67 | description="Backup QEMU virtual machines", 68 | epilog=( 69 | "Examples:\n" 70 | " # full backup with all attached disks:\n" 71 | "\t%(prog)s --socket /tmp/sock backup --level full --target /backup/\n" 72 | " # incremental backup with all attached disks:\n" 73 | "\t%(prog)s --socket /tmp/sock backup --level inc --target /backup/\n" 74 | " # show attached block devices:\n" 75 | "\t%(prog)s --socket /tmp/socket info --show blockdev\n" 76 | " # full backup but exclude disk:\n" 77 | "\t%(prog)s --socket /tmp/sock backup --level full --exclude ide0-hd0" 78 | " --target /backup/\n" 79 | ), 80 | formatter_class=argparse.RawTextHelpFormatter, 81 | ) 82 | parser.add_argument( 83 | "--socket", dest="socket", help="qmp socket to connect", required=1 84 | ) 85 | parser.add_argument( 86 | "--agent-socket", 87 | dest="agentsocket", 88 | help="socket to use for communication with qemu agent", 89 | required=False, 90 | ) 91 | parser.add_argument( 92 | "--debug", 93 | dest="debug", 94 | help="more verbose output", 95 | action="store_true", 96 | required=False, 97 | ) 98 | parser.add_argument( 99 | "-L", 100 | "--logfile", 101 | default="", 102 | help="log output to specified logfile", 103 | required=False, 104 | ) 105 | parser.add_argument( 106 | "--syslog", 107 | action="store_true", 108 | help="log output to syslog", 109 | required=False, 110 | default=False, 111 | ) 112 | subparsers = parser.add_subparsers(help="sub-command help") 113 | parser_backup = subparsers.add_parser("backup", help="backup") 114 | parser_backup.set_defaults(which="backup") 115 | parser_backup.add_argument( 116 | "-l", 117 | "--level", 118 | choices=["copy", "full", "inc", "auto"], 119 | type=str, 120 | help="backup level", 121 | required=True, 122 | ) 123 | parser_backup.add_argument( 124 | "-e", 125 | "--exclude", 126 | type=str, 127 | default=None, 128 | help="exclude block device from backup", 129 | required=False, 130 | ) 131 | parser_backup.add_argument( 132 | "-i", 133 | "--include", 134 | type=str, 135 | default=None, 136 | help="backup only specified block device", 137 | required=False, 138 | ) 139 | parser_backup.add_argument( 140 | "--monthly", 141 | action="store_true", 142 | help=( 143 | "Create monthly backup directories (in format YYYY-MM). " 144 | "If combined with backup level 'auto' this will " 145 | "create monthly backup chains." 146 | ), 147 | required=False, 148 | ) 149 | parser_backup.add_argument( 150 | "--no-subdir", 151 | action="store_true", 152 | help="Use flat directory structure for storing the backup files", 153 | required=False, 154 | ) 155 | parser_backup.add_argument( 156 | "--no-timestamp", 157 | action="store_true", 158 | help="Dont use timestamp for backup files", 159 | required=False, 160 | ) 161 | parser_backup.add_argument( 162 | "--no-symlink", 163 | action="store_true", 164 | help="Dont create symlinks to full backups", 165 | required=False, 166 | default=False, 167 | ) 168 | parser_backup.add_argument( 169 | "--quiesce", 170 | action="store_true", 171 | help="Use Qemu Agent to quiesce filesystem", 172 | required=False, 173 | ) 174 | parser_backup.add_argument( 175 | "-t", "--target", type=str, help="backup target directory", required=True 176 | ) 177 | parser_backup.add_argument( 178 | "--speed-limit", 179 | type=int, 180 | default=0, 181 | help="speed limit in bytes / second", 182 | required=False, 183 | ) 184 | parser_backup.add_argument( 185 | "--compress", 186 | action="store_true", 187 | default=False, 188 | help="Attempt to compress data if target image format supports it", 189 | required=False, 190 | ) 191 | parser_backup.add_argument( 192 | "--include-raw", 193 | action="store_true", 194 | default=False, 195 | help="Include raw images in backup.", 196 | required=False, 197 | ) 198 | parser_backup.add_argument( 199 | "--uuid", 200 | help="use specified uuid for bitmap", 201 | type=str, 202 | required=False, 203 | default="", 204 | ) 205 | parser_backup.add_argument( 206 | "--remove-delay", 207 | help="Delay removal of attached disks (seconds)", 208 | default=0, 209 | type=int, 210 | ) 211 | parser_backup.add_argument( 212 | "--blockdev-disable-cache", 213 | help="Disable caching during backup operation", 214 | required=False, 215 | action="store_true", 216 | ) 217 | parser_backup.add_argument( 218 | "--blockdev-aio", 219 | help="Aio option to use during backup, default: %(default)s", 220 | choices=["threads", "io_uring"], 221 | required=False, 222 | default="threads", 223 | ) 224 | parser_cleanup = subparsers.add_parser("cleanup", help="cleanup functions") 225 | parser_cleanup.set_defaults(which="cleanup") 226 | parser_cleanup.add_argument( 227 | "--remove-bitmap", 228 | action="store_true", 229 | help="remove all existent bitmaps for all devices", 230 | required=True, 231 | ) 232 | parser_cleanup.add_argument( 233 | "--uuid", 234 | help="remove bitmaps matching uuid", 235 | type=str, 236 | required=False, 237 | default="", 238 | ) 239 | parser_info = subparsers.add_parser("info", help="print info about VM") 240 | parser_info.set_defaults(which="info") 241 | parser_info.add_argument( 242 | "--show", 243 | choices=["blockdev", "bitmaps"], 244 | type=str, 245 | help="show block device information", 246 | required=True, 247 | ) 248 | argv = parser.parse_args() 249 | try: 250 | action = argv.which 251 | except AttributeError: 252 | parser.print_help() 253 | sys.exit(1) 254 | 255 | log = lib.setup_log(argv) 256 | log.info("Version: %s Arguments: %s", version.VERSION, " ".join(sys.argv)) 257 | 258 | if action == "backup" and argv.exclude and argv.include: 259 | log.error("Specify either included or excluded devices") 260 | sys.exit(1) 261 | 262 | new_monthly = False 263 | qmp = QMPClient() 264 | log.info("Connecting QMP socket: [%s]", argv.socket) 265 | try: 266 | await qmp.connect(argv.socket) 267 | except protocol.ConnectError as errmsg: 268 | log.fatal("Can't connect QMP socket [%s]: %s", argv.socket, errmsg) 269 | sys.exit(1) 270 | 271 | qemu_client = QmpCommon(qmp) 272 | 273 | try: 274 | await qemu_client.show_vm_state() 275 | except RuntimeError as errmsg: 276 | log.fatal(errmsg) 277 | sys.exit(1) 278 | 279 | qemu_client.show_version() 280 | await qemu_client.show_name() 281 | 282 | excluded_disks = None 283 | included_disks = None 284 | uuid = None 285 | if action == "backup": 286 | if argv.monthly: 287 | monthdir = datetime.today().strftime("%Y-%m") 288 | backupdir = os.path.join(argv.target, monthdir) 289 | if not os.path.exists(backupdir): 290 | log.info("New monthly directory will be created: %s", backupdir) 291 | new_monthly = True 292 | argv.target = backupdir 293 | 294 | try: 295 | os.makedirs(argv.target, exist_ok=True) 296 | except OSError as errmsg: 297 | log.error("Unable to create target dir: %s", errmsg) 298 | sys.exit(1) 299 | 300 | log.info("Backup target directory: %s", argv.target) 301 | if argv.level == "auto": 302 | if new_monthly is True or not os.path.exists( 303 | os.path.join(argv.target, "uuid") 304 | ): 305 | argv.level = "full" 306 | else: 307 | argv.level = "inc" 308 | log.info("Auto backup mode set to: %s", argv.level) 309 | 310 | if argv.exclude is not None: 311 | excluded_disks = argv.exclude.split(",") 312 | log.debug("Excluded disks: %s", excluded_disks) 313 | if argv.include is not None: 314 | included_disks = argv.include.split(",") 315 | log.debug("Saving only specified disks: %s", included_disks) 316 | if argv.compress: 317 | log.info("Enabling compress option for backup operation.") 318 | if argv.include_raw: 319 | log.info("Including raw devices in backup operation.") 320 | if argv.level == "full": 321 | if os.path.exists(os.path.join(argv.target, "uuid")): 322 | try: 323 | uuid = lib.get_uuid(argv.target) 324 | except RuntimeError as errmsg: 325 | log.error("Unable to get backup uuid: [%s]", errmsg) 326 | sys.exit(1) 327 | else: 328 | try: 329 | uuid = lib.save_uuid(argv.target, argv.uuid) 330 | except RuntimeError as errmsg: 331 | log.error("Unable to store backup uuid: [%s]", errmsg) 332 | sys.exit(1) 333 | if argv.level == "inc": 334 | try: 335 | uuid = lib.get_uuid(argv.target) 336 | except RuntimeError as errmsg: 337 | log.error("Unable to get UUID for incremental backup: [%s]", errmsg) 338 | sys.exit(1) 339 | 340 | if action == "info": 341 | argv.include_raw = True 342 | if action == "cleanup": 343 | argv.include_raw = False 344 | 345 | blockdev = vm.get_block_devices( 346 | await qemu_client.do_query_block(), argv, excluded_disks, included_disks, uuid 347 | ) 348 | 349 | loop = asyncio.get_event_loop() 350 | for signame in ("SIGINT", "SIGTERM"): 351 | loop.add_signal_handler( 352 | getattr(signal, signame), 353 | lambda signame=signame: asyncio.create_task( 354 | stop_jobs(blockdev, log, qmp, signame) 355 | ), 356 | ) 357 | 358 | if blockdev is None: 359 | log.error("VM does not have any devices suitable for backup") 360 | sys.exit(1) 361 | 362 | if action == "info": 363 | if argv.show == "blockdev": 364 | log.info("Attached block devices:") 365 | for dev in blockdev: 366 | log.info("%s", lib.json_pp(asdict(dev))) 367 | if argv.show == "bitmaps": 368 | for dev in blockdev: 369 | if not dev.bitmaps: 370 | log.info( 371 | 'No bitmaps found for device: "%s:%s"', dev.node, dev.filename 372 | ) 373 | continue 374 | log.info("%s:", dev.node) 375 | log.info("%s", lib.json_pp(dev.bitmaps)) 376 | 377 | if action == "cleanup": 378 | if argv.uuid != "": 379 | log.info("Removing bitmaps matching uuid [%s]", argv.uuid) 380 | await qemu_client.remove_bitmaps(blockdev, uuid=argv.uuid) 381 | else: 382 | log.info("Removing all existent bitmaps.") 383 | await qemu_client.remove_bitmaps(blockdev) 384 | 385 | if action == "backup": 386 | if argv.quiesce and not argv.agentsocket: 387 | log.warning( 388 | "Quisce option set but agent socket is missing, please set via --agent-socket" 389 | ) 390 | 391 | backupdir = argv.target 392 | for device in blockdev: 393 | tdir = backupdir 394 | if not argv.no_subdir: 395 | nodename = device.node 396 | if device.node.startswith("#block"): 397 | nodename = device.device 398 | tdir = os.path.join(backupdir, nodename) 399 | if ( 400 | device.has_bitmap is False 401 | and argv.level == "inc" 402 | and device.format != "raw" 403 | ): 404 | log.error( 405 | "[%s:%s] Incremental backup requested but no active bitmap has been found.", 406 | device.node, 407 | device.filename, 408 | ) 409 | sys.exit(1) 410 | if argv.level == "inc": 411 | if not lib.has_full(tdir, device.filename): 412 | log.error( 413 | "No full backup found for device [%s:%s] in [%s]: Execute full backup first.", 414 | device.node, 415 | os.path.basename(device.filename), 416 | tdir, 417 | ) 418 | sys.exit(1) 419 | if ( 420 | not lib.check_bitmap_uuid(device.bitmaps, uuid) 421 | and device.format != "raw" 422 | ): 423 | log.error("Unable to find any bitmap with uuid: [%s]", uuid) 424 | sys.exit(1) 425 | if ( 426 | not lib.check_bitmap_state(device.node, device.bitmaps) 427 | and device.format != "raw" 428 | ): 429 | log.error( 430 | "Bitmap for device [%s:%s] is not in state ready for backup.", 431 | device.node, 432 | os.path.basename(device.filename), 433 | ) 434 | sys.exit(1) 435 | if not lib.has_full(tdir, device.filename): 436 | log.error( 437 | "No full backup found for device [%s:%s] in [%s]: Execute full backup first.", 438 | device.node, 439 | os.path.basename(device.filename), 440 | tdir, 441 | ) 442 | sys.exit(1) 443 | if lib.has_partial(tdir): 444 | log.error( 445 | "Partial backup found in [%s], possible broken backup chain. Execute new full backup", 446 | tdir, 447 | ) 448 | sys.exit(1) 449 | 450 | try: 451 | image.save_info(backupdir, blockdev) 452 | targetfiles, fleecefiles = image.create(argv, backupdir, blockdev) 453 | except RuntimeError as errmsg: 454 | log.fatal(errmsg) 455 | sys.exit(1) 456 | 457 | qga = False 458 | if argv.agentsocket and argv.quiesce: 459 | qga = lib.connect_qaagent(argv.agentsocket) 460 | if qga: 461 | fs.quiesce(qga) 462 | 463 | try: 464 | await qemu_client.prepare_target_devices(argv, blockdev, targetfiles) 465 | await qemu_client.prepare_fleece_devices(blockdev, fleecefiles) 466 | await qemu_client.add_cbw_device(argv, blockdev, uuid) 467 | await qemu_client.blockdev_replace(blockdev, action="enable") 468 | await qemu_client.add_snapshot_access_devices(blockdev) 469 | await qemu_client.backup(argv, blockdev, qga, uuid) 470 | except (QMPError, RuntimeError) as errmsg: 471 | log.fatal("Error executing backup: %s", errmsg) 472 | sys.exit(1) 473 | finally: 474 | if int(argv.remove_delay) > 0: 475 | log.info("Delay removal of devices by [%s] seconds", argv.remove_delay) 476 | sleep(int(argv.remove_delay)) 477 | try: 478 | await qemu_client.remove_snapshot_access_devices(blockdev) 479 | await qemu_client.blockdev_replace(blockdev, action="disable") 480 | await qemu_client.remove_cbw_devices(blockdev) 481 | await qemu_client.remove_target_devices(blockdev) 482 | await qemu_client.remove_fleece_devices(blockdev) 483 | except QMPError as errmsg: 484 | log.warning("Unable to cleanup: %s", errmsg) 485 | if qga is not False: 486 | fs.thaw(qga) 487 | 488 | if argv.level == "copy": 489 | blockdev = vm.get_block_devices( 490 | await qemu_client.do_query_block(), 491 | argv, 492 | excluded_disks, 493 | included_disks, 494 | uuid, 495 | ) 496 | log.info("Removing non-persistent bitmaps used for copy backup.") 497 | await qemu_client.remove_bitmaps(blockdev, prefix="qmpbackup-copy") 498 | 499 | for task in asyncio.all_tasks(): 500 | if task.get_name() == "progress" and task.done() is not True: 501 | log.debug("Cancelling progress job") 502 | task.cancel() 503 | await qmp.disconnect() 504 | 505 | if SIGNAL_CATCHED is True: 506 | log.error("Backup aborted by signal.") 507 | sys.exit(1) 508 | 509 | log.info("Renaming partial files") 510 | for _, saveset in targetfiles.items(): 511 | new_filename = saveset.replace(".partial", "") 512 | try: 513 | os.rename(saveset, new_filename) 514 | except OSError as errmsg: 515 | log.error("Unable to rename files: %s", errmsg) 516 | sys.exit(1) 517 | 518 | if argv.no_symlink is True: 519 | continue 520 | 521 | if argv.level in ("copy", "full") and argv.no_timestamp: 522 | short = os.path.basename(new_filename) 523 | tgtdir = os.path.dirname(new_filename) 524 | os.symlink(new_filename, f"{tgtdir}/{argv.level.upper()}-{short}") 525 | 526 | log.info("Removing fleece image files") 527 | for _, fleeceimage in fleecefiles.items(): 528 | try: 529 | os.remove(fleeceimage) 530 | except OSError as errmsg: 531 | log.error("Unable to remove file: %s", errmsg) 532 | sys.exit(1) 533 | 534 | 535 | if __name__ == "__main__": 536 | asyncio.run(main()) 537 | -------------------------------------------------------------------------------- /qmpbackup.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abbbi/qmpbackup/6f3a7767361fd4e4ccd10c00ce09a17600426ea2/qmpbackup.jpg -------------------------------------------------------------------------------- /qmprestore: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | qmpbackup: Full an incremental backup using Qemus 4 | dirty bitmap feature 5 | 6 | Copyright (C) 2022 Michael Ablassmeier 7 | 8 | Authors: 9 | Michael Ablassmeier 10 | 11 | This work is licensed under the terms of the GNU GPL, version 3. See 12 | the LICENSE file in the top-level directory. 13 | """ 14 | import os 15 | import sys 16 | import argparse 17 | from libqmpbackup import version 18 | from libqmpbackup import image 19 | from libqmpbackup import lib 20 | 21 | parser = argparse.ArgumentParser(prog=sys.argv[0]) 22 | parser.add_argument( 23 | "--skip-check", 24 | default=False, 25 | help="skip image check during restore actions", 26 | action="store_true", 27 | required=False, 28 | ) 29 | 30 | 31 | subparsers = parser.add_subparsers(help="sub-command help") 32 | parser_snapshot = subparsers.add_parser("snapshotrebase", help="snapshotrebase") 33 | parser_rebase = subparsers.add_parser("rebase", help="rebase") 34 | parser_merge = subparsers.add_parser("merge", help="merge") 35 | parser_commit = subparsers.add_parser("commit", help="commit") 36 | 37 | parser_rebase.set_defaults(which="rebase") 38 | parser_rebase.add_argument( 39 | "--dir", type=str, help="directory which contains images", required=True 40 | ) 41 | 42 | parser_snapshot.set_defaults(which="snapshotrebase") 43 | parser_commit.set_defaults(which="commit") 44 | parser_snapshot.add_argument( 45 | "--dir", type=str, help="directory which contains images", required=True 46 | ) 47 | parser_snapshot.add_argument( 48 | "--until", 49 | type=str, 50 | help="point in time restore until specified backup file", 51 | required=False, 52 | ) 53 | parser_snapshot.add_argument( 54 | "--dry-run", 55 | action="store_true", 56 | help="do not run commands, only show them", 57 | required=False, 58 | ) 59 | parser_snapshot.add_argument( 60 | "--filter", 61 | type=str, 62 | help="only process images matching string", 63 | required=False, 64 | default="", 65 | ) 66 | parser_snapshot.add_argument( 67 | "--rate-limit", 68 | type=int, 69 | help="Rate limit passed to qemu-img commit command", 70 | required=False, 71 | default=0, 72 | ) 73 | 74 | parser_commit.add_argument( 75 | "--dir", type=str, help="directory which contains images", required=True 76 | ) 77 | parser_commit.add_argument( 78 | "--until", 79 | type=str, 80 | help="point in time restore until specified backup file", 81 | required=False, 82 | ) 83 | parser_commit.add_argument( 84 | "--dry-run", 85 | action="store_true", 86 | help="do not run commands, only show them", 87 | required=False, 88 | ) 89 | parser_commit.add_argument( 90 | "--filter", 91 | type=str, 92 | help="only process images matching string", 93 | required=False, 94 | default="", 95 | ) 96 | parser_commit.add_argument( 97 | "--rate-limit", 98 | type=int, 99 | help="Rate limit passed to qemu-img commit command", 100 | required=False, 101 | default=0, 102 | ) 103 | parser_merge.set_defaults(which="merge") 104 | parser_merge.add_argument( 105 | "--dir", type=str, help="directory which contains images", required=True 106 | ) 107 | parser_merge.add_argument( 108 | "--targetfile", 109 | type=str, 110 | help="Restore image to specified target file", 111 | required=True, 112 | ) 113 | parser_merge.add_argument( 114 | "--until", 115 | type=str, 116 | help="point in time restore until specified backup file", 117 | required=False, 118 | ) 119 | parser_merge.add_argument( 120 | "--filter", 121 | type=str, 122 | help="only process images matching string", 123 | required=False, 124 | default="", 125 | ) 126 | parser_merge.add_argument( 127 | "--rate-limit", 128 | type=int, 129 | help="Rate limit passed to qemu-img commit command", 130 | required=False, 131 | default=0, 132 | ) 133 | parser_rebase.add_argument( 134 | "--until", 135 | type=str, 136 | help="point in time restore until specified backup file", 137 | required=False, 138 | ) 139 | parser_rebase.add_argument( 140 | "--dry-run", 141 | action="store_true", 142 | help="do not run commands, only show them", 143 | required=False, 144 | ) 145 | parser_rebase.add_argument( 146 | "--filter", 147 | type=str, 148 | help="only process images matching string", 149 | required=False, 150 | default="", 151 | ) 152 | parser_rebase.add_argument( 153 | "--rate-limit", 154 | type=int, 155 | help="Rate limit passed to qemu-img commit command", 156 | required=False, 157 | default=0, 158 | ) 159 | 160 | argv = parser.parse_args() 161 | try: 162 | action = argv.which 163 | except AttributeError: 164 | parser.print_help() 165 | sys.exit(1) 166 | 167 | argv.logfile = "" 168 | argv.syslog = False 169 | argv.debug = False 170 | log = lib.setup_log(argv) 171 | 172 | log.info("Version: %s Arguments: %s", version.VERSION, " ".join(sys.argv)) 173 | 174 | if not os.path.exists(argv.dir): 175 | log.error("Specified target folder does not exist: [%s]", argv.dir) 176 | sys.exit(1) 177 | 178 | if argv.filter != "": 179 | log.info("Filter images in [%s] based on string: [%s]", argv.dir, argv.filter) 180 | 181 | if action in ("rebase", "snapshotrebase", "commit"): 182 | if argv.dry_run: 183 | log.info("Dry run activated, not applying any changes") 184 | 185 | if action == "merge": 186 | log.info("Merging images in source folder: [%s] to [%s]", argv.dir, argv.targetfile) 187 | 188 | if not os.path.exists(os.path.dirname(argv.targetfile)): 189 | os.makedirs(os.path.dirname(argv.targetfile), exist_ok=True) 190 | 191 | if image.merge(argv): 192 | log.info("Image file merge successful.") 193 | sys.exit(0) 194 | 195 | if action == "rebase": 196 | log.info("Rebasing images in source folder: [%s]", argv.dir) 197 | if image.rebase(argv): 198 | log.info("Image file rebase successful.") 199 | sys.exit(0) 200 | 201 | if action == "snapshotrebase": 202 | log.info("Rebasing using snapshot images in source folder: [%s]", argv.dir) 203 | if image.snapshot_rebase(argv): 204 | log.info("Image file rebase successful.") 205 | sys.exit(0) 206 | 207 | if action == "commit": 208 | log.info("Rebasing and committing images in source folder: [%s]", argv.dir) 209 | if image.commit(argv): 210 | log.info("Image file rebase and commit successful.") 211 | sys.exit(0) 212 | 213 | sys.exit(1) 214 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | qemu.qmp >= 0.0.0a0 2 | colorlog 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from setuptools import setup 3 | 4 | 5 | def read(fname): 6 | return open(os.path.join(os.path.dirname(__file__), fname)).read() 7 | 8 | 9 | from libqmpbackup import version 10 | 11 | setup( 12 | name="qmpbackup", 13 | version=version.VERSION, 14 | author="Michael Ablassmeier", 15 | author_email="abi@grinser.de", 16 | description=("Qemu incremental backup via QMP"), 17 | license="GPL", 18 | keywords="qemu incremental backup", 19 | url="https://github.com/abbbi/qmpbackup", 20 | packages=["libqmpbackup"], 21 | long_description=read("README.md"), 22 | classifiers=[ 23 | "Development Status :: 3 - Alpha", 24 | "Topic :: Utilities", 25 | ], 26 | scripts=["qmpbackup", "qmprestore"], 27 | ) 28 | -------------------------------------------------------------------------------- /t/agent.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from time import sleep 3 | 4 | sys.path.append("..") 5 | from libqmpbackup.qaclient import QemuGuestAgentClient 6 | 7 | 8 | class TestCaseAgent(QemuGuestAgentClient): 9 | def create_dir_for_inc(self, target): 10 | self.qga.exec(path="/bin/cp", arg=["-r", "/etc/fstab", target]) 11 | self.qga.exec(path="/bin/sync") 12 | 13 | 14 | while True: 15 | try: 16 | qga = TestCaseAgent("/tmp/qga.sock") 17 | except: 18 | continue 19 | 20 | if not qga.ping(2): 21 | print("Waiting for VM to be reachable via guest agent") 22 | sleep(10) 23 | continue 24 | 25 | print("guest agent is reachable") 26 | break 27 | 28 | cmd = None 29 | try: 30 | cmd = sys.argv[1] 31 | except: 32 | sys.exit(0) 33 | 34 | if cmd is not None: 35 | print("Changing some files within guest") 36 | qga.create_dir_for_inc(f"/tmp/{cmd}") 37 | -------------------------------------------------------------------------------- /t/runtest: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | AGENT_SOCKET=/tmp/qga.sock 3 | QMP_SOCKET=/tmp/socket 4 | PIDFILE="/tmp/qemu.pid" 5 | 6 | cleanup() { 7 | echo "cleanup" 8 | if [ -e ${PIDFILE} ]; then 9 | PID=$(cat ${PIDFILE}) 10 | echo "killing qemu process: ${PID}" 11 | kill -9 "${PID}" 12 | fi 13 | rm -f ${AGENT_SOCKET} 14 | rm -f ${QMP_SOCKET} 15 | rm -f /tmp/file.qcow2 16 | rm -f /tmp/disk1.qcow2 17 | rm -f /tmp/disk2.qcow2 18 | rm -f /tmp/disk3.qcow2 19 | rm -f /tmp/qemu.pid 20 | } 21 | trap cleanup EXIT 22 | 23 | set -e 24 | 25 | rm -rf /tmp/restore 26 | rm -rf /tmp/backup 27 | 28 | IMAGE="https://app.vagrantup.com/generic/boxes/alpine38/versions/3.6.6/providers/libvirt.box" 29 | 30 | exist_files() { 31 | if ! ls "${1}" 1> /dev/null 2>&1; then 32 | echo "backup file ${1} does not exist" 33 | exit 1 34 | fi 35 | } 36 | no_exist_files() { 37 | if ls "${1}" 1> /dev/null 2>&1; then 38 | echo "backup files ${1} should not exist" 39 | exit 1 40 | fi 41 | } 42 | 43 | echo "Downloading image" 44 | [ ! -e /tmp/libvirt.box ] && curl -L -s $IMAGE > /tmp/libvirt.box 45 | [ ! -e /tmp/box.img ] && tar -zxvf /tmp/libvirt.box box.img 46 | mv -f box.img /tmp/disk1.qcow2 47 | if [ -n "${DEBUG_BIG}" ]; then 48 | echo "two big disks" 49 | cp /tmp/disk1.qcow2 /tmp/disk2.qcow2 50 | else 51 | [ ! -e /tmp/disk2.qcow2 ] && qemu-img create -f qcow2 /tmp/disk2.qcow2 10M 52 | fi 53 | [ ! -e /tmp/disk3.raw ] && qemu-img create -f raw /tmp/disk3.raw 10M 54 | [ ! -e /tmp/file.qcow2 ] && qemu-img create -f qcow2 /tmp/file.qcow2 10M 55 | [ ! -e /tmp/disk4.qcow2 ] && qemu-img create -f qcow2 /tmp/disk4.qcow2 10M 56 | 57 | KVMOPT="" 58 | [ -e /dev/kvm ] && KVMOPT="--enable-kvm" && echo "with kvm" 59 | 60 | if [ -z "$DEBUG_CONSOLE" ]; then 61 | echo "without console" 62 | KVMOPT="${KVMOPT} -daemonize -display none" 63 | else 64 | KVMOPT="${KVMOPT} -net nic,model=virtio,macaddr=52:54:00:00:00:01 -net bridge,br=virtbr0" 65 | fi 66 | 67 | echo "Starting qemu process" 68 | qemu-system-x86_64 -name "testvm" $KVMOPT -smp "$(nproc)" -m 1024 \ 69 | -drive node-name=disk1,file=/tmp/disk1.qcow2,format=qcow2 \ 70 | -drive node-name=disk2,file=/tmp/disk2.qcow2,format=qcow2 \ 71 | -drive node-name=disk3,file=/tmp/disk3.raw,format=raw \ 72 | -drive file=/tmp/disk4.qcow2,format=qcow2 \ 73 | -qmp unix:/tmp/socket,server=on,wait=off \ 74 | -qmp unix:/tmp/socket2,server=on,wait=off \ 75 | -chardev socket,path=$AGENT_SOCKET,server=on,wait=off,id=qga0 \ 76 | -device virtio-serial \ 77 | -device "virtserialport,chardev=qga0,name=org.qemu.guest_agent.0" \ 78 | -blockdev driver=qcow2,node-name=disk.0,file.driver=file,file.filename=/tmp/file.qcow2 \ 79 | -device virtio-scsi-pci,id=scsi \ 80 | -device scsi-hd,drive=disk.0,bus=scsi.0 \ 81 | -pidfile ${PIDFILE} 82 | 83 | # wait until qemu agent is reachable within booted Vm, then continue 84 | # with the tests 85 | python3 -u agent.py 86 | 87 | if [ -n "$DEBUG_PAUSE" ]; then 88 | echo "pausing" 89 | sleep 1d 90 | fi 91 | 92 | echo "------------------------------------------------" 93 | echo "Executing qmpbackup tests" 94 | echo "------------------------------------------------" 95 | rm -rf /tmp/backup_no_agent 96 | rm -f /tmp/backup.log 97 | ../qmpbackup --agent-socket /tmp/doenstexist --socket $QMP_SOCKET --logfile /tmp/backup.log backup --level full --exclude disk1 --target /tmp/backup_no_agent/ --quiesce 98 | [ -e /tmp/backup.log ] 99 | [ -e /tmp/backup_no_agent/uuid ] 100 | grep Arguments /tmp/backup.log > /dev/null 101 | grep INFO /tmp/backup.log > /dev/null 102 | 103 | rm -rf /tmp/backup 104 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level full --target /tmp/backup/ --quiesce 105 | rm -rf /tmp/copy_backup 106 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level copy --target /tmp/copy_backup/ --quiesce 107 | 108 | exist_files /tmp/backup//disk1/FULL* 109 | exist_files /tmp/backup//disk2/FULL* 110 | 111 | # no-subdir option 112 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level copy --target /tmp/nosubdir_backup/ --no-subdir --quiesce 113 | exist_files /tmp/nosubdir_backup/*disk1.qcow2 114 | exist_files /tmp/nosubdir_backup/*disk2.qcow2 115 | rm -rf /tmp/nosubdir_backup/ 116 | 117 | 118 | # no-timestamp and no-subdir/no-symlink option 119 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level full --target /tmp/nosubdir_timestamp_backup/ --no-subdir --no-symlink --no-timestamp --quiesce 120 | no_exist_files /tmp/nosubdir_timestamp_backup/FULL* 121 | no_exist_files /tmp/nosubdir_timestamp_backup/FULL* 122 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level inc --target /tmp/nosubdir_timestamp_backup/ --no-subdir --no-symlink --no-timestamp --quiesce 123 | exist_files /tmp/nosubdir_timestamp_backup/INC* 124 | rm -rf /tmp/nosubdir_timestamp_backup/ 125 | 126 | # compress option 127 | rm -rf /tmp/compressed_backup/ 128 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level copy --target /tmp/compressed_backup/ --quiesce --compress 129 | rm -rf /tmp/compressed_backup/ 130 | 131 | # compress option 132 | rm -rf /tmp/raw_backup/ 133 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level full --target /tmp/raw_backup/ --quiesce --include-raw 134 | exist_files /tmp/raw_backup//disk1/FULL* 135 | rm -rf /tmp/raw_backup/ 136 | 137 | # caching and aio options 138 | rm -rf /tmp/caching/ 139 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level full --target /tmp/caching/ --blockdev-aio io_uring 140 | rm -rf /tmp/caching/ 141 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level full --target /tmp/caching/ --blockdev-disable-cache 142 | rm -rf /tmp/caching/ 143 | 144 | # auto backup to empty directory must execute FULL backup 145 | rm -rf /tmp/empty 146 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level auto --target /tmp/empty/ --quiesce 147 | exist_files /tmp/empty//disk1/FULL* 148 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level auto --target /tmp/empty/ --quiesce 149 | exist_files /tmp/empty//disk1/INC* 150 | 151 | # create /tmp/incdata1 within the guest, execute further 152 | # incremental backups 153 | echo "------------------------------------------------" 154 | python3 agent.py incdata1 155 | echo "------------------------------------------------" 156 | 157 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level inc --target /tmp/backup/ --quiesce 158 | exist_files /tmp/backup//disk1/INC* 159 | exist_files /tmp/backup//disk2/INC* 160 | 161 | echo "------------------------------------------------" 162 | python3 agent.py incdata2 163 | echo "------------------------------------------------" 164 | 165 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level auto --target /tmp/backup/ --quiesce 166 | 167 | echo "------------------------------------------------" 168 | python3 agent.py incdata3 169 | echo "------------------------------------------------" 170 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level auto --target /tmp/backup/ --quiesce --compress 171 | 172 | 173 | rm -rf /tmp/monthly 174 | ../qmpbackup --socket $QMP_SOCKET backup --level auto --monthly --target /tmp/monthly/ 175 | exist_files /tmp/monthly/*/*/FULL* 176 | ../qmpbackup --socket $QMP_SOCKET backup --level auto --monthly --target /tmp/monthly/ 177 | exist_files /tmp/monthly/*/*/INC* 178 | 179 | echo "------------------------------------------------" 180 | echo "Executing common functionality tests" 181 | echo "------------------------------------------------" 182 | # exclude/include 183 | rm -rf /tmp/exclude 184 | rm -rf /tmp/include 185 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level full --exclude disk1 --target /tmp/exclude/ --quiesce 186 | [ -e /tmp/exclude/disk1 ] && echo "backed up excluded disk" && exit 1 187 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level full --include disk2 --target /tmp/include/ --quiesce 188 | [ -e /tmp/exclude/disk1 ] && echo "backed up non included disks" && exit 1 189 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level full --target /tmp/delay/ --quiesce --remove-delay 10 190 | 191 | 192 | echo "------------------------------------------------" 193 | echo "Check bitmap information output" 194 | echo "------------------------------------------------" 195 | 196 | 197 | # at this point, block devices must show bitmaps 198 | ../qmpbackup --socket $QMP_SOCKET info --show blockdev | grep "qmpbackup-disk1" 199 | # bitmaps must be active 200 | ../qmpbackup --socket $QMP_SOCKET info --show bitmaps 2>&1 | grep "recording.*true" 201 | # at least one bitmap must be removed at this point 202 | ../qmpbackup --socket $QMP_SOCKET cleanup --remove-bitmap 2>&1 | grep "Removing bitmap: qmpbackup-disk1" 203 | 204 | 205 | # exit code of qmpbackup must be errnous if partial backup is found in directory 206 | rm -rf /tmp/partial_backup 207 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level full --include disk2 --target /tmp/partial_backup/ --quiesce 208 | touch /tmp/partial_backup/disk2/FULL-bar.partial 209 | ../qmpbackup --agent-socket $AGENT_SOCKET --socket $QMP_SOCKET backup --level inc --include disk2 --target /tmp/partial_backup/ --quiesce && exit 1 210 | ../qmprestore rebase --dir /tmp/partial_backup/disk2/ --dry-run && exit 1 211 | 212 | echo "------------------------------------------------" 213 | echo "Executing qmprestore tests: rebase" 214 | echo "------------------------------------------------" 215 | rm -rf /tmp/rebase 216 | cp -a /tmp/backup/disk1/ /tmp/rebase 217 | ../qmprestore rebase --dir /tmp/rebase 218 | virt-ls /tmp/rebase/image /tmp | grep incdata3 219 | rm -rf /tmp/skip_check 220 | cp -a /tmp/backup/disk1/ /tmp/skip_check 221 | ../qmprestore --skip-check rebase --dir /tmp/skip_check 222 | 223 | echo "------------------------------------------------" 224 | echo "Executing qmprestore tests: snapshotrebase" 225 | echo "------------------------------------------------" 226 | rm -rf /tmp/snaprebase 227 | cp -a /tmp/backup/disk1/ /tmp/snaprebase 228 | ../qmprestore snapshotrebase --dir /tmp/snaprebase 229 | qemu-img info "$(find /tmp/snaprebase/ -type f)" | grep "Snapshot" || exit 1 230 | rm -rf /tmp/snaprebase 231 | 232 | echo "------------------------------------------------" 233 | echo "Executing qmprestore tests: commit" 234 | echo "------------------------------------------------" 235 | rm -rf /tmp/commitrebase /tmp/commitrebaselimit 236 | cp -a /tmp/backup/disk1/ /tmp/commitrebase 237 | ../qmprestore commit --dir /tmp/commitrebase 238 | virt-ls -a "$(find /tmp/commitrebase/ -type f)" /tmp | grep incdata3 239 | cp -a /tmp/backup/disk1/ /tmp/commitrebaselimit 240 | ../qmprestore commit --dir /tmp/commitrebaselimit --rate-limit 1000000 241 | 242 | echo "------------------------------------------------" 243 | echo "Executing qmprestore tests: merge" 244 | echo "------------------------------------------------" 245 | RESTORED_FILE="/tmp/restore/restore.qcow2" 246 | rm -rf /tmp/restore 247 | 248 | # merge must not alter original files 249 | md5sum /tmp/backup/disk1/* > /tmp/sum 250 | ../qmprestore merge --dir /tmp/backup/disk1/ --targetfile /tmp/restore/restore.qcow2 251 | echo "merge OK" 252 | md5sum /tmp/backup/disk1/* > /tmp/sum_after_restore 253 | 254 | echo "check if merge has altered original files" 255 | diff /tmp/sum /tmp/sum_after_restore || exit 1 256 | echo "OK" 257 | 258 | qemu-img info "${RESTORED_FILE}" > /dev/null 259 | 260 | ORIGINAL_FILE=$(echo /tmp/backup/disk1/FULL*) 261 | echo "------------------------------------------------------" 262 | echo "Check restored image for contents of all inc backups " 263 | echo "------------------------------------------------------" 264 | qemu-img info "${RESTORED_FILE}" > /dev/null 265 | # between full and inc backup, additional data was changed 266 | # within the image. Diff must show these changes between 267 | # original and on incremental rebased image after restore. 268 | rm -f /tmp/diff 269 | virt-diff -a "$ORIGINAL_FILE" -A "$RESTORED_FILE" > /tmp/diff 270 | grep -m 1 incdata1 /tmp/diff 271 | grep -m 1 incdata2 /tmp/diff 272 | grep -m 1 incdata3 /tmp/diff 273 | 274 | echo "OK" 275 | --------------------------------------------------------------------------------