├── LICENSE ├── LICENSE.gpl2 ├── README.md ├── btrfs-balance-slowly ├── btrfs-balance-slowly.python └── btrfs-scrub-slowly /LICENSE: -------------------------------------------------------------------------------- 1 | btrfs-balance-slowly and btrfs-scrub-slowly are distributed under the GPL V2 2 | (see the copyright notices and the LICENSE.gpl2 file). 3 | 4 | btrfs-balance-slowly.python is made available under Hans van Kranenburg's 5 | licence which is reproduced below: 6 | 7 | Copyright (C) 2019 Graham R. Cobb 8 | Copyright (C) 2017 Hans van Kranenburg 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining 11 | a copy of this software and associated documentation files (the 12 | "Software"), to deal in the Software without restriction, including 13 | without limitation the rights to use, copy, modify, merge, publish, 14 | distribute, sublicense, and/or sell copies of the Software, and to 15 | permit persons to whom the Software is furnished to do so, subject to 16 | the following conditions: 17 | 18 | The above copyright notice and this permission notice shall be included 19 | in all copies or substantial portions of the Software. 20 | 21 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 22 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 23 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 24 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 25 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 26 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 27 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 28 | -------------------------------------------------------------------------------- /LICENSE.gpl2: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # btrfs-balance-slowly.python 2 | 3 | Run btrfs balance with frequent breaks. 4 | 5 | btrfs balance on my main data disk completely disrupts the system. 6 | It runs for several hours and most access to the disk just hangs. 7 | Even creating a new file using "touch" can hang for over an hour while a balance 8 | is in progress. 9 | Many services report timeouts and errors. 10 | In particular, this completely destroys mail processing -- mail handling times out, 11 | which is often treated as a permanent error and mails are lost. 12 | 13 | The balance "limit" filter is useful in reducing the problem 14 | (although a time-based filter instead of a count-based filter would be much more useful). 15 | However, on a heavily used disk, the filtered balance has to be re-run many times. 16 | 17 | This script re-runs the balance operation until it finds no further work to do. 18 | In between each run (called a "portion"), the script sleeps for a while, to allow the 19 | system to perform other work. 20 | Also, commands can be executed before and after each portion run to allow time-sensitive services 21 | such as mail to be stopped during the balance. 22 | 23 | ## Usage 24 | 25 | ``` 26 | btrfs-balance-slowly.python [options] 27 | disk to balance, for example: /mnt/backup2 28 | Options: 29 | -d | --data balance data block groups (default) 30 | -m | --metadata balance metadata block groups 31 | -s | --system balance system block groups 32 | -u | --usage - only consider block groups with up to this percentage used 33 | -l | --limit - maximum number of portions, default 0 (no limit) 34 | -t | --time - maximum duration of the whole operation (in seconds), default 3600 35 | -L | --portion-limit - maximum number of block groups in a portion, default 0 (no limit) 36 | -T | --portion-time - maximum duration for one portion (in seconds), default 3600 37 | -i | --interval - delay between portions (in seconds), default 600 38 | -H | --hook - python function to execute before/after portion of balance, default``hook_null`` 39 | -h | --help display this help 40 | ``` 41 | 42 | ## Hooks 43 | The python function specified with --hook is called before and after each portion with 2 arguments: 44 | ``` 45 | hook (PRE, ) 46 | hook (POST, ) 47 | ``` 48 | ``PRE`` and ``POST`` are constants to indicate which context the hook is being called for. 49 | ```` is a string containing the disk specified on the command line. 50 | 51 | The function must raise an exception if processing is not to continue. 52 | 53 | There are two pre-defined hook functions: ``hook_null`` and ``hook_nomail``. 54 | ``hook_null`` does nothing, and is the default. 55 | 56 | ``hook_nomail`` is specific to my particular use: it stops fetchmail, postfix and dovecot during the run 57 | and restarts them afterwards. It may provide a useful example for creating other hook functions. 58 | 59 | ## Example 60 | Here are some real examples taken from my cron jobs (but with line breaks added for readability) 61 | ``` 62 | 40 2 * * thu root /usr/local/sbin/btrfs-balance-slowly.python --time 3600 --portion-time 600 --interval 300 --hook hook_nomail -d --usage 0 /mnt/data ; 63 | /usr/local/sbin/btrfs-balance-slowly.python --time 600 --interval 300 -m --usage 20 /mnt/data ; 64 | /usr/local/sbin/btrfs-balance-slowly.python --limit 20 --time 7200 --portion-time 600 --hook hook_nomail -d --usage 20 /mnt/data 65 | 66 | 5 3 * * mon root /usr/local/sbin/btrfs-balance-slowly.python -d --usage 0 /mnt/backup2 ; 67 | /usr/local/sbin/btrfs-balance-slowly.python -d -m -u 20 /mnt/backup2 68 | ``` 69 | 70 | ## Notices 71 | ``` 72 | Copyright (C) 2019 Graham R. Cobb 73 | Copyright (C) 2017 Hans van Kranenburg 74 | 75 | Permission is hereby granted, free of charge, to any person obtaining 76 | a copy of this software and associated documentation files (the 77 | "Software"), to deal in the Software without restriction, including 78 | without limitation the rights to use, copy, modify, merge, publish, 79 | distribute, sublicense, and/or sell copies of the Software, and to 80 | permit persons to whom the Software is furnished to do so, subject to 81 | the following conditions: 82 | 83 | The above copyright notice and this permission notice shall be included 84 | in all copies or substantial portions of the Software. 85 | 86 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 87 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 88 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 89 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 90 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 91 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 92 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 93 | 94 | Note: this software is based on btrfs-balance-least-used, by 95 | Hans van Kranenburg . Used with permission. 96 | ``` 97 | 98 | # btrfs-scrub-slowly 99 | 100 | Similar script for btrfs scrub commands. 101 | 102 | Although not as disruptive as balance, scrubs can cause big slowdowns. 103 | 104 | I normally use this with long time limits set but meaning that if it gets too slow I can 105 | manually cancel the scrub knowing that the script will resume it in a while. 106 | 107 | Usage and hooks work the same as btrfs-balance-slowly except that no is used. 108 | 109 | ## Example 110 | Real example from my cron jobs: 111 | ``` 112 | 40 2 1 * * root /usr/local/sbin/btrfs-balance-slowly --portion-time $((6*60*60)) --interval $((1*60*60)) /mnt/data/ 113 | ``` 114 | 115 | ## Notices 116 | Copyright (c) 2016-2018 Graham R. Cobb. 117 | This software is distributed under the GPL (see the copyright notices and the LICENSE.gpl2 file). 118 | 119 | `btrfs-scrub-slowly` is free software; you can redistribute it and/or modify 120 | it under the terms of the GNU General Public License as published by 121 | the Free Software Foundation; either version 2 of the License, or 122 | (at your option) any later version. 123 | 124 | `btrfs-scrub-slowly` is distributed in the hope that it will be useful, 125 | but WITHOUT ANY WARRANTY; without even the implied warranty of 126 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 127 | GNU General Public License for more details. 128 | 129 | # btrfs-balance-slowly 130 | 131 | This is the original `bash` version of the script, no longer maintained. The python version (above) is now the preferred version. 132 | The information below is provided for reference. 133 | 134 | Run btrfs balance with frequent breaks. 135 | 136 | btrfs balance on my main data disk completely disrupts the system. 137 | It runs for several hours and most access to the disk just hangs. 138 | Even creating a new file using "touch" can hang for over an hour while a balance 139 | is in progress. 140 | Many services report timeouts and errors. 141 | In particular, this completely destroys mail processing -- mail handling times out, 142 | which is often treated as a permanent error and mails are lost. 143 | 144 | The balance "limit" filter is useful in reducing the problem 145 | (although a time-based filter instead of a count-based filter would be much more useful). 146 | However, on a heavily used disk, the filtered balance has to be re-run many times. 147 | 148 | This script re-runs the balance command until it finds no further work to do. 149 | In between each run (called a "portion"), the script sleeps for a while, to allow the 150 | system to perform other work. 151 | Also, commands can be executed before and after each run to allow time-sensitive services 152 | such as mail to be stopped during the balance. 153 | 154 | ## Usage 155 | 156 | ``` 157 | btrfs-balance-slowly [options] 158 | balance filter, for example: -dusage=20,limit=10 159 | disk to balance, for example: /mnt/backup2 160 | Options: 161 | -l | --limit - maximum number of portions, default 0 162 | -t | --time - maximum time (in seconds), default 3600 163 | -i | --interval - delay between portions, default 600 164 | -h | --hook - command to execute before/after portion of balance, default "true" 165 | ``` 166 | 167 | ## Hooks 168 | The command specified with --hook is called before and after each portion with 3 arguments: 169 | ``` 170 | hook "pre" 171 | hook "post" 172 | ``` 173 | 174 | The command must exit with success (0) if processing is to continue. 175 | An error return will cause processing to terminate. 176 | 177 | There is one pre-defined hook function: ``hook-nomail``. 178 | This is specific to my particular use: it stops fetchmail, postfix and dovecot during the run 179 | and restarts them afterwards. 180 | 181 | ## Example 182 | Here is a real example taken from my cron jobs (but with line breaks added for readability) 183 | ``` 184 | 4 5 * * thu root /usr/local/sbin/btrfs-balance-slowly --time 600 --interval 300 -musage=0,limit=10 /mnt/data ; 185 | /usr/local/sbin/btrfs-balance-slowly --time 600 --interval 300 -dusage=0,limit=5 /mnt/data ; 186 | /usr/local/sbin/btrfs-balance-slowly --time 600 --interval 300 -musage=20,limit=10 /mnt/data ; 187 | /usr/local/sbin/btrfs-balance-slowly --limit 20 --time 3600 --hook hook-nomail -dusage=20,limit=5 /mnt/data 188 | ``` 189 | 190 | ## Notices 191 | Copyright (c) 2016-2018 Graham R. Cobb. 192 | This software is distributed under the GPL (see the copyright notices and the LICENSE.gpl2 file). 193 | 194 | `btrfs-balance-slowly` is free software; you can redistribute it and/or modify 195 | it under the terms of the GNU General Public License as published by 196 | the Free Software Foundation; either version 2 of the License, or 197 | (at your option) any later version. 198 | 199 | `btrfs-balance-slowly` is distributed in the hope that it will be useful, 200 | but WITHOUT ANY WARRANTY; without even the implied warranty of 201 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 202 | GNU General Public License for more details. 203 | 204 | # Mirrors 205 | 206 | Currently this software is primarily made available on GitHub. GitHub should be used 207 | for issues or pull requests for now. 208 | 209 | Currently the repository is also made available on Codeberg as a secondary repository. 210 | I am investigating Codeberg as a development platform and may switch to it in 211 | the future. 212 | -------------------------------------------------------------------------------- /btrfs-balance-slowly: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright (C) 2016-2018 Graham R. Cobb 3 | # Released under GPL V2 -- see LICENSE 4 | 5 | # Note: the master version of this file is in git but it has to be checked 6 | # and then stored somewhere like /usr/local/sbin/ to be safe to be run automatically by root. 7 | # Never have root automatically run programs/scripts that can be modified by non-root users. 8 | 9 | # btrfs-balance-slowly [options] 10 | # 11 | # Do a btrfs balance with frequent breaks. 12 | # 13 | # This script is designed to run a btrfs balance in portions, using the limit filter. 14 | # There can be delays between portions, and there are hooks to allow services 15 | # to be stopped during the balance portion and restarted again afterwards. 16 | # 17 | 18 | # GRC - on my systems, check there is not a new version to be deployed 19 | [ -x /usr/local/bin/check-usr-local-sbin ] && /usr/local/bin/check-usr-local-sbin "$0" 20 | 21 | interval=600 22 | limit=0 23 | tlimit=3600 24 | hook="true" 25 | portion_tlimit=300 26 | 27 | usage() { 28 | echo "Usage: $0 " '[options] ' 29 | echo $'\t\tbalance filter, for example: -dusage=20,limit=10' 30 | echo $'\t\tdisk to balance, for example: /mnt/backup2' 31 | echo $'Options:' 32 | echo $'\t-l | --limit\t - maximum number of portions, default' $limit 33 | echo $'\t-t | --time\t - maximum total time (in seconds), default' $tlimit 34 | echo $'\t-T | --portion-time\t - timeout for each balance portion (in seconds), default' $portion_tlimit 35 | echo $'\t-i | --interval\t - delay between portions, default' $interval 36 | echo $'\t-h | --hook\t - command to execute before/after portion of balance, default "true"' 37 | } 38 | 39 | while [ $# -gt 2 ] 40 | do 41 | if [ "$1" = "-l" -o "$1" = "--limit" ] 42 | then 43 | limit=$2 44 | shift 2 45 | elif [ "$1" = "-t" -o "$1" = "--time" ] 46 | then 47 | tlimit=$2 48 | shift 2 49 | elif [ "$1" = "-T" -o "$1" = "--portion-time" ] 50 | then 51 | portion_tlimit=$2 52 | shift 2 53 | elif [ "$1" = "-i" -o "$1" = "--interval" ] 54 | then 55 | interval=$2 56 | shift 2 57 | elif [ "$1" = "-h" -o "$1" = "--hook" ] 58 | then 59 | hook=$2 60 | shift 2 61 | else 62 | echo "Unrecognised option $1" 63 | usage 64 | exit 98 65 | fi 66 | done 67 | 68 | if [ $# -ne 2 ] 69 | then 70 | echo "Insufficient arguments" 71 | usage 72 | exit 97 73 | fi 74 | 75 | filter=$1 76 | disk=$2 77 | 78 | start-portion-timer() { 79 | test $portion_tlimit -eq 0 && return 80 | # Run a timer and cancel the balance if it expires 81 | ( for ((i=portion_tlimit; i-- ; )) ; do sleep 1 ; done; echo "Portion timeout ($portion_tlimit seconds)" ; btrfs balance status $disk ; btrfs balance cancel $disk ) & 82 | portion_timer=$! 83 | } 84 | 85 | stop-portion-timer() { 86 | test $portion_tlimit -eq 0 && return 87 | kill $portion_timer 2>/dev/null && wait $portion_timer 2>/dev/null 88 | } 89 | 90 | run-portion() { 91 | # Run one portion. Returns success if at least one chunk was relocated. 92 | 93 | pre-balance-hook "$@" 94 | hookstatus=$? 95 | if [ $hookstatus -ne 0 ] 96 | then 97 | echo "Pre-balance hook failed ($hookstatus)" 98 | return $hookstatus 99 | fi 100 | 101 | start-portion-timer 102 | outfile="$(mktemp)" 103 | command time -v btrfs balance start "$@" >$outfile 104 | runstatus=$? 105 | stop-portion-timer 106 | cat $outfile 107 | 108 | post-balance-hook "$@" 109 | hookstatus=$? 110 | if [ $hookstatus -ne 0 ] 111 | then 112 | echo "Post-balance hook failed ($hookstatus)" 113 | runstatus=$hookstatus 114 | fi 115 | 116 | if [ $runstatus -eq 0 ] 117 | then 118 | # Look at the output to see if anything was done 119 | # Note: this check depends on the format of the btrfs balance output 120 | # but tries to fail-safe: if the output format changes we will return failure 121 | if ! grep --silent 'relocate [1-9]' $outfile 122 | then runstatus=99 123 | fi 124 | fi 125 | 126 | rm $outfile 127 | return $runstatus 128 | } 129 | 130 | pre-balance-hook() { 131 | $hook "pre" "$@" 132 | } 133 | 134 | post-balance-hook() { 135 | $hook "post" "$@" 136 | } 137 | 138 | # Hook function to stop mail handling during the balance 139 | # Used for main data disk 140 | hook-nomail() { 141 | retstatus=0 142 | 143 | if [ "$1" = "pre" ] 144 | then 145 | systemctl stop fetchmail && systemctl stop postfix && systemctl stop dovecot 146 | retstatus=$? 147 | if [ $retstatus -ne 0 ] 148 | then 149 | # Stopping services failed. Try to start them again 150 | logger -s -t $0 "Stopping fetchmail, postfix or dovecot failed. Trying restarting." 151 | systemctl start dovecot 152 | systemctl start postfix 153 | systemctl start fetchmail 154 | fi 155 | elif [ "$1" = "post" ] 156 | then 157 | systemctl start dovecot 158 | tempstatus=$? 159 | if [ $tempstatus -ne 0 ] 160 | then 161 | logger -s -t $0 "Could not restart dovecot: $tempstatus" 162 | retstatus=$tempstatus 163 | # We used to go on and try to restart postfix and fetchmail anyway, 164 | # but now postfix requires dovecot lmtp to be working so we don't go on, just return 165 | return $retstatus 166 | fi 167 | 168 | systemctl start postfix 169 | tempstatus=$? 170 | if [ $tempstatus -ne 0 ] 171 | then 172 | logger -s -t $0 "Could not restart postfix: $tempstatus" 173 | retstatus=$tempstatus 174 | # Postfix has failed. Do not restart fetchmail, just return 175 | return $retstatus 176 | fi 177 | 178 | systemctl start fetchmail 179 | tempstatus=$? 180 | if [ $tempstatus -ne 0 ] 181 | then 182 | logger -s -t $0 "Could not restart fetchmail: $tempstatus" 183 | retstatus=$tempstatus 184 | fi 185 | else 186 | echo "$0 internal error: invalid hook argument $1" 187 | retstatus=97 188 | fi 189 | 190 | return $retstatus 191 | 192 | } 193 | 194 | count=0 195 | seconds=0 196 | portion_start="$(date --utc +%s)" 197 | while run-portion "$@" 198 | do 199 | count=$((count+1)) 200 | portion_end="$(date --utc +%s)" 201 | seconds=$((seconds + 1 + portion_end - portion_start)) 202 | 203 | [ -n "$limit" ] && [ "$limit" -gt 0 ] && [ "$count" -ge "$limit" ] && echo "Limit reached: $limit" && break 204 | [ -n "$tlimit" ] && [ "$tlimit" -gt 0 ] && [ "$seconds" -ge "$tlimit" ] && echo "Time limit reached: $tlimit seconds" && break 205 | 206 | sleep ${interval}s 207 | portion_start="$(date --utc +%s)" 208 | done 209 | 210 | echo "Balance completed in $count portions, $seconds seconds" 211 | -------------------------------------------------------------------------------- /btrfs-balance-slowly.python: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # 3 | # Copyright (C) 2019 Graham R. Cobb 4 | # Copyright (C) 2017 Hans van Kranenburg 5 | # 6 | # Permission is hereby granted, free of charge, to any person obtaining 7 | # a copy of this software and associated documentation files (the 8 | # "Software"), to deal in the Software without restriction, including 9 | # without limitation the rights to use, copy, modify, merge, publish, 10 | # distribute, sublicense, and/or sell copies of the Software, and to 11 | # permit persons to whom the Software is furnished to do so, subject to 12 | # the following conditions: 13 | # 14 | # The above copyright notice and this permission notice shall be included 15 | # in all copies or substantial portions of the Software. 16 | # 17 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 19 | # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 20 | # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 21 | # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 22 | # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | # 25 | # Note: this software is based on btrfs-balance-least-used, by 26 | # Hans van Kranenburg . Used with permission. 27 | 28 | # Note: the master version of this file is in git but it has to be checked 29 | # and then stored somewhere like /usr/local/sbin/ to be safe to be run automatically by root. 30 | # Never have root automatically run programs/scripts that can be modified by non-root users. 31 | 32 | # btrfs-balance-slowly.python [options] 33 | # 34 | # Do a btrfs balance with frequent breaks. 35 | # 36 | # This script is designed to run a btrfs balance in small portions, using limits and filters. 37 | # There can be delays between portions, and there are hooks to allow services 38 | # to be stopped during the balance portion and restarted again afterwards. 39 | # 40 | 41 | 42 | import argparse 43 | import btrfs 44 | import errno 45 | import heapq 46 | import sys 47 | import time 48 | 49 | 50 | class Bork(Exception): 51 | pass 52 | 53 | PRE = 1 54 | POST = 2 55 | 56 | def load_block_groups(fs, max_used_pct, bgflag): 57 | min_used_pct = 101 58 | block_groups = [] 59 | print("Loading block group objects with used_pct <= {} ...".format(max_used_pct), 60 | end='', flush=True) 61 | for chunk in fs.chunks(): 62 | if not (chunk.type & bgflag): 63 | continue 64 | try: 65 | block_group = fs.block_group(chunk.vaddr, chunk.length) 66 | if block_group.used_pct <= max_used_pct: 67 | block_groups.append((block_group.used_pct, block_group)) 68 | if block_group.used_pct < min_used_pct: 69 | min_used_pct = block_group.used_pct 70 | except IndexError: 71 | continue 72 | heapq.heapify(block_groups) 73 | print(" found {}".format(len(block_groups))) 74 | return min_used_pct, block_groups 75 | 76 | def balance_one_block_group(fs, block_groups, max_used_pct): 77 | next_used_pct, next_block_group = block_groups[0] 78 | try: 79 | block_group = fs.block_group(next_block_group.vaddr, next_block_group.length) 80 | except IndexError: 81 | heapq.heappop(block_groups) 82 | return 83 | vaddr = block_group.vaddr 84 | used_pct = block_group.used_pct 85 | flags = block_group.flags 86 | if used_pct > next_used_pct: 87 | if used_pct > max_used_pct: 88 | print("Ignoring block group vaddr {} used_pct changed {} -> {}".format( 89 | vaddr, next_used_pct, used_pct)) 90 | heapq.heappop(block_groups) 91 | else: 92 | print("Postponing block group vaddr {} used_pct changed {} -> {}".format( 93 | vaddr, next_used_pct, used_pct)) 94 | heapq.heapreplace(block_groups, (used_pct, block_group)) 95 | return 96 | 97 | start_time = time.time() 98 | heapq.heappop(block_groups) 99 | args = btrfs.ioctl.BalanceArgs(vstart=vaddr, vend=vaddr+1) 100 | print("Balance block group vaddr {} used_pct {} ...".format( 101 | vaddr, used_pct), end='', flush=True) 102 | try: 103 | if flags & btrfs.BLOCK_GROUP_DATA: 104 | progress = btrfs.ioctl.balance_v2(fs.fd, data_args=args) 105 | elif flags & btrfs.BLOCK_GROUP_METADATA: 106 | progress = btrfs.ioctl.balance_v2(fs.fd, meta_args=args) 107 | elif flags & btrfs.BLOCK_GROUP_SYSTEM: 108 | progress = btrfs.ioctl.balance_v2(fs.fd, sys_args=args) 109 | else: 110 | Bork("Internal error: unrecognised block group type") 111 | end_time = time.time() 112 | print(" duration {} sec total {}".format(int(end_time - start_time), progress.considered)) 113 | except KeyboardInterrupt: 114 | end_time = time.time() 115 | print(" duration {} sec".format(int(end_time - start_time))) 116 | raise 117 | 118 | 119 | def parse_args(): 120 | parser = argparse.ArgumentParser() 121 | parser.add_argument( 122 | '-d', 123 | '--data', 124 | action='store_true', 125 | help="Balance data block groups (default)", 126 | ) 127 | parser.add_argument( 128 | '-m', 129 | '--meta', 130 | action='store_true', 131 | help="Balance metadata block groups", 132 | ) 133 | parser.add_argument( 134 | '-s', 135 | '--system', 136 | action='store_true', 137 | help="Balance system block groups", 138 | ) 139 | parser.add_argument( 140 | '-u', 141 | '--usage', 142 | type=int, 143 | default=100, 144 | help="Only consider block groups with less than this percentage used", 145 | ) 146 | parser.add_argument( 147 | '-l', 148 | '--limit', 149 | type=int, 150 | default=0, 151 | help="Maximum number of portions", 152 | ) 153 | parser.add_argument( 154 | '-t', 155 | '--time', 156 | type=int, 157 | default=3600, 158 | help="Maximum total time (in seconds)", 159 | ) 160 | parser.add_argument( 161 | '-L', 162 | '--portion-limit', 163 | type=int, 164 | default=0, 165 | help="Maximum number of block groups for each balance portion", 166 | ) 167 | parser.add_argument( 168 | '-T', 169 | '--portion-time', 170 | type=int, 171 | default=300, 172 | help="Timeout for each balance portion (in seconds)", 173 | ) 174 | parser.add_argument( 175 | '-i', 176 | '--interval', 177 | type=int, 178 | default=600, 179 | help="Delay between portions (in seconds)", 180 | ) 181 | parser.add_argument( 182 | '-H', 183 | '--hook', 184 | default='hook_null', 185 | help="Command to execute before/after each portion of balance", 186 | ) 187 | parser.add_argument( 188 | 'mountpoint', 189 | help="Btrfs filesystem mountpoint", 190 | ) 191 | return parser.parse_args() 192 | 193 | 194 | def permission_check(fs): 195 | """This is a simple canary function that explodes if the user does not have 196 | enough permissions to use the search ioctl. 197 | """ 198 | fs.top_level() 199 | 200 | def pre_balance_hook(hook, disk): 201 | exec(hook + "(PRE,disk)") 202 | 203 | def post_balance_hook(hook,disk): 204 | exec(hook + "(POST,disk)") 205 | 206 | # Hook which does nothing (default) 207 | def hook_null(context, disk): 208 | if context == PRE : 209 | pass 210 | elif context == POST : 211 | pass 212 | else : 213 | raise Bork("hook_null internal error: invalid hook argument {}".format(context)) 214 | 215 | # Hook used for testing 216 | def hook_test(context, disk): 217 | if context == PRE : 218 | raise Bork("context = {} disk = {}".format(context, disk)) 219 | elif context == POST : 220 | raise Bork("context = {} disk = {}".format(context, disk)) 221 | else : 222 | raise Bork("hook_test internal error: invalid hook argument {}".format(context)) 223 | 224 | # Hook which stops mail handling during balance 225 | # Used for main data disk on server 226 | def hook_nomail(context, disk): 227 | import subprocess 228 | import syslog 229 | if context == PRE : 230 | try : 231 | print("Stopping fetchmail, postfix and dovecot") 232 | subprocess.run(["systemctl","stop","fetchmail"], check=True) 233 | subprocess.run(["systemctl","stop","postfix"], check=True) 234 | subprocess.run(["systemctl","stop","dovecot"], check=True) 235 | except : 236 | # Stopping services failed. Try to start them again 237 | syslog.syslog(syslog.LOG_ERR,"Stopping fetchmail, postfix or dovecot failed. Trying restarting.") 238 | print("Stopping fetchmail, postfix or dovecot failed. Trying restarting.", file=sys.stderr, flush=True) 239 | subprocess.run(["systemctl","start","dovecot"]) 240 | subprocess.run(["systemctl","start","postfix"]) 241 | subprocess.run(["systemctl","start","fetchmail"]) 242 | raise 243 | elif context == POST : 244 | print("Starting fetchmail, postfix and dovecot") 245 | 246 | status_dovecot = subprocess.run(["systemctl","start","dovecot"]).returncode 247 | if status_dovecot != 0 : 248 | syslog.syslog(syslog.LOG_ERR,"Could not restart dovecot: {}".format(status_dovecot)) 249 | print("Could not restart dovecot: {}".format(status_dovecot), file=sys.stderr, flush=True) 250 | # Dovecot has failed, we used to just go on and try to restart postfix and fetchmail anyway 251 | # but now that postifx depends on dovecot-lmtp we don't 252 | raise Bork("Could not restart dovecot: {}".format(status_dovecot)) 253 | 254 | status_postfix = subprocess.run(["systemctl","start","postfix"]).returncode 255 | if status_postfix != 0 : 256 | syslog.syslog(syslog.LOG_ERR,"Could not restart postfix: {}".format(status_postfix)) 257 | # Postfix has failed. Do not restart fetchmail, just return 258 | raise Bork("Could not restart postfix: {}".format(status_postfix)) 259 | 260 | status_fetchmail = subprocess.run(["systemctl","start","fetchmail"]).returncode 261 | if status_fetchmail != 0 : 262 | syslog.syslog(syslog.LOG_ERR,"Could not restart fetchmail: {}".format(status_fetchmail)) 263 | raise Bork("Could not restart fetchmail: {}".format(status_fetchmail)) 264 | 265 | # Postfix and Fetchmail restarted, check whether dovecot failed 266 | # Note: no longer used but left in place in case we go back to restarting postfix when dovecot fails 267 | if status_dovecot != 0 : 268 | raise Bork("Could not restart dovecot: {}".format(status_dovecot)) 269 | else : 270 | raise Bork("hook_nomail internal error: invalid hook argument {}".format(context)) 271 | 272 | def main(): 273 | args = parse_args() 274 | max_used_pct = args.usage 275 | path = args.mountpoint 276 | limit = args.limit 277 | tlimit = args.time 278 | portion_limit = args.portion_limit 279 | portion_tlimit = args.portion_time 280 | interval = args.interval 281 | hook = args.hook 282 | bgflag = (btrfs.BLOCK_GROUP_DATA if args.data else 0) | (btrfs.BLOCK_GROUP_METADATA if args.meta else 0) | (btrfs.BLOCK_GROUP_SYSTEM if args.system else 0) 283 | bgflag = bgflag or btrfs.BLOCK_GROUP_DATA 284 | 285 | try: 286 | with btrfs.FileSystem(path) as fs: 287 | permission_check(fs) 288 | min_used_pct, block_groups = load_block_groups(fs, max_used_pct, bgflag) 289 | if len(block_groups) == 0: 290 | print("Nothing to do, least used block group has used_pct {}".format(min_used_pct)) 291 | return 292 | # Start balance 293 | balance_start_time = time.time() 294 | # Start first portion 295 | portion_count = 1 296 | bg_count = 0 297 | pre_balance_hook(hook, path) 298 | portion_start_time = time.time() 299 | print("Portion {} starting at {}".format(portion_count,time.asctime(time.localtime(portion_start_time)))) 300 | while len(block_groups) > 0 and (time.time() - balance_start_time) < tlimit and (limit == 0 or portion_count <= limit) : 301 | bg_count = bg_count + 1 302 | balance_one_block_group(fs, block_groups, max_used_pct) 303 | if len(block_groups) == 0 or (time.time() - balance_start_time) > tlimit : 304 | break 305 | if (time.time() - portion_start_time) > portion_tlimit or (portion_limit > 0 and bg_count >= portion_limit) : 306 | # End of this portion 307 | # Was this the final portion? 308 | if limit > 0 and portion_count >= limit : 309 | break 310 | print("Portion {} completed at {}. Suspend processing for {} seconds".format(portion_count,time.asctime(time.localtime()),interval)) 311 | post_balance_hook(hook, path) 312 | time.sleep(interval) 313 | portion_count += 1 314 | bg_count = 0 315 | pre_balance_hook(hook, path) 316 | portion_start_time = time.time() 317 | print("Portion {} started at {}".format(portion_count,time.asctime(time.localtime(portion_start_time)))) 318 | # End final portion 319 | print("Final portion {} completed at {}".format(portion_count,time.asctime(time.localtime()))) 320 | post_balance_hook(hook, path) 321 | except OSError as e: 322 | if e.errno == errno.EPERM: 323 | raise Bork("Insufficient permissions to use the btrfs kernel API.\n" 324 | "Hint: Try running the script as root user.".format(e)) 325 | elif e.errno == errno.ENOTTY: 326 | raise Bork("Unable to retrieve data. Hint: Not a mounted btrfs file system?") 327 | raise 328 | 329 | 330 | if __name__ == '__main__': 331 | try: 332 | main() 333 | except KeyboardInterrupt: 334 | print("Exiting...") 335 | sys.exit(130) # 128 + SIGINT 336 | except Bork as e: 337 | print("Error: {0}".format(e), file=sys.stderr) 338 | sys.exit(1) 339 | except Exception as e: 340 | print(e) 341 | sys.exit(1) 342 | -------------------------------------------------------------------------------- /btrfs-scrub-slowly: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Copyright (C) 2016-2018 Graham R. Cobb 3 | # Released under GPL V2 -- see LICENSE 4 | 5 | # Note: the master version of this file is in git but it has to be checked 6 | # and then stored somewhere like /usr/local/sbin/ to be safe to be run automatically by root. 7 | # Never have root automatically run programs/scripts that can be modified by non-root users. 8 | 9 | # btrfs-scrub-slowly [options] 10 | # 11 | # Do a btrfs scrub with frequent breaks. 12 | # 13 | # This script is designed to run a btrfs scrub in portions. 14 | # There can be delays between portions, and there are hooks to allow services 15 | # to be stopped during the scrub portion and restarted again afterwards. 16 | # 17 | 18 | # GRC - on my systems, check there is not a new version to be deployed 19 | [ -x /usr/local/bin/check-usr-local-sbin ] && /usr/local/bin/check-usr-local-sbin "$0" 20 | 21 | interval=$((10*60)) 22 | limit=0 23 | tlimit=0 24 | hook="true" 25 | portion_tlimit=$((1*60*60)) 26 | debug=0 27 | 28 | usage() { 29 | echo "Usage: $0 " '[options] ' 30 | echo $'\t\tdisk to scrub, for example: /mnt/backup2' 31 | echo $'Options:' 32 | echo $'\t-l | --limit\t - maximum number of portions, default' $limit 33 | echo $'\t-t | --time\t - maximum total time (in seconds), default' $tlimit 34 | echo $'\t-T | --portion-time\t - timeout for each scrub portion (in seconds), default' $portion_tlimit 35 | echo $'\t-i | --interval\t - delay between portions, default' $interval 36 | echo $'\t-h | --hook\t - command to execute before/after portion of scrub, default "true"' 37 | echo $'\t-D | --debug - print additional debugging information' 38 | } 39 | 40 | while [ $# -gt 1 ] 41 | do 42 | if [ "$1" = "-l" -o "$1" = "--limit" ] 43 | then 44 | limit=$2 45 | shift 2 46 | elif [ "$1" = "-t" -o "$1" = "--time" ] 47 | then 48 | tlimit=$2 49 | shift 2 50 | elif [ "$1" = "-T" -o "$1" = "--portion-time" ] 51 | then 52 | portion_tlimit=$2 53 | shift 2 54 | elif [ "$1" = "-i" -o "$1" = "--interval" ] 55 | then 56 | interval=$2 57 | shift 2 58 | elif [ "$1" = "-h" -o "$1" = "--hook" ] 59 | then 60 | hook=$2 61 | shift 2 62 | elif [ "$1" = "-D" -o "$1" = "--debug" ] 63 | then 64 | debug=1 65 | shift 66 | else 67 | echo "Unrecognised option $1" 68 | usage 69 | exit 98 70 | fi 71 | done 72 | 73 | if [ $# -ne 1 ] 74 | then 75 | echo "Insufficient arguments" 76 | usage 77 | exit 97 78 | fi 79 | 80 | # total lines of decimal numbers - for adding each device together 81 | total-lines() { 82 | local num total=0 83 | while read num 84 | do 85 | ((total+=num)) 86 | done 87 | echo $total 88 | } 89 | 90 | disk=$1 91 | fs_uuid=$(btrfs fi show "$disk" | grep -o 'uuid: \+[-0-9a-f]\+' | cut -d ' ' -f 2) 92 | fs_size=$(btrfs fi show --raw "$fs_uuid" | grep -o 'size \+[-0-9]\+' | cut -d ' ' -f 2 | total-lines) 93 | 94 | # Calculate how many bytes have been scrubbed, for log messages and for protecting against runaways 95 | calc-bytes-scrubbed() { 96 | btrfs scrub status -dR $1 | fgrep _bytes_scrubbed | grep -o '[0-9]\+' | total-lines 97 | } 98 | 99 | # Debug code to check that last_physical is non-zero. UUID is passed as $1. 100 | # Note: this check is only valid if the scrub has been cancelled or finished. 101 | # If the scrub is running, this file may not be completely up to date. 102 | check-last-physical() { 103 | local status_file_base='/var/lib/btrfs/scrub.status.' 104 | local status_file="${status_file_base}$1" 105 | if grep -F --quiet '|last_physical:0|' "$status_file" 106 | then 107 | echo "%%%ERROR: last_physical is 0" 108 | cat "$status_file" 109 | return 1 110 | fi 111 | return 0 112 | } 113 | 114 | # This function implements waits while showing the time remaining in the process name used by ps 115 | sleep-showing-remaining-seconds() { 116 | # $1 - time to sleep IN SECONDS 117 | # $2 - message 118 | for ((i=$1; i-- ; )) 119 | do 120 | hours="$(($i/3600)):" 121 | [ "$hours" != "0:" ] || hours="" 122 | mins="$((($i%3600)/60)):" 123 | secs="$(($i%60))" 124 | bash -c "exec -a \"$2 ($hours$mins$secs), sleep\" sleep 1s" 125 | done 126 | } 127 | 128 | start-portion-timer() { 129 | test $portion_tlimit -eq 0 && return 130 | # Run a timer and cancel the scrub if it expires 131 | echo "Portion timer ($portion_tlimit seconds) starting" 132 | ( sleep-showing-remaining-seconds $portion_tlimit Scrubbing 133 | # for ((i=portion_tlimit; i-- ; )) ; do sleep 1s ; done 134 | echo "Portion timeout ($portion_tlimit seconds) - scrub will be cancelled" 135 | [ $debug -ne 0 ] && echo '>>>>' && echo "Scrub status just before cancel..." && btrfs scrub status -dR $disk && btrfs scrub status -d $disk && echo '<<<<' 136 | btrfs scrub cancel $disk 137 | ret=$? 138 | # Let the scrub exit 139 | # WARNING: these must not take so long that stop-portion-time can drop through to its kill command before we have exited 140 | # See the comment in stop-portion-timer before changing the following few lines. 141 | sleep 5s 142 | [ $debug -ne 0 ] && echo '>>>>' && echo "Scrub status just after cancel..." && btrfs scrub status -dR $disk && btrfs scrub status -d $disk && echo '<<<<' 143 | [ $debug -ne 0 ] && check-last-physical $fs_uuid 144 | exit $ret 145 | ) & 146 | portion_timer=$! 147 | } 148 | 149 | stop-portion-timer() { 150 | # Note: if return value is 129 the portion timer is not configured 151 | # if return value is 143, then the kill killed the portion timer while it was still running 152 | # (scrub finished before portion timer finished) 153 | # If it is <= 128 it is the return value from the scrub cancel in the portion timer 154 | test $portion_tlimit -eq 0 && return 129 155 | # Reduce race with portion timer finishing cancel processing (and debug output) 156 | # WARNING - the sleep below must be long enough for the "scrub exit" actions in start-portion-timer 157 | sleep 10s 158 | kill $portion_timer 2>/dev/null 159 | wait $portion_timer 2>/dev/null 160 | } 161 | 162 | run-portion() { 163 | # Run one portion. Returns success if should be run again 164 | 165 | pre-scrub-hook "$@" 166 | hookstatus=$? 167 | if [ $hookstatus -ne 0 ] 168 | then 169 | echo "Pre-scrub hook failed ($hookstatus)" 170 | return $hookstatus 171 | fi 172 | 173 | echo "Scrub status before $startorresume..." 174 | echo '>>>>' && btrfs scrub status -dR $disk && btrfs scrub status -d $disk && echo '<<<<' 175 | [ $debug -ne 0 -a "$count" -gt 1 ] && check-last-physical $fs_uuid 176 | echo "scrub $count $startorresume ..." 177 | start-portion-timer 178 | outfile="$(mktemp)" 179 | command time -v nice -10 btrfs scrub $startorresume -Bd -c 3 "$@" >$outfile 180 | runstatus=$? 181 | stop-portion-timer 182 | timerstatus=$? 183 | cat $outfile ; echo 184 | [ $debug -ne 0 ] && echo "actual runstatus=$runstatus, timerstatus=$timerstatus" 185 | # Next run will be a "resume" 186 | startorresume="resume" 187 | # Scrub status 0 means the scrub finished, which means do not try again 188 | if [ $runstatus -eq 0 ] 189 | then 190 | runstatus=255 191 | fi 192 | # Scrub status 1 and timer status <= 128 means the scrub ran out of time 193 | # and was cancelled, which means try again 194 | if [ $runstatus -eq 1 -a $timerstatus -le 128 ] 195 | then 196 | runstatus=0 197 | fi 198 | 199 | post-scrub-hook "$@" 200 | hookstatus=$? 201 | if [ $hookstatus -ne 0 ] 202 | then 203 | echo "Post-scrub hook failed ($hookstatus)" 204 | runstatus=$hookstatus 205 | fi 206 | 207 | [ $debug -ne 0 ] && echo "modified runstatus=$runstatus" 208 | 209 | # Debugging bad last_physical 210 | if [ $debug -ne 0 ] 211 | then 212 | # This check is being tested to see if it can replace the one below 213 | check-last-physical $fs_uuid 214 | 215 | # If we are going to resume, at least one last_physical must be non-zero 216 | if [ $runstatus -eq 0 ] 217 | then 218 | last_physical=0 219 | btrfs scrub status -dR $disk | fgrep last_physical | grep -o '[0-9]\+' | 220 | { 221 | while read num 222 | do 223 | ((last_physical+=num)) 224 | done 225 | 226 | if [ $last_physical -eq 0 ] 227 | then 228 | echo "%%%ERROR: Resuming with all last_physical equal to 0!!" 229 | 230 | echo '>>>>' && btrfs scrub status -dR $disk && btrfs scrub status -d $disk && echo '<<<<' 231 | fi 232 | } 233 | fi 234 | fi 235 | 236 | rm $outfile 237 | return $runstatus 238 | } 239 | 240 | pre-scrub-hook() { 241 | $hook "pre" "$@" 242 | } 243 | 244 | post-scrub-hook() { 245 | $hook "post" "$@" 246 | } 247 | 248 | # Hook function to stop mail handling during the scrub 249 | # Used for main data disk 250 | hook-nomail() { 251 | retstatus=0 252 | 253 | if [ "$1" = "pre" ] 254 | then 255 | systemctl stop fetchmail && systemctl stop postfix && systemctl stop dovecot 256 | retstatus=$? 257 | if [ $retstatus -ne 0 ] 258 | then 259 | # Stopping services failed. Try to start them again 260 | logger -s -t $0 "Stopping fetchmail, postfix or dovecot failed. Trying restarting." 261 | systemctl start dovecot 262 | systemctl start postfix 263 | systemctl start fetchmail 264 | fi 265 | elif [ "$1" = "post" ] 266 | then 267 | systemctl start dovecot 268 | tempstatus=$? 269 | if [ $tempstatus -ne 0 ] 270 | then 271 | logger -s -t $0 "Could not restart dovecot: $tempstatus" 272 | retstatus=$tempstatus 273 | # Dovecot has failed, we used to just go on and try to restart postfix and fetchmail anyway 274 | # but now that postifx depends on dovecot-lmtp we don't 275 | return $retstatus 276 | fi 277 | 278 | systemctl start postfix 279 | tempstatus=$? 280 | if [ $tempstatus -ne 0 ] 281 | then 282 | logger -s -t $0 "Could not restart postfix: $tempstatus" 283 | retstatus=$tempstatus 284 | # Postfix has failed. Do not restart fetchmail, just return 285 | return $retstatus 286 | fi 287 | 288 | systemctl start fetchmail 289 | tempstatus=$? 290 | if [ $tempstatus -ne 0 ] 291 | then 292 | logger -s -t $0 "Could not restart fetchmail: $tempstatus" 293 | retstatus=$tempstatus 294 | fi 295 | else 296 | echo "$0 internal error: invalid hook argument $1" 297 | retstatus=97 298 | fi 299 | 300 | return $retstatus 301 | 302 | } 303 | 304 | echo "Starting scrub on $disk ($fs_size bytes)" 305 | 306 | portion_start="$(date --utc +%s)" 307 | startorresume="start" 308 | seconds=0 309 | count=1 310 | 311 | while 312 | run-portion "$@" 313 | do 314 | portion_end="$(date --utc +%s)" 315 | ((seconds += 1 + portion_end - portion_start)) 316 | 317 | [ -n "$limit" ] && [ "$limit" -gt 0 ] && [ "$count" -ge "$limit" ] && echo "Limit reached: $limit" && break 318 | [ -n "$tlimit" ] && [ "$tlimit" -gt 0 ] && [ "$seconds" -ge "$tlimit" ] && echo "Time limit reached: $tlimit seconds" && break 319 | 320 | # Work out number of bytes scrubbed so far 321 | scrubbed=$(calc-bytes-scrubbed $disk) 322 | [ $debug -ne 0 ] && echo "Scrubbed bytes: $scrubbed of $fs_size ($((100*scrubbed/fs_size))%)" 323 | [[ "$scrubbed" -gt $((2*fs_size)) ]] && echo "ERROR: Scrubbed bytes ($scrubbed) more than twice disk total size ($fs_size)!!" && break 324 | 325 | [ $debug -ne 0 ] && echo "Scrub status before sleeping..." && echo '>>>>' && btrfs scrub status -dR $disk && btrfs scrub status -d $disk && echo '<<<<' 326 | sleep-showing-remaining-seconds ${interval} Paused 327 | portion_start="$(date --utc +%s)" 328 | ((count++)) 329 | done 330 | portion_end="$(date --utc +%s)" 331 | ((seconds += 1 + portion_end - portion_start)) 332 | ((count++)) 333 | 334 | btrfs scrub status -dR $disk && btrfs scrub status -d $disk 335 | echo "Scrub completed in $count portions, $seconds seconds" 336 | --------------------------------------------------------------------------------