reniced-1.23/0000755000175000017500000000000014052471336012047 5ustar mitchmitchreniced-1.23/README.md0000644000175000017500000001315414052471336013332 0ustar mitchmitch[![Linux Test](https://github.com/mmitch/reniced/actions/workflows/test_linux.yml/badge.svg)](https://github.com/mmitch/reniced/actions/workflows/test_linux.yml) [![GPL 2+](https://img.shields.io/badge/license-GPL%202%2B-blue.svg)](http://www.gnu.org/licenses/gpl-2.0-standalone.html) # NAME reniced - renice running processes based on regular expressions # SYNOPSIS **reniced** \[**-h**\] \[**-v**\] \[**-o** _format_\] \[_configfile_\] # OVERVIEW reniced takes a list of regular expressions, looks for processes (and threads) matching them and renices the processes to given values. reniced can also change io priorities. # DESCRIPTION On start, reniced reads a configuration file. It consists of nice values and regular expressions. It then scans the process table using the [ps(1)](http://man.he.net/man1/ps) command. Whenever a process name from the CMD column matches a regular expression, that process is reniced to the given value. If a process matches multiple regular expressions, all rule matches are executed in order and the last match wins. When run as root, reniced will scan all processes (`` `ps H -e` ``). When run as a user, renice only scans the user's processes (`` `ps H --user` ``). ## Switches - **-h** This prints the version number, a short help text and exits without doing anything. - **-n** This activates no-op mode. No actions are taken but everything that would be done is written to stdout. - **-v** This activates verbose mode. Error messages, some statistics and all renice actions are printed to stdout. - **-o** _format_ Set the [ps(1)](http://man.he.net/man1/ps) output format to filter on. The default format is `comm`. See the **-o** parameter in the [ps(1)](http://man.he.net/man1/ps) manpage for details. - _configfile_ This reads the regular expressions from an alternate configfile. The default location of the configfile is `/etc/reniced.conf` if reniced is run as root, `~/.reniced` otherwise. ## Configuration file format The configuration file is composed of single lines. Empty lines and lines starting with a **#** are ignored. Every line must consist of a command followed by a whitespace and a Perl regular expression. The regular expression is matched against the [ps(1)](http://man.he.net/man1/ps) output. For every matched process the command is executed. A command generally takes the form of a character followed by a number. Multiple commands can be given simultaneously with no spaces inbetween. Sometimes the number is optional. ### Command characters - **n** Sets the nice value of a process. Must be followed by a number, usually within the range of -20 to 19. For backwards compatibility a **n** at the beginning of the command can be left out (if the command starts with a number it is treated as a nice value). - **r** Sets the io priority to the realtime scheduling class. The optional number is treated as class data (typically 0-7, lower being higher priority). - **b** Sets the io priority to the best-effort scheduling class. The optional number is treated as class data (typically 0-7, lower being higher priority). - **i** Sets the io priority to the idle scheduling class. No number needs to be given as the idle scheduling class ignores the class data value. - **o** Sets the OOM killer adjustment in `/proc/$PID/oom_adj` to the given number. (Internally, `/proc/$PID/oom_score_adj` will be used when available, but for backwards compatibility this value is still expected the in old `oom_adj` format and will be converted automatically.) ### Examples - `5 ^bash` gives currently running bash shells a nice value of 5 - `b2 ^tar` sets currently running tar-processes to io priority best-effort within class 2 - `i torrent` sets currently running torrent-like applications to io priority idle - `n-10r4 seti` gives currently running seti-processes a nice value of -10 and sets them to realtime io priority in class 4 # MODULES NEEDED use BSD::Resource; This module can be obtained from [http://www.cpan.org](http://www.cpan.org). # PROGRAMS NEEDED ps ionice ionice is only needed if you want to change io priority. It can be obtained from [http://rlove.org/schedutils/](http://rlove.org/schedutils/). You also need a suitable kernel and scheduler, e.g. Linux 2.6 with CFQ. # LIMITATIONS The purpose of reniced is to renice long running server processes (hence the **d** for daemon in it's name). Selecting and renicing processes it not atomic: There is a small gap between scanning the process list and renicing the processes. If you target short-lived processes with your regular expressions, reniced might try to act on a process that is already gone. In the worst case it might renice a new process that got the same process id as the already ended process that was matched. # BUGS reniced can run without the BSD::Resource module. In this case, the PRIO\_PROCESS is set to 0. This works on Linux 2.6.11 i686 but it could break on other systems. Installing BSD::Resource is the safer way. Be careful using realtime priorities, don't starve other tasks. Please report bugs to <`mitch@cgarbs.de`>. # AUTHOR reniced was written by Christian Garbs <`mitch@cgarbs.de`>. # COPYRIGHT reniced is Copyright (C) 2005, 2020 by Christian Garbs. It is licensed under the GNU GPL v2 or later. # AVAILABILITY Look for updates at [https://github.com/mmitch/reniced](https://github.com/mmitch/reniced). # SEE ALSO [ionice(1)](http://man.he.net/man1/ionice), [renice(1)](http://man.he.net/man1/renice), [ps(1)](http://man.he.net/man1/ps) reniced-1.23/reniced.conf0000644000175000017500000000070614052471336014332 0ustar mitchmitch# example configuration for reniced # format: # command perl_regular_expression # high prio network services 0 ^apache 0 ^nfsd 0 ^ntpd 0 ^openvpn 0 ^portmap 0 ^ppp 0 ^rpc. 0 ^sshd # medium prio network services 5 ^inn$ 5 ^mysqld # low prio network services 15i ^amavisd-new 15i ^clamd 15 ^controlchan 15 ^exim4 15 ^freshclam 15 ^innwatch 12 ^mailman 15 ^rc.news 15i ^spamd # long running user processes (screen) 3 ^irssi # test OOM settings o1 bash reniced-1.23/COPYRIGHT0000644000175000017500000004310314052471336013343 0ustar mitchmitch GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. reniced-1.23/HISTORY0000644000175000017500000000300114052471336013125 0ustar mitchmitchreniced HISTORY ---------------------------- 2021-06-17 revision 1.23 - fix error when using BSD::Resource ---------------------------- 2020-06-17 revision 1.22 - fix for PIDs longer than 5 digits - fix fallback for missing BSD::Resource - add no-op mode (-n) ---------------------------- 2016-05-15 revision 1.21 - clarify license: GNU GPL v2 or later - add a README.md ---------------------------- 2016-04-05 revision 1.20 - support newer oom_score_adj kernel interface (patch by Michal Hocko ) - fallback to old deprecated oom_adj interface if needed - no configuration changes, existing oom_adj values are converted to oom_score_adj as needed - don't print oom adjustment value to STDOUT - update manpage - add LIMITATION section - update project homepage ---------------------------- 2010-09-19 revision 1.19 - allow adjustment of OOM killer ---------------------------- 2010-06-06 revision 1.18 - add -o parameter to change ps(1) format to filter on ---------------------------- 2007-08-05 revision 1.17 - documentation updates ---------------------------- 2007-08-01 revision 1.15 - include patch from Mario Galanti to match threads as well, not only processes - add HISTORY ---------------------------- 2007-04-20 revision 1.13 - enable setting of io priorities through ionice - fix PRIO_PROCESS inquiry (pure luck that this has worked so far) ---------------------------- 2005-04-17 revision 1.5 - initial release reniced-1.23/reniced.10000644000175000017500000002372214052471336013550 0ustar mitchmitch.\" Automatically generated by Pod::Man 4.10 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "RENICED 1" .TH RENICED 1 "2021-05-23" "1.23" "reniced" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" reniced \- renice running processes based on regular expressions .SH "SYNOPSIS" .IX Header "SYNOPSIS" \&\fBreniced\fR [\fB\-h\fR] [\fB\-v\fR] [\fB\-o\fR\ \fIformat\fR] [\fIconfigfile\fR] .SH "OVERVIEW" .IX Header "OVERVIEW" reniced takes a list of regular expressions, looks for processes (and threads) matching them and renices the processes to given values. reniced can also change io priorities. .SH "DESCRIPTION" .IX Header "DESCRIPTION" On start, reniced reads a configuration file. It consists of nice values and regular expressions. .PP It then scans the process table using the \fBps\fR\|(1) command. Whenever a process name from the \s-1CMD\s0 column matches a regular expression, that process is reniced to the given value. If a process matches multiple regular expressions, all rule matches are executed in order and the last match wins. .PP When run as root, reniced will scan all processes (\f(CW\*(C`\`ps H \-e\`\*(C'\fR). When run as a user, renice only scans the user's processes (\f(CW\*(C`\`ps H \-\-user\`\*(C'\fR). .SS "Switches" .IX Subsection "Switches" .IP "\fB\-h\fR" 5 .IX Item "-h" This prints the version number, a short help text and exits without doing anything. .IP "\fB\-n\fR" 5 .IX Item "-n" This activates no-op mode. No actions are taken but everything that would be done is written to stdout. .IP "\fB\-v\fR" 5 .IX Item "-v" This activates verbose mode. Error messages, some statistics and all renice actions are printed to stdout. .IP "\fB\-o\fR \fIformat\fR" 5 .IX Item "-o format" Set the \fBps\fR\|(1) output format to filter on. The default format is \&\f(CW\*(C`comm\*(C'\fR. See the \fB\-o\fR parameter in the \fBps\fR\|(1) manpage for details. .IP "\fIconfigfile\fR" 5 .IX Item "configfile" This reads the regular expressions from an alternate configfile. .Sp The default location of the configfile is \f(CW\*(C`/etc/reniced.conf\*(C'\fR if reniced is run as root, \f(CW\*(C`~/.reniced\*(C'\fR otherwise. .SS "Configuration file format" .IX Subsection "Configuration file format" The configuration file is composed of single lines. Empty lines and lines starting with a \fB#\fR are ignored. .PP Every line must consist of a command followed by a whitespace and a Perl regular expression. .PP The regular expression is matched against the \fBps\fR\|(1) output. For every matched process the command is executed. .PP A command generally takes the form of a character followed by a number. Multiple commands can be given simultaneously with no spaces inbetween. Sometimes the number is optional. .PP \fICommand characters\fR .IX Subsection "Command characters" .IP "\fBn\fR" 5 .IX Item "n" Sets the nice value of a process. Must be followed by a number, usually within the range of \-20 to 19. .Sp For backwards compatibility a \fBn\fR at the beginning of the command can be left out (if the command starts with a number it is treated as a nice value). .IP "\fBr\fR" 5 .IX Item "r" Sets the io priority to the realtime scheduling class. The optional number is treated as class data (typically 0\-7, lower being higher priority). .IP "\fBb\fR" 5 .IX Item "b" Sets the io priority to the best-effort scheduling class. The optional number is treated as class data (typically 0\-7, lower being higher priority). .IP "\fBi\fR" 5 .IX Item "i" Sets the io priority to the idle scheduling class. No number needs to be given as the idle scheduling class ignores the class data value. .IP "\fBo\fR" 5 .IX Item "o" Sets the \s-1OOM\s0 killer adjustment in \f(CW\*(C`/proc/$PID/oom_adj\*(C'\fR to the given number. (Internally, \f(CW\*(C`/proc/$PID/oom_score_adj\*(C'\fR will be used when available, but for backwards compatibility this value is still expected the in old \f(CW\*(C`oom_adj\*(C'\fR format and will be converted automatically.) .PP \fIExamples\fR .IX Subsection "Examples" .ie n .IP """5 ^bash""" 5 .el .IP "\f(CW5 ^bash\fR" 5 .IX Item "5 ^bash" gives currently running bash shells a nice value of 5 .ie n .IP """b2 ^tar""" 5 .el .IP "\f(CWb2 ^tar\fR" 5 .IX Item "b2 ^tar" sets currently running tar-processes to io priority best-effort within class 2 .ie n .IP """i torrent""" 5 .el .IP "\f(CWi torrent\fR" 5 .IX Item "i torrent" sets currently running torrent-like applications to io priority idle .ie n .IP """n\-10r4 seti""" 5 .el .IP "\f(CWn\-10r4 seti\fR" 5 .IX Item "n-10r4 seti" gives currently running seti-processes a nice value of \-10 and sets them to realtime io priority in class 4 .SH "MODULES NEEDED" .IX Header "MODULES NEEDED" .Vb 1 \& use BSD::Resource; .Ve .PP This module can be obtained from . .SH "PROGRAMS NEEDED" .IX Header "PROGRAMS NEEDED" .Vb 2 \& ps \& ionice .Ve .PP ionice is only needed if you want to change io priority. It can be obtained from . .PP You also need a suitable kernel and scheduler, e.g. Linux 2.6 with \&\s-1CFQ.\s0 .SH "LIMITATIONS" .IX Header "LIMITATIONS" The purpose of reniced is to renice long running server processes (hence the \fBd\fR for daemon in it's name). .PP Selecting and renicing processes it not atomic: There is a small gap between scanning the process list and renicing the processes. If you target short-lived processes with your regular expressions, reniced might try to act on a process that is already gone. In the worst case it might renice a new process that got the same process id as the already ended process that was matched. .SH "BUGS" .IX Header "BUGS" reniced can run without the BSD::Resource module. In this case, the \&\s-1PRIO_PROCESS\s0 is set to 0. This works on Linux 2.6.11 i686 but it could break on other systems. Installing BSD::Resource is the safer way. .PP Be careful using realtime priorities, don't starve other tasks. .PP Please report bugs to <\fImitch@cgarbs.de\fR>. .SH "AUTHOR" .IX Header "AUTHOR" reniced was written by Christian Garbs <\fImitch@cgarbs.de\fR>. .SH "COPYRIGHT" .IX Header "COPYRIGHT" reniced is Copyright (C) 2005, 2020 by Christian Garbs. It is licensed under the \s-1GNU GPL\s0 v2 or later. .SH "AVAILABILITY" .IX Header "AVAILABILITY" Look for updates at . .SH "SEE ALSO" .IX Header "SEE ALSO" \&\fBionice\fR\|(1), \fBrenice\fR\|(1), \fBps\fR\|(1) reniced-1.23/reniced0000755000175000017500000003527414052471336013421 0ustar mitchmitch#!/usr/bin/env perl # # reniced - renice running processes based on regular expressions # # Copyright (C) 2005, 2020, 2021 Christian Garbs # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. use strict; use warnings; =begin markdown [![Build Status](https://travis-ci.org/mmitch/reniced.svg?branch=master)](https://travis-ci.org/mmitch/reniced) [![GPL 2+](https://img.shields.io/badge/license-GPL%202%2B-blue.svg)](http://www.gnu.org/licenses/gpl-2.0-standalone.html) =end markdown =head1 NAME reniced - renice running processes based on regular expressions =head1 SYNOPSIS B S<[B<-h>]> S<[B<-v>]> S<[B<-o> I]> S<[I]> =head1 OVERVIEW reniced takes a list of regular expressions, looks for processes (and threads) matching them and renices the processes to given values. reniced can also change io priorities. =head1 DESCRIPTION On start, reniced reads a configuration file. It consists of nice values and regular expressions. It then scans the process table using the L command. Whenever a process name from the CMD column matches a regular expression, that process is reniced to the given value. If a process matches multiple regular expressions, all rule matches are executed in order and the last match wins. When run as root, reniced will scan all processes (C<`ps H -e`>). When run as a user, renice only scans the user's processes (C<`ps H --user`>). =head2 Switches =over 5 =item B<-h> This prints the version number, a short help text and exits without doing anything. =item B<-n> This activates no-op mode. No actions are taken but everything that would be done is written to stdout. =item B<-v> This activates verbose mode. Error messages, some statistics and all renice actions are printed to stdout. =item B<-o> I Set the L output format to filter on. The default format is C. See the B<-o> parameter in the L manpage for details. =item I This reads the regular expressions from an alternate configfile. The default location of the configfile is C if reniced is run as root, C<~/.reniced> otherwise. =back =head2 Configuration file format The configuration file is composed of single lines. Empty lines and lines starting with a B<#> are ignored. Every line must consist of a command followed by a whitespace and a Perl regular expression. The regular expression is matched against the L output. For every matched process the command is executed. A command generally takes the form of a character followed by a number. Multiple commands can be given simultaneously with no spaces inbetween. Sometimes the number is optional. =head3 Command characters =over 5 =item B Sets the nice value of a process. Must be followed by a number, usually within the range of -20 to 19. For backwards compatibility a B at the beginning of the command can be left out (if the command starts with a number it is treated as a nice value). =item B Sets the io priority to the realtime scheduling class. The optional number is treated as class data (typically 0-7, lower being higher priority). =item B Sets the io priority to the best-effort scheduling class. The optional number is treated as class data (typically 0-7, lower being higher priority). =item B Sets the io priority to the idle scheduling class. No number needs to be given as the idle scheduling class ignores the class data value. =item B Sets the OOM killer adjustment in C to the given number. (Internally, C will be used when available, but for backwards compatibility this value is still expected the in old C format and will be converted automatically.) =back =head3 Examples =over 5 =item C<5 ^bash> gives currently running bash shells a nice value of 5 =item C sets currently running tar-processes to io priority best-effort within class 2 =item C sets currently running torrent-like applications to io priority idle =item C gives currently running seti-processes a nice value of -10 and sets them to realtime io priority in class 4 =back =head1 MODULES NEEDED use BSD::Resource; This module can be obtained from L. =head1 PROGRAMS NEEDED ps ionice ionice is only needed if you want to change io priority. It can be obtained from L. You also need a suitable kernel and scheduler, e.g. Linux 2.6 with CFQ. =head1 LIMITATIONS The purpose of reniced is to renice long running server processes (hence the B for daemon in it's name). Selecting and renicing processes it not atomic: There is a small gap between scanning the process list and renicing the processes. If you target short-lived processes with your regular expressions, reniced might try to act on a process that is already gone. In the worst case it might renice a new process that got the same process id as the already ended process that was matched. =head1 BUGS reniced can run without the BSD::Resource module. In this case, the PRIO_PROCESS is set to 0. This works on Linux 2.6.11 i686 but it could break on other systems. Installing BSD::Resource is the safer way. Be careful using realtime priorities, don't starve other tasks. Please report bugs to >. =head1 AUTHOR reniced was written by Christian Garbs >. =head1 COPYRIGHT reniced is Copyright (C) 2005, 2020 by Christian Garbs. It is licensed under the GNU GPL v2 or later. =head1 AVAILABILITY Look for updates at L. =head1 SEE ALSO L, L, L =cut ### Global settings # default values for rulefile position my $rulefile_root = '/etc/reniced.conf'; my $rulefile_user = '~/.reniced'; # default debug value my $debug = 0; # default ps output format my $psformat = 'comm'; # default actions my %actions = ( ADJUST_OOM => \&adjust_oom, SET_PRIO => \&set_priority, SET_IO_PRIO => \&set_io_priority, ); # are we root? my $root = $> == 0; # a dynamically calculated constant :-) my $PRIO_PROCESS; # my %SCHEDULING_CLASS = ( 1 => 'realtime', 2 => 'best-effort', 3 => 'idle' ); ### Subroutines sub show_help() # print options { print << 'EOF'; Usage: reniced [-h] [-v] [-o format] [configfile] Options: -h print help -n only show what would be done -v be verbose -o format output format to filter on see ps(1) manpage for details default: comm configfile read alternative configuration file default: /etc/reniced.conf for root ~/.reniced for others Configuration file format: # is a comment command perl_regular_expression Command format: 5 set nice value to 5 b2 set io priority to best effort class 2 i set io priority to idle -10r4 set nice value to -10 and io priority to realtime class 4 o-10 set OOM value /proc/$PID/oom_adj to -10 Version: reniced 1.23 EOF ; } sub debug(@) # print debug messages { return unless $debug; my $format = shift @_; printf "$format\n", @_; } sub adjust_oom($$$) # adjust OOM parameters for a pid { my ($pid, $cmd, $score) = @_; my $success = 1; my $procfile = '/proc/'.$pid.'/oom_score_adj'; if ( open (PROC, '>', $procfile)) { $score = convert_oom_adj($score); } else { $procfile = '/proc/'.$pid.'/oom_adj'; if (! open (PROC, '>', $procfile) ) { $success = 0; } } if ($success) { print PROC $score."\n"; close PROC or $success = 0; } debug '%sOOM adjust set to %d: %d/%s', $success ? '' : "FAILED ($!): ", $score, $pid, $cmd; } sub adjust_oom_noop($$$) # NO-OP: adjust OOM parameters for a pid { my ($pid, $cmd, $score) = @_; print "would adjust OOM setting of pid $pid to $score\n"; debug 'OOM adjust set to %d: %d/%s', $score, $pid, $cmd; } sub set_priority($$$) # set priority (nice level) of a process { my ($pid, $cmd, $nice) = @_; my $success = setpriority $PRIO_PROCESS, $pid, $nice; debug '%snice set to %d: %d/%s', $success ? '' : 'FAILED: ', $nice, $pid, $cmd; } sub set_priority_noop($$$) # NO-OP: set priority (nice level) of a process { my ($pid, $cmd, $nice) = @_; print "would set priority of $pid to $nice\n"; debug 'nice set to %d: %d/%s', $nice, $pid, $cmd; } sub set_io_priority($$$$) # set IO priority and scheduling class of a process { my ($pid, $cmd, $ioclass, $ionice) = @_ ; my $schedclass = $SCHEDULING_CLASS{$ioclass}; if (defined $ionice) { my $success = system 'ionice', '-c', $ioclass, '-p', $pid, '-n', $ionice; debug '%sionice set to %s, class %d: %d/%s', $success ? 'FAILED: ' : '', $schedclass, $ionice, $pid, $cmd; } else { my $success = system 'ionice', '-c', $ioclass, '-p', $pid; debug '%sionice set to %s: %d/%s', $success ? 'FAILED: ' : '', $schedclass, $pid, $cmd; } } sub set_io_priority_noop($$$$) # NO-OP: set IO priority and scheduling class of a process { my ($pid, $cmd, $ioclass, $ionice) = @_ ; my $schedclass = $SCHEDULING_CLASS{$ioclass}; if (defined $ionice) { printf "would set IO priority for pid $pid to class $ioclass with nice $ionice\n"; debug 'ionice set to %s, class %d: %d/%s', $schedclass, $ionice, $pid, $cmd; } else { printf "would set IO priority for pid $pid to class $ioclass\n"; debug 'ionice set to %s: %d/%s', $schedclass, $pid, $cmd; } } sub get_prio_process() # get the numerical value for PRIO_PROCESS { # Check if BSD::Resource can be loaded eval { require BSD::Resource; }; if (not $@) { # BSD::Resource which has the constant is available $PRIO_PROCESS = eval 'use BSD::Resource qw(PRIO_PROCESS); return BSD::Resource::PRIO_PROCESS'; debug 'PRIO_PROCESS set to %d via BSD::Resource', $PRIO_PROCESS; } else { # dirty fallback, works for my Linux 2.6.11 i686 GNU/Linux # see setpriority(2) and /usr/include/bits/resource.h $PRIO_PROCESS = 0; debug 'PRIO_PROCESS set to %d via fallback', $PRIO_PROCESS; } } sub parse_options() # parse commandline arguments { while (@ARGV) { my $arg = $ARGV[0]; if ($arg eq '-o') { shift @ARGV; if (@ARGV) { $psformat = shift @ARGV; } else { die "-o is missing the format parameter\n"; } next; } if ($arg eq '-v') { shift @ARGV; $debug = 1; next; } if ($arg eq '-n') { shift @ARGV; %actions = ( ADJUST_OOM => \&adjust_oom_noop, SET_PRIO => \&set_priority_noop, SET_IO_PRIO => \&set_io_priority_noop, ); next; } if ($arg eq '-h') { shift @ARGV; show_help(); exit 0; } last; } } sub find_rulefile() # find rulefile { my $rulefile; if ($root) { $rulefile = $rulefile_root; } else { $rulefile = $rulefile_user; } if ($ARGV[0]) { $rulefile = shift @ARGV; } $rulefile =~ s/^~/$ENV{HOME}/; debug 'rulefile: %s', $rulefile; return $rulefile; } sub read_rulefile() # read rules { my $rulefile = find_rulefile(); my @rule; open RULES, '<', $rulefile or die "can't open `$rulefile': $!\n"; while (my $line = ) { chomp $line; next if ($line =~ /^\s*$/); next if ($line =~ /^#/); if ($line =~ /^\s*((?:[norbi]?-?\d*)+)\s+(.+)/) { my $command = $1; my $rule = { REGEXP => $2 }; # add missing n at start (backwards compatibility) $command =~ s/^(-?\d+)/n$1/; # nice value starts with n while ($command =~ s/n(-?\d+)//) { $rule->{NICE} = $1; } # OOM value starts with o while ($command =~ s/o(-?\d+)//) { $rule->{OOMADJ} = $1; } # ionice values start with [rbi] while ($command =~ s/([rbi])(\d+)?//) { if ($1 eq 'r') { $rule->{IOCLASS} = 1; } elsif ($1 eq 'b') { $rule->{IOCLASS} = 2; } elsif ($1 eq 'i') { $rule->{IOCLASS} = 3; } else { warn "rule line #$.: error during IOnice parsing: 1=`$1' 2=`$2' all=`$line'"; } if (defined $2) { $rule->{IONICE} = $2; } } if (scalar keys %{$rule} > 1) { push @rule, $rule; } else { warn "rule line #$. skipped: `$line'\n"; } } else { warn "rules line #$. skipped: `$line'\n"; } } close RULES or die "can't close `$rulefile': $!\n"; debug '%d rules read', scalar @rule; return \@rule; } sub generate_ps_command() # generate ps commandline { my $cmdline = 'ps'; if ($root) { $cmdline .= " H -eo lwp,$psformat"; } else { $cmdline .= " H -o lwp,$psformat --user $>"; } debug 'ps commandline is: %s', $cmdline; return $cmdline; } sub read_processes() # read processes { my @proc; my $cmdline = generate_ps_command(); open PS, '-|', $cmdline or die "can't open `$cmdline': $!\n"; { my $line = ; # skip first line while ($line = ) { chomp $line; if ($line =~ m/^\s*(\d+)\s+(.*)$/) { my ($pid, $cmd) = ($1, $2); push @proc, { PID => $pid, CMD => $cmd }; } } } close PS or die "can't close `$cmdline': $!\n"; debug '%d processes read', scalar @proc; return \@proc; } sub convert_oom_adj($) { my $score = shift; my $OOM_ADJUST_MAX = 15; my $OOM_SCORE_ADJ_MAX = 1000; my $OOM_DISABLE = -17; if ($score == $OOM_ADJUST_MAX) { $score = $OOM_SCORE_ADJ_MAX; } else { $score = int(($score * $OOM_SCORE_ADJ_MAX) / -$OOM_DISABLE); } return $score } sub renice_processes($$) # renice { my $rules = shift; my $procs = shift; foreach my $proc (@{$procs}) { my $pid = $proc->{PID}; my $cmd = $proc->{CMD}; foreach my $rule (@{$rules}) { if ($cmd =~ /$rule->{REGEXP}/) { # nice if (exists $rule->{NICE}) { $actions{SET_PRIO}->($pid, $cmd, $rule->{NICE}); } # OOM adjust if (exists $rule->{OOMADJ}) { $actions{ADJUST_OOM}->($pid, $cmd, $rule->{OOMADJ}); } # IO nice if (exists $rule->{IOCLASS}) { $actions{SET_IO_PRIO}->($pid, $cmd, $rule->{IOCLASS}, $rule->{IONICE}); } } } } } ### Main program parse_options(); get_prio_process(); my $rules = read_rulefile(); exit unless @{$rules}; my $procs = read_processes(); exit unless @{$procs}; renice_processes($rules, $procs); exit 0;