pax_global_header00006660000000000000000000000064132047667560014532gustar00rootroot0000000000000052 comment=46469f425f9844f355f6496785ee1ce993b58747 python-schedutils-0.6/000077500000000000000000000000001320476675600150655ustar00rootroot00000000000000python-schedutils-0.6/COPYING000066400000000000000000000430761320476675600161320ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, 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 Library 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 Appendix: 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) 19yy 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., 675 Mass Ave, Cambridge, MA 02139, 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) 19yy 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 Library General Public License instead of this License. python-schedutils-0.6/ChangeLog000066400000000000000000000020041320476675600166330ustar00rootroot00000000000000v0.4: [acme@mica python-schedutils]$ git log v0.2.. --format=oneline --abbrev-commit 1568357 Fix cpusetsize parameter in sched_setaffinity call 28a2f17 Support SCHED_IDLE in schedfromstr ac29a2e Use PyErr_SetFromErrno return value f09bae5 Fix leak on setaffinity error path 76269f0 Don't set the error string twice 80ce42f Don't limit looking for CPUs at 1024 028a3af Use PyErr_NoMemory when CPU_ALLOC fails 36e377d CPU_ALLOC macros are not present in older systems 6b9f411 sched_setaffinity expects a cpu_set_t pointer, not a ptr to a pointer 741697a Dinamically size the cpu_set_t objects 4f3b33c Support SCHED_RESET_ON_FORK policy flag 66a2327 Add SCHED_IDLE to the list of constants exported 4e05f75 Methods should raise OSError exceptions d3aead2 schedutils: Older kernels don't have SCHED_BATCH defined c162a1e Merge branch 'master' of ssh://master.kernel.org/pub/scm/linux/kernel/git/acme/python-schedutils fb72c8e Makefile: fixup version gathering 10f78ff rpm: Fixed %build and %install sections, part of fedora review python-schedutils-0.6/MANIFEST000066400000000000000000000001701320476675600162140ustar00rootroot00000000000000COPYING pchrt.py ptaskset.py setup.py rpm/SPECS/python-schedutils.spec MANIFEST python-schedutils/schedutils.c Makefile python-schedutils-0.6/Makefile000066400000000000000000000015761320476675600165360ustar00rootroot00000000000000PACKAGE := python-schedutils VERSION := $(shell rpm -q --qf '%{VERSION} ' --specfile rpm/SPECS/$(PACKAGE).spec | cut -d' ' -f1) rpmdirs: @[ -d rpm/BUILD ] || mkdir rpm/BUILD @[ -d rpm/RPMS ] || mkdir rpm/RPMS @[ -d rpm/SRPMS ] || mkdir rpm/SRPMS @[ -d rpm/SOURCES ] || mkdir rpm/SOURCES bz2: rpmdirs git archive --format=tar --prefix=$(PACKAGE)-$(VERSION)/ HEAD | \ bzip2 -9 > rpm/SOURCES/$(PACKAGE)-$(VERSION).tar.bz2 install: python setup.py install --root=$(DESTDIR) rpm: bz2 rpmdirs rpmbuild -ba --define "_topdir $(PWD)/rpm" rpm/SPECS/$(PACKAGE).spec bz2dev: rpmdirs @mkdir -p /tmp/$(PACKAGE)-$(VERSION) @tar cf - `cat MANIFEST` | (cd /tmp/$(PACKAGE)-$(VERSION) ; tar xf -) @(cd /tmp; tar cf - $(PACKAGE)-$(VERSION)) | bzip2 -9 > rpm/SOURCES/$(PACKAGE)-$(VERSION).tar.bz2 rpmdev: bz2dev rpmdirs rpmbuild -ba --define "_topdir $(PWD)/rpm" rpm/SPECS/$(PACKAGE).spec python-schedutils-0.6/README000066400000000000000000000001041320476675600157400ustar00rootroot00000000000000Report bugs and send patches to python-schedutils-0.6/pchrt000077500000000000000000000110131320476675600161270ustar00rootroot00000000000000#! /usr/bin/python # -*- python -*- # -*- coding: utf-8 -*- # Copyright (C) 2008 Red Hat Inc. # # Arnaldo Carvalho de Melo # # This application 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; version 2. # # This application 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. from __future__ import print_function import os import schedutils import sys def usage(): print('''pchrt (python-schedutils) usage: pchrt [options] [prio] [pid | cmd [args...]] manipulate real-time attributes of a process -b, --batch set policy to SCHED_BATCH -f, --fifo set policy to SCHED_FIFO -i, --idle set policy to SCHED_IDLE -p, --pid operate on existing given pid -m, --max show min and max valid priorities -o, --other set policy to SCHED_OTHER -r, --rr set policy to SCHED_RR (default) -R, --reset-on-fork set SCHED_RESET_ON_FORK for FIFO or RR -h, --help display this help You must give a priority if changing policy. Report bugs and send patches to ''') return def show_priority_limits(policy): print("%-32.32s: %d/%d" % ( "%s min/max priority" % schedutils.schedstr(policy), schedutils.get_priority_min(policy), schedutils.get_priority_max(policy) )) def show_all_priority_limits(): for policy in (schedutils.SCHED_OTHER, schedutils.SCHED_FIFO, schedutils.SCHED_RR, schedutils.SCHED_BATCH): show_priority_limits(policy) def show_settings(pid): policy = schedutils.get_scheduler(pid) spolicy = schedutils.schedstr(policy) rtprio = schedutils.get_priority(pid) reset_on_fork = "" if policy & schedutils.SCHED_RESET_ON_FORK: reset_on_fork = "|SCHED_RESET_ON_FORK" print('''pid %d's current scheduling policy: %s%s pid %d's current scheduling priority: %d''' % (pid, spolicy, reset_on_fork, pid, rtprio)) def valid_policy_flag(policy, policy_flag): if policy_flag == schedutils.SCHED_RESET_ON_FORK and \ policy not in (schedutils.SCHED_RR, schedutils.SCHED_FIFO): print("SCHED_RESET_ON_FORK flag is supported for SCHED_FIFO and SCHED_RR policies only") return False return True def change_settings(pid, policy, policy_flag, rtprio): try: schedutils.set_scheduler(pid, policy | policy_flag, rtprio) except SystemError as err: print("sched_setscheduler: %s" % err[1]) print("failed to set pid %d's policy" % pid) def main(): args = sys.argv[1:] if not args: usage() return policy = schedutils.SCHED_RR policy_flag = 0 while True: o = args.pop(0) try: priority = int(o) break except: pass if o in ("-h", "--help"): usage() return elif o in ("-b", "--batch"): policy = schedutils.SCHED_BATCH elif o in ("-f", "--fifo"): policy = schedutils.SCHED_FIFO elif o in ("-i", "--idle"): policy = schedutils.SCHED_IDLE elif o in ("-m", "--max"): show_all_priority_limits() return elif o in ("-o", "--other"): policy = schedutils.SCHED_OTHER elif o in ("-r", "--rr"): policy = schedutils.SCHED_RR elif o in ("-R", "--reset-on-fork"): policy_flag |= schedutils.SCHED_RESET_ON_FORK elif o in ("-p", "--pid"): if len(args) > 1: priority = int(args.pop(0)) pid = int(args.pop(0)) if not valid_policy_flag(policy, policy_flag): return change_settings(pid, policy, policy_flag, priority) else: pid = int(args.pop(0)) show_settings(pid) return else: usage() return if not valid_policy_flag(policy, policy_flag): return schedutils.set_scheduler(0, policy | policy_flag, priority) os.execvp(args[0], args) if __name__ == '__main__': main() python-schedutils-0.6/pchrt.1000066400000000000000000000020221320476675600162630ustar00rootroot00000000000000.\" Hey, EMACS: -*- nroff -*- .TH PCHRT 1 "May 10 2016" .SH NAME .B pchrt (python\-schedutils) \- manipulate the real-time attributes of a process .SH SYNOPSIS pchrt [options] [prio] [pid | cmd [args...]] .SH OPTIONS .TP .B \-b, \-\-batch set policy to SCHED_BATCH .TP .B \-f, \-\-fifo set policy to SCHED_FIFO .TP .B \-i, \-\-idle set policy to SCHED_IDLE .TP .B \-p, \-\-pid operate on existing given pid .TP .B \-m, \-\-max show min and max valid priorities .TP .B \-o, \-\-other set policy to SCHED_OTHER .TP .B \-r, \-\-rr set policy to SCHED_RR (default) .TP .B \-R, \-\-reset-on-fork set SCHED_RESET_ON_FORK for FIFO or RR .TP .B \-h, \-\-help display help .TP .B Note: You must give a priority if changing policy. .SH SEE ALSO .BR chrt (1) .SH AUTHOR pchrt was written by Arnaldo Carvalho de Melo .br as part of python\-schedutils .PP This manual page was written by John Kacur .PP Report bugs and send patches to python-schedutils-0.6/ptaskset000077500000000000000000000107321320476675600166540ustar00rootroot00000000000000#! /usr/bin/python # -*- python -*- # -*- coding: utf-8 -*- # Copyright (C) 2008 Red Hat Inc. # # Arnaldo Carvalho de Melo # # This application 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; version 2. # # This application 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. from __future__ import print_function import os import schedutils import sys def usage(): print('''ptaskset (python-schedutils) usage: ptaskset [options] [mask | cpu-list] [pid | cmd [args...]] set or get the affinity of a process -p, --pid operate on existing given pid -c, --cpu-list display and specify cpus in list format -h, --help display this help''') return def hexbitmask(l): hexbitmask = [] bit = 0 mask = 0 nr_entries = 1 << max(l) for entry in range(nr_entries): if entry in l: mask |= (1 << bit) bit += 1 if bit == 32: bit = 0 hexbitmask.insert(0, mask) mask = 0 if bit < 32 and mask != 0: hexbitmask.insert(0, mask) return hexbitmask def find_last_bit(n, wordsize=32): bit = wordsize - 1 while bit != 0: if n & (1 << bit): return bit bit -= 1 return 0 def bitmasklist(line): fields = line.strip().split(",") bitmasklist = [] while int(fields[0], 16) == 0: fields.pop(0) if not fields: return [] nr_entries = (len(fields) - 1) * 32 + find_last_bit(int(fields[0], 16)) + 1 entry = 0 for i in range(len(fields) - 1, -1, -1): mask = int(fields[i], 16) while mask != 0: if mask & 1: bitmasklist.append(entry) mask >>= 1 entry += 1 if entry == nr_entries: break if entry == nr_entries: break return bitmasklist def cpustring_to_list(cpustr): """Convert a string of numbers to an integer list. Given a string of comma-separated numbers and number ranges, return a simple sorted list of the integers it represents. This function will throw exceptions for badly-formatted strings. Returns a list of integers.""" fields = cpustr.strip().split(",") cpu_list = [] for field in fields: ends = field.split("-") if len(ends) > 2: raise "Syntax error" if len(ends) == 2: cpu_list += list(range(int(ends[0]), int(ends[1]) + 1)) else: cpu_list += [int(ends[0])] return list(set(cpu_list)) def show_settings(pid, when, cpu_list_mode): affinity = schedutils.get_affinity(pid) if cpu_list_mode: mask = ",".join([str(a) for a in affinity]) else: mask = ",".join(["%x" % a for a in hexbitmask(affinity)]) print("pid %d's %s affinity mask: %s" % (pid, when, mask)) def change_settings(pid, affinity, cpu_list_mode): if cpu_list_mode: try: affinity = [int(a) for a in affinity.split(",")] except: affinity = cpustring_to_list(affinity) else: affinity = bitmasklist(affinity) try: schedutils.set_affinity(pid, affinity) except SystemError as err: print("sched_setaffinity: %s" % err[1]) print("failed to set pid %d's affinity" % pid) def main(): args = sys.argv[1:] if not args: usage() return cpu_list_mode = False while True: o = args.pop(0) if o in ("-h", "--help"): usage() return elif o in ("-c", "--cpu-list"): cpu_list_mode = True elif o in ("-p", "--pid"): if len(args) > 1: affinity = args.pop(0) pid = int(args.pop(0)) show_settings(pid, "current", cpu_list_mode) change_settings(pid, affinity, cpu_list_mode) show_settings(pid, "new", cpu_list_mode) else: pid = int(args.pop(0)) show_settings(pid, "current", cpu_list_mode) return else: break affinity = o change_settings(0, affinity, cpu_list_mode) os.execvp(args[0], args) if __name__ == '__main__': main() python-schedutils-0.6/ptaskset.1000066400000000000000000000012651320476675600170110ustar00rootroot00000000000000.\" Hey, EMACS: -*- nroff -*- .TH PTASKSET 1 "May 10 2016" .SH NAME .B ptaskset (python\-schedutils) \- set or get the affinity of a process .SH SYNOPSIS ptaskset [options] [mask | cpu\-list] [pid | cmd [args...]] .SH OPTIONS .TP .B \-p, \-\-pid operate on existing given pid .TP .B \-c, \-\-cpu\-list display and specify cpus in list format .TP .B \-h, \-\-help display help .SH SEE ALSO .BR taskset (1) .SH AUTHOR ptaskset was written by Arnaldo Carvalho de Melo .br as part of python\-schedutils .PP This manual page was written by John Kacur .PP Report bugs and send patches to python-schedutils-0.6/python-schedutils/000077500000000000000000000000001320476675600205535ustar00rootroot00000000000000python-schedutils-0.6/python-schedutils/py3compat.h000066400000000000000000000020561320476675600226460ustar00rootroot00000000000000/* Python 3 compatibility macros Copyright (C) Petr Viktorin 2015 */ #include #if PY_MAJOR_VERSION >= 3 /***** Python 3 *****/ #define IS_PY3 1 /* Ints */ #define PyInt_AsLong PyLong_AsLong /* Strings */ #define PyStr_FromString PyUnicode_FromString /* Module init */ #define MODULE_INIT_FUNC(name) \ PyMODINIT_FUNC PyInit_ ## name(void); \ PyMODINIT_FUNC PyInit_ ## name(void) #else /***** Python 2 *****/ #define IS_PY3 0 /* Strings */ #define PyStr_FromString PyString_FromString /* Module init */ #define PyModuleDef_HEAD_INIT 0 typedef struct PyModuleDef { int m_base; const char* m_name; const char* m_doc; Py_ssize_t m_size; PyMethodDef *m_methods; } PyModuleDef; #define PyModule_Create(def) \ Py_InitModule3((def)->m_name, (def)->m_methods, (def)->m_doc) #define MODULE_INIT_FUNC(name) \ static PyObject *PyInit_ ## name(void); \ void init ## name(void); \ void init ## name(void) { PyInit_ ## name(); } \ static PyObject *PyInit_ ## name(void) #endif python-schedutils-0.6/python-schedutils/schedutils.c000066400000000000000000000242501320476675600230710ustar00rootroot00000000000000#include #include "py3compat.h" #include #include #include #ifndef __unused #define __unused __attribute__ ((unused)) #endif #ifndef CPU_ALLOC /* From glibc-headers-2.12-1.7.el6.x86_64 */ /* Basic access functions. */ #define __CPUELT(cpu) ((cpu) / __NCPUBITS) #define __CPUMASK(cpu) ((__cpu_mask) 1 << ((cpu) % __NCPUBITS)) #define CPU_ALLOC_SIZE(ncpus) \ ((((ncpus) + __NCPUBITS - 1) / __NCPUBITS) * sizeof (__cpu_mask)) /* Access functions for CPU masks. */ # if __GNUC_PREREQ (2, 91) # define __CPU_ZERO_S(setsize, cpusetp) \ do __builtin_memset (cpusetp, '\0', setsize); while (0) # else # define __CPU_ZERO_S(setsize, cpusetp) \ do { \ size_t __i; \ size_t __imax = (setsize) / sizeof (__cpu_mask); \ __cpu_mask *__bits = (cpusetp)->__bits; \ for (__i = 0; __i < __imax; ++__i) \ __bits[__i] = 0; \ } while (0) # endif #define CPU_FREE(cpus) free(cpus) #define CPU_ALLOC(ncpus) malloc(CPU_ALLOC_SIZE(ncpus)) # define __CPU_SET_S(cpu, setsize, cpusetp) \ (__extension__ \ ({ size_t __cpu = (cpu); \ __cpu < 8 * (setsize) \ ? (((__cpu_mask *) ((cpusetp)->__bits))[__CPUELT (__cpu)] \ |= __CPUMASK (__cpu)) \ : 0; })) # define __CPU_ISSET_S(cpu, setsize, cpusetp) \ (__extension__ \ ({ size_t __cpu = (cpu); \ __cpu < 8 * (setsize) \ ? ((((__const __cpu_mask *) ((cpusetp)->__bits))[__CPUELT (__cpu)] \ & __CPUMASK (__cpu))) != 0 \ : 0; })) #define CPU_SET_S(cpu, setsize, cpusetp) __CPU_SET_S (cpu, setsize, cpusetp) #define CPU_ISSET_S(cpu, setsize, cpusetp) __CPU_ISSET_S (cpu, setsize, cpusetp) #define CPU_ZERO_S(setsize, cpusetp) __CPU_ZERO_S (setsize, cpusetp) #endif /* CPU_ALLOC */ #ifndef SCHED_RESET_ON_FORK #define SCHED_RESET_ON_FORK 0x40000000 #endif /* * The following bitmask declarations, bitmask_*() routines, and associated * _setbit() and _getbit() routines are: * Copyright (c) 2004 Silicon Graphics, Inc. (SGI) All rights reserved. * SGI publishes it under the terms of the GNU General Public License, v2, * as published by the Free Software Foundation. */ #define howmany(x,y) (((x)+((y)-1))/(y)) #define bitsperlong (8 * sizeof(unsigned long)) #define longsperbits(n) howmany(n, bitsperlong) #define bytesperbits(x) ((x+7)/8) /* * Number of bits in a CPU bitmask on current system */ static int __get_max_number_of_cpus(void) { int n; int cpus = 2048; for (;;) { unsigned long buffer[longsperbits(cpus)]; memset(buffer, 0, sizeof(buffer)); /* the library version does not return size of cpumask_t */ n = syscall(SYS_sched_getaffinity, 0, bytesperbits(cpus), &buffer); if (n < 0 && errno == EINVAL && cpus < 1024 * 1024) { cpus *= 2; continue; } return n * 8; } return -1; } static PyObject *get_max_number_of_cpus(PyObject *self __unused, PyObject *args __unused) { int ret = __get_max_number_of_cpus(); if (ret < 0) return PyErr_SetFromErrno(PyExc_OSError); return Py_BuildValue("i", ret); } static PyObject *get_affinity(PyObject *self __unused, PyObject *args) { PyObject *list = NULL; cpu_set_t *cpus; int pid, cpu; size_t cpusetsize; int max_cpus; if (!PyArg_ParseTuple(args, "i", &pid)) goto out_error; max_cpus = __get_max_number_of_cpus(); if (max_cpus < 0) goto out_error; cpus = CPU_ALLOC(max_cpus); if (cpus == NULL) return PyErr_NoMemory(); cpusetsize = CPU_ALLOC_SIZE(max_cpus); CPU_ZERO_S(cpusetsize, cpus); if (sched_getaffinity(pid, cpusetsize, cpus) < 0) goto out_free; list = PyList_New(0); for (cpu = 0; cpu < max_cpus; ++cpu) if (CPU_ISSET_S(cpu, cpusetsize, cpus)) PyList_Append(list, Py_BuildValue("i", cpu)); CPU_FREE(cpus); return list; out_free: CPU_FREE(cpus); out_error: return PyErr_SetFromErrno(PyExc_OSError); } static PyObject *set_affinity(PyObject *self __unused, PyObject *args) { int pid, nr_elements, i, max_cpus; cpu_set_t *cpus; PyObject *list; size_t cpusetsize; if (!PyArg_ParseTuple(args, "iO", &pid, &list)) goto out_error; max_cpus = __get_max_number_of_cpus(); if (max_cpus < 0) goto out_error; cpus = CPU_ALLOC(max_cpus); if (cpus == NULL) return PyErr_NoMemory(); cpusetsize = CPU_ALLOC_SIZE(max_cpus); CPU_ZERO_S(cpusetsize, cpus); nr_elements = PyList_Size(list); for (i = 0; i < nr_elements; ++i) { int cpu = PyInt_AsLong(PyList_GetItem(list, i)); if (cpu >= max_cpus) { PyErr_SetString(PyExc_OSError, "Invalid CPU"); CPU_FREE(cpus); return NULL; } CPU_SET_S(cpu, cpusetsize, cpus); } i = sched_setaffinity(pid, cpusetsize, cpus); CPU_FREE(cpus); if (i < 0) return PyErr_SetFromErrno(PyExc_OSError); Py_INCREF(Py_None); return Py_None; out_error: return PyErr_SetFromErrno(PyExc_OSError); } static PyObject *get_scheduler(PyObject *self __unused, PyObject *args) { int pid, scheduler; if (!PyArg_ParseTuple(args, "i", &pid)) return NULL; scheduler = sched_getscheduler(pid); if (scheduler < 0) return PyErr_SetFromErrno(PyExc_OSError); return Py_BuildValue("i", scheduler); } static PyObject *set_scheduler(PyObject *self __unused, PyObject *args) { int pid, policy, priority; struct sched_param param; if (!PyArg_ParseTuple(args, "iii", &pid, &policy, &priority)) return NULL; memset(¶m, 0, sizeof(param)); param.sched_priority = priority; if (sched_setscheduler(pid, policy, ¶m) < 0) return PyErr_SetFromErrno(PyExc_OSError); Py_RETURN_NONE; } static PyObject *get_priority(PyObject *self __unused, PyObject *args) { int pid; struct sched_param param = { .sched_priority = -1, }; if (!PyArg_ParseTuple(args, "i", &pid)) return NULL; if (sched_getparam(pid, ¶m) != 0) return PyErr_SetFromErrno(PyExc_OSError); return Py_BuildValue("i", param.sched_priority); } #ifndef SCHED_BATCH #define SCHED_BATCH 3 #endif #ifndef SCHED_IDLE #define SCHED_IDLE 5 #endif #ifndef SCHED_DEADLINE #define SCHED_DEADLINE 6 #endif static PyObject *schedstr(PyObject *self __unused, PyObject *args) { int scheduler; char *s; if (!PyArg_ParseTuple(args, "i", &scheduler)) return NULL; switch (scheduler & ~SCHED_RESET_ON_FORK) { case SCHED_OTHER: s = "SCHED_OTHER"; break; case SCHED_RR: s = "SCHED_RR"; break; case SCHED_FIFO: s = "SCHED_FIFO"; break; case SCHED_BATCH: s = "SCHED_BATCH"; break; case SCHED_IDLE: s = "SCHED_IDLE"; break; case SCHED_DEADLINE: s = "SCHED_DEADLINE"; break; default: s = "UNKNOWN"; break; } return PyStr_FromString(s); } static PyObject *schedfromstr(PyObject *self __unused, PyObject *args) { int scheduler; char *s; if (!PyArg_ParseTuple(args, "s", &s)) return NULL; if (strcmp(s, "SCHED_OTHER") == 0) scheduler = SCHED_OTHER; else if (strcmp(s, "SCHED_RR") == 0) scheduler = SCHED_RR; else if (strcmp(s, "SCHED_FIFO") == 0) scheduler = SCHED_FIFO; else if (strcmp(s, "SCHED_BATCH") == 0) scheduler = SCHED_BATCH; else if (strcmp(s, "SCHED_IDLE") == 0) scheduler = SCHED_IDLE; else if (strcmp(s, "SCHED_DEADLINE") == 0) scheduler = SCHED_DEADLINE; else { PyErr_SetString(PyExc_OSError, "Unknown scheduler"); return NULL; } return Py_BuildValue("i", scheduler); } static PyObject *get_priority_min(PyObject *self __unused, PyObject *args) { int policy, min; if (!PyArg_ParseTuple(args, "i", &policy)) return NULL; min = sched_get_priority_min(policy); if (min < 0) return PyErr_SetFromErrno(PyExc_OSError); return Py_BuildValue("i", min); } static PyObject *get_priority_max(PyObject *self __unused, PyObject *args) { int policy, max; if (!PyArg_ParseTuple(args, "i", &policy)) return NULL; max = sched_get_priority_max(policy); if (max < 0) return PyErr_SetFromErrno(PyExc_OSError); return Py_BuildValue("i", max); } static struct PyMethodDef PySchedutilsModuleMethods[] = { { .ml_name = "get_affinity", .ml_meth = (PyCFunction)get_affinity, .ml_flags = METH_VARARGS, }, { .ml_name = "set_affinity", .ml_meth = (PyCFunction)set_affinity, .ml_flags = METH_VARARGS, }, { .ml_name = "get_scheduler", .ml_meth = (PyCFunction)get_scheduler, .ml_flags = METH_VARARGS, }, { .ml_name = "set_scheduler", .ml_meth = (PyCFunction)set_scheduler, .ml_flags = METH_VARARGS, }, { .ml_name = "get_priority", .ml_meth = (PyCFunction)get_priority, .ml_flags = METH_VARARGS, }, { .ml_name = "schedstr", .ml_meth = (PyCFunction)schedstr, .ml_flags = METH_VARARGS, }, { .ml_name = "schedfromstr", .ml_meth = (PyCFunction)schedfromstr, .ml_flags = METH_VARARGS, }, { .ml_name = "get_priority_min", .ml_meth = (PyCFunction)get_priority_min, .ml_flags = METH_VARARGS, }, { .ml_name = "get_priority_max", .ml_meth = (PyCFunction)get_priority_max, .ml_flags = METH_VARARGS, }, { .ml_name = "get_max_number_of_cpus", .ml_meth = (PyCFunction)get_max_number_of_cpus, .ml_flags = METH_NOARGS, }, { .ml_name = NULL, }, }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, .m_name = "schedutils", .m_doc = NULL, .m_size = -1, .m_methods = PySchedutilsModuleMethods, }; MODULE_INIT_FUNC(schedutils) { PyObject *m = PyModule_Create(&moduledef); if (m == NULL) return NULL; PyModule_AddIntConstant(m, "SCHED_OTHER", SCHED_OTHER); PyModule_AddIntConstant(m, "SCHED_FIFO", SCHED_FIFO); PyModule_AddIntConstant(m, "SCHED_RR", SCHED_RR); PyModule_AddIntConstant(m, "SCHED_BATCH", SCHED_BATCH); PyModule_AddIntConstant(m, "SCHED_IDLE", SCHED_IDLE); PyModule_AddIntConstant(m, "SCHED_DEADLINE", SCHED_DEADLINE); PyModule_AddIntConstant(m, "SCHED_RESET_ON_FORK", SCHED_RESET_ON_FORK); return m; } python-schedutils-0.6/rpm/000077500000000000000000000000001320476675600156635ustar00rootroot00000000000000python-schedutils-0.6/rpm/SPECS/000077500000000000000000000000001320476675600165405ustar00rootroot00000000000000python-schedutils-0.6/rpm/SPECS/python-schedutils.spec000066400000000000000000000060431320476675600231050ustar00rootroot00000000000000%if 0%{?fedora} %global with_python3 1 %else %global without_python3 1 %endif Summary: Linux scheduler python bindings Name: python-schedutils Version: 0.6 Release: 1%{?dist} License: GPLv2 URL: https://rt.wiki.kernel.org/index.php/Tuna Source: https://cdn.kernel.org/pub/software/libs/python/%{name}/%{name}-%{version}.tar.xz Group: System Environment/Libraries BuildRequires: python2-devel %if 0%{?with_python3} BuildRequires: python3-devel %endif BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n) %global _description\ Python interface for the Linux scheduler sched_{get,set}{affinity,scheduler} functions and friends. %description %_description %package -n python2-schedutils Summary: %summary %{?python_provide:%python_provide python2-schedutils} %description -n python2-schedutils %_description %if 0%{?with_python3} %package -n python3-schedutils Summary: %summary %{?python_provide:%python_provide python3-schedutils} %description -n python3-schedutils %_description %endif %prep %autosetup -p1 %build %py2_build %if 0%{?with_python3} %py3_build %endif %install rm -rf %{buildroot} %py2_install %if 0%{?with_python3} %py3_install %endif %clean rm -rf %{buildroot} %files -n python2-schedutils %defattr(-,root,root) %license COPYING %{python2_sitearch}/schedutils.so %license COPYING %if 0%{?without_python3} %{_bindir}/pchrt %{_bindir}/ptaskset %{_mandir}/man1/pchrt.1* %{_mandir}/man1/ptaskset.1* %endif %{python2_sitearch}/*.egg-info %if 0%{?with_python3} %files -n python3-schedutils %defattr(-,root,root) %license COPYING %{_bindir}/pchrt %{_bindir}/ptaskset %{_mandir}/man1/pchrt.1* %{_mandir}/man1/ptaskset.1* %{python3_sitearch}/schedutils*.so %{python3_sitearch}/*.egg-info %endif %changelog * Mon Nov 20 2017 Jiri Kastner - 0.6-1 - added python 3 support * Thu Dec 22 2016 Jiri Kastner - 0.5-1 - added basic support for SCHED_DEADLINE - fixed URL and Source in specfile * Tue May 10 2016 John Kacur - 0.4-2 - Add man pages for pchrt and ptaskset - Fix and update usage messages for pchrt and ptaskset * Mon Aug 1 2011 Arnaldo Carvalho de Melo - 0.4-1 - New upstream release. * Tue May 17 2011 Clark Williams - 0.3-1 - reworked get_affinity() and set_affinity() to use dynamic CPU_* macros * Thu Aug 28 2008 Arnaldo Carvalho de Melo - 0.2-2 - Fix build and install sections as suggested by the fedora rewiewer (BZ #460387) * Wed Aug 27 2008 Arnaldo Carvalho de Melo - 0.2-1 - Add get_priority_{min,max} methods - Add constants for SCHED_{BATCH,FIFO,OTHER,RR} - Implement get_priority method - Add pchrt utility for testing the bindings, chrt clone - Add ptaskset utility for testing the bindings, taskset clone * Tue Jun 10 2008 Arnaldo Carvalho de Melo - 0.1-3 - add dist to the release tag * Wed Dec 19 2007 Arnaldo Carvalho de Melo - 0.1-2 - First build into rhel5-rt * Wed Dec 19 2007 Arnaldo Carvalho de Melo - 0.1-1 - Initial package python-schedutils-0.6/setup.py000066400000000000000000000011261320476675600165770ustar00rootroot00000000000000#!/usr/bin/python2 from distutils.core import setup, Extension schedutils = Extension('schedutils', sources = ['python-schedutils/schedutils.c']) # don't reformat this line, Makefile parses it setup(name='schedutils', version='0.6', description='Python module to interface with the Linux scheduler', author='Arnaldo Carvalho de Melo', author_email='acme@redhat.com', url='http://fedoraproject.org/wiki/python-schedutils', scripts=['pchrt', 'ptaskset'], data_files=[('share/man/man1', ['pchrt.1','ptaskset.1'])], ext_modules=[schedutils])