From 84d38353f54ed99bcf043bd5c1b2b906e7f22b26 Mon Sep 17 00:00:00 2001 From: rpm-build Date: Aug 05 2020 15:41:30 +0000 Subject: python-pid-2.1.1 base --- diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..64388d3 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,3 @@ + * trbs http://github.com/trbs/ + * nnathan http://github.com/nnathan/ + diff --git a/CHANGELOG b/CHANGELOG new file mode 100644 index 0000000..c38fb93 --- /dev/null +++ b/CHANGELOG @@ -0,0 +1,113 @@ +Changelog +========= + +2.1.1 +----- + + - Add Python 3.5 to travis + +2.1.0 +----- + + - Same pid support, multiple calls to the same process won't + file when allow_samepid=True is set. + +2.0.1 +----- + + - Bundle AUTHOR, CHANGELOG and LICENSE with source distribution + +2.0.0 +----- + + - PidFile will now look at the environment variables it + needs just before acquiring the lock instead of at + instantiation time of the PidFile class. + + - pid is now friendly with daemon context managers such + as python-daemon where the PidFile context manager is + passed as a parameter. + + - The signal handler on SIGTERM is now only installed + automatically if there is no previous signal handler + installed. + + - You can install a custom SIGTERM handler by specifying + a callable for 'register_term_signal_handler'. + + - All in all we tried to make sure that with version 2.0.0 + pid will play nice with other code and has sane defaults. + + - Many thanks to nnathan who's efforts coding and testing + made this version possible. + + +1.1.0 +----- + + - Add pypy to classifiers and travis + + +1.0.9 +----- + + - Wrong documentation on how to call the decorator + - Allow to set default pid dir at runtime. + - Make sure pid files are nor prematurely removed. + + +1.0.8 +----- + + - disable gid test for now + + +1.0.7 +----- + + - update title in setup.py + + +1.0.6 +----- + + - more unit tests + + +1.0.5 +----- + + - fix flake8 errors + + +1.0.4 +----- + + - fix flake8 errors + - add pid/decorator.py + +1.0.3 +----- + + - add coveralls badge to README + - add travis badge to README + - set rights on /var/run in travis + + +1.0.2 +----- + + - use DESCRIPTION as README + + +1.0.1 +----- + + - Add force tempdir + - Add travis + + +1.0.0 +----- + + - Initial commit diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..040d9dc --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014 Trbs + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..92cd89d --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,3 @@ +include AUTHORS +include CHANGELOG +include LICENSE diff --git a/PKG-INFO b/PKG-INFO new file mode 100644 index 0000000..7c218e8 --- /dev/null +++ b/PKG-INFO @@ -0,0 +1,106 @@ +Metadata-Version: 1.1 +Name: pid +Version: 2.1.1 +Summary: Pidfile featuring stale detection and file-locking, can also be used as context-manager or decorator +Home-page: https://github.com/trbs/pid/ +Author: Trbs +Author-email: trbs@trbs.net +License: ASL +Description: pid + === + + .. image:: https://travis-ci.org/trbs/pid.svg?branch=master + :target: https://travis-ci.org/trbs/pid + + .. image:: https://coveralls.io/repos/trbs/pid/badge.png + :target: https://coveralls.io/r/trbs/pid + + .. image:: https://pypip.in/v/pid/badge.png + :target: https://pypi.python.org/pypi/pid/ + :alt: Latest PyPI version + + .. image:: https://pypip.in/d/pid/badge.png + :target: https://pypi.python.org/pypi/pid/ + :alt: Number of PyPI downloads + + PidFile class featuring: + + - stale detection + - pidfile locking (fcntl) + - chmod (default is 0o644) + - chown + - custom exceptions + + Context Manager + --------------- + + PidFile can be used as a context manager:: + + from pid import PidFile + + with PidFile(): + do_something() + + + Decorator + --------- + + PidFile can also be used a a decorator:: + + from pid.decorator import pidfile + + @pidfile() + def main(): + pass + + if __name__ == "__main__": + main() + + + Exception Order + --------------- + + In default mode PidFile will try to acquire a file lock before anything else. + This means that normally you get a PidFileAlreadyLockedError instead of the + PidFileAlreadyRunningError when running a program twice. + + If you just want to know if a program is already running its easiest to catch + just PidFileError since it will capture all possible PidFile exceptions. + + Behaviour + --------- + + Changes in version 2.0.0 and going forward: + + * pid is now friendly with daemon context managers such as + `python-daemon `_ where + the PidFile context manager is passed as a parameter. The + new corrected behaviour will ensure the process environment is + determinde at the time of acquiring/checking the lock. Prior + behaviour would determine the process environment when + instancing the class which may result in incorrect determination + of the PID in the case of a process forking after instancing + PidFile. + + \ + + * Cleanup of pidfile on termination is done using `atexit` module. + The default SIGTERM handler doesn't cleanly exit and therefore + the atexit registered functions will not execute. A custom + handler which triggers the atexit registered functions for cleanup + will override the default SIGTERM handler. If a prior signal handler + has been configured, then it will not be overridden. + +Keywords: pid pidfile context manager decorator +Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.6 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: Implementation :: PyPy diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..7e2d05f --- /dev/null +++ b/README.rst @@ -0,0 +1,84 @@ +pid +=== + +.. image:: https://travis-ci.org/trbs/pid.svg?branch=master + :target: https://travis-ci.org/trbs/pid + +.. image:: https://coveralls.io/repos/trbs/pid/badge.png + :target: https://coveralls.io/r/trbs/pid + +.. image:: https://pypip.in/v/pid/badge.png + :target: https://pypi.python.org/pypi/pid/ + :alt: Latest PyPI version + +.. image:: https://pypip.in/d/pid/badge.png + :target: https://pypi.python.org/pypi/pid/ + :alt: Number of PyPI downloads + +PidFile class featuring: + + - stale detection + - pidfile locking (fcntl) + - chmod (default is 0o644) + - chown + - custom exceptions + +Context Manager +--------------- + +PidFile can be used as a context manager:: + + from pid import PidFile + + with PidFile(): + do_something() + + +Decorator +--------- + +PidFile can also be used a a decorator:: + + from pid.decorator import pidfile + + @pidfile() + def main(): + pass + + if __name__ == "__main__": + main() + + +Exception Order +--------------- + +In default mode PidFile will try to acquire a file lock before anything else. +This means that normally you get a PidFileAlreadyLockedError instead of the +PidFileAlreadyRunningError when running a program twice. + +If you just want to know if a program is already running its easiest to catch +just PidFileError since it will capture all possible PidFile exceptions. + +Behaviour +--------- + +Changes in version 2.0.0 and going forward: + +* pid is now friendly with daemon context managers such as + `python-daemon `_ where + the PidFile context manager is passed as a parameter. The + new corrected behaviour will ensure the process environment is + determinde at the time of acquiring/checking the lock. Prior + behaviour would determine the process environment when + instancing the class which may result in incorrect determination + of the PID in the case of a process forking after instancing + PidFile. + +\ + +* Cleanup of pidfile on termination is done using `atexit` module. + The default SIGTERM handler doesn't cleanly exit and therefore + the atexit registered functions will not execute. A custom + handler which triggers the atexit registered functions for cleanup + will override the default SIGTERM handler. If a prior signal handler + has been configured, then it will not be overridden. diff --git a/pid.egg-info/PKG-INFO b/pid.egg-info/PKG-INFO new file mode 100644 index 0000000..7c218e8 --- /dev/null +++ b/pid.egg-info/PKG-INFO @@ -0,0 +1,106 @@ +Metadata-Version: 1.1 +Name: pid +Version: 2.1.1 +Summary: Pidfile featuring stale detection and file-locking, can also be used as context-manager or decorator +Home-page: https://github.com/trbs/pid/ +Author: Trbs +Author-email: trbs@trbs.net +License: ASL +Description: pid + === + + .. image:: https://travis-ci.org/trbs/pid.svg?branch=master + :target: https://travis-ci.org/trbs/pid + + .. image:: https://coveralls.io/repos/trbs/pid/badge.png + :target: https://coveralls.io/r/trbs/pid + + .. image:: https://pypip.in/v/pid/badge.png + :target: https://pypi.python.org/pypi/pid/ + :alt: Latest PyPI version + + .. image:: https://pypip.in/d/pid/badge.png + :target: https://pypi.python.org/pypi/pid/ + :alt: Number of PyPI downloads + + PidFile class featuring: + + - stale detection + - pidfile locking (fcntl) + - chmod (default is 0o644) + - chown + - custom exceptions + + Context Manager + --------------- + + PidFile can be used as a context manager:: + + from pid import PidFile + + with PidFile(): + do_something() + + + Decorator + --------- + + PidFile can also be used a a decorator:: + + from pid.decorator import pidfile + + @pidfile() + def main(): + pass + + if __name__ == "__main__": + main() + + + Exception Order + --------------- + + In default mode PidFile will try to acquire a file lock before anything else. + This means that normally you get a PidFileAlreadyLockedError instead of the + PidFileAlreadyRunningError when running a program twice. + + If you just want to know if a program is already running its easiest to catch + just PidFileError since it will capture all possible PidFile exceptions. + + Behaviour + --------- + + Changes in version 2.0.0 and going forward: + + * pid is now friendly with daemon context managers such as + `python-daemon `_ where + the PidFile context manager is passed as a parameter. The + new corrected behaviour will ensure the process environment is + determinde at the time of acquiring/checking the lock. Prior + behaviour would determine the process environment when + instancing the class which may result in incorrect determination + of the PID in the case of a process forking after instancing + PidFile. + + \ + + * Cleanup of pidfile on termination is done using `atexit` module. + The default SIGTERM handler doesn't cleanly exit and therefore + the atexit registered functions will not execute. A custom + handler which triggers the atexit registered functions for cleanup + will override the default SIGTERM handler. If a prior signal handler + has been configured, then it will not be overridden. + +Keywords: pid pidfile context manager decorator +Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.6 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: Implementation :: PyPy diff --git a/pid.egg-info/SOURCES.txt b/pid.egg-info/SOURCES.txt new file mode 100644 index 0000000..416135a --- /dev/null +++ b/pid.egg-info/SOURCES.txt @@ -0,0 +1,14 @@ +AUTHORS +CHANGELOG +LICENSE +MANIFEST.in +README.rst +setup.cfg +setup.py +pid/__init__.py +pid/decorator.py +pid.egg-info/PKG-INFO +pid.egg-info/SOURCES.txt +pid.egg-info/dependency_links.txt +pid.egg-info/pbr.json +pid.egg-info/top_level.txt \ No newline at end of file diff --git a/pid.egg-info/dependency_links.txt b/pid.egg-info/dependency_links.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/pid.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/pid.egg-info/pbr.json b/pid.egg-info/pbr.json new file mode 100644 index 0000000..6a83874 --- /dev/null +++ b/pid.egg-info/pbr.json @@ -0,0 +1 @@ +{"is_release": false, "git_version": "a60e231"} \ No newline at end of file diff --git a/pid.egg-info/top_level.txt b/pid.egg-info/top_level.txt new file mode 100644 index 0000000..7fe681d --- /dev/null +++ b/pid.egg-info/top_level.txt @@ -0,0 +1 @@ +pid diff --git a/pid/__init__.py b/pid/__init__.py new file mode 100644 index 0000000..65d67f7 --- /dev/null +++ b/pid/__init__.py @@ -0,0 +1,210 @@ +import os +import sys +import errno +import fcntl +import atexit +import signal +import logging +import tempfile + + +__version__ = "2.1.1" + +DEFAULT_PID_DIR = "/var/run/" +PID_CHECK_EMPTY = "PID_CHECK_EMPTY" +PID_CHECK_NOFILE = "PID_CHECK_NOFILE" +PID_CHECK_SAMEPID = "PID_CHECK_SAMEPID" +PID_CHECK_NOTRUNNING = "PID_CHECK_NOTRUNNING" + + +class PidFileError(Exception): + pass + + +class PidFileUnreadableError(PidFileError): + pass + + +class PidFileAlreadyRunningError(PidFileError): + pass + + +class PidFileAlreadyLockedError(PidFileError): + pass + + +class PidFile(object): + __slots__ = ("pid", "pidname", "piddir", "enforce_dotpid_postfix", "register_term_signal_handler", + "filename", "fh", "lock_pidfile", "chmod", "uid", "gid", "force_tmpdir", + "allow_samepid", "_logger", "_is_setup") + + def __init__(self, pidname=None, piddir=None, enforce_dotpid_postfix=True, + register_term_signal_handler='auto', lock_pidfile=True, chmod=0o644, + uid=-1, gid=-1, force_tmpdir=False, allow_samepid=False): + self.pidname = pidname + self.piddir = piddir + self.enforce_dotpid_postfix = enforce_dotpid_postfix + self.register_term_signal_handler = register_term_signal_handler + self.lock_pidfile = lock_pidfile + self.chmod = chmod + self.uid = uid + self.gid = gid + self.force_tmpdir = force_tmpdir + self.allow_samepid = allow_samepid + + self.fh = None + self.filename = None + self.pid = None + + self._logger = None + self._is_setup = False + + @property + def logger(self): + if not self._logger: + self._logger = logging.getLogger("PidFile") + + return self._logger + + def setup(self): + if not self._is_setup: + self.logger.debug("%r entering setup", self) + if self.filename is None: + self.pid = os.getpid() + self.filename = self._make_filename() + self._register_term_signal() + + # setup should only be performed once + self._is_setup = True + + def _make_filename(self): + pidname = self.pidname + piddir = self.piddir + if pidname is None: + pidname = "%s.pid" % os.path.basename(sys.argv[0]) + if self.enforce_dotpid_postfix and not pidname.endswith(".pid"): + pidname = "%s.pid" % pidname + if piddir is None: + if os.path.isdir(DEFAULT_PID_DIR) and self.force_tmpdir is False: + piddir = DEFAULT_PID_DIR + else: + piddir = tempfile.gettempdir() + + if not os.path.isdir(piddir): + os.makedirs(piddir) + if not os.access(piddir, os.R_OK): + raise IOError("Pid file directory '%s' cannot be read" % piddir) + if not os.access(piddir, os.W_OK): + raise IOError("Pid file directory '%s' cannot be written to" % piddir) + + filename = os.path.abspath(os.path.join(piddir, pidname)) + return filename + + def _register_term_signal(self): + register_term_signal_handler = self.register_term_signal_handler + if register_term_signal_handler == 'auto': + if signal.getsignal(signal.SIGTERM) == signal.SIG_DFL: + register_term_signal_handler = True + else: + register_term_signal_handler = False + + if callable(register_term_signal_handler): + signal.signal(signal.SIGTERM, register_term_signal_handler) + elif register_term_signal_handler: + # Register TERM signal handler to make sure atexit runs on TERM signal + def sigterm_noop_handler(*args, **kwargs): + raise SystemExit(1) + + signal.signal(signal.SIGTERM, sigterm_noop_handler) + + def check(self): + def inner_check(fh): + try: + fh.seek(0) + pid_str = fh.read(16).split("\n", 1)[0].strip() + if not pid_str: + return PID_CHECK_EMPTY + pid = int(pid_str) + except (IOError, ValueError) as exc: + self.close(fh=fh) + raise PidFileUnreadableError(exc) + else: + if self.allow_samepid and self.pid == pid: + return PID_CHECK_SAMEPID + + try: + os.kill(pid, 0) + except OSError as exc: + if exc.errno == errno.ESRCH: + # this pid is not running + return PID_CHECK_NOTRUNNING + self.close(fh=fh, cleanup=False) + raise PidFileAlreadyRunningError(exc) + self.close(fh=fh, cleanup=False) + raise PidFileAlreadyRunningError("Program already running with pid: %d" % pid) + + self.setup() + + self.logger.debug("%r check pidfile: %s", self, self.filename) + + if self.fh is None: + if self.filename and os.path.isfile(self.filename): + with open(self.filename, "r") as fh: + return inner_check(fh) + return PID_CHECK_NOFILE + else: + return inner_check(self.fh) + + def create(self): + self.setup() + + self.logger.debug("%r create pidfile: %s", self, self.filename) + self.fh = open(self.filename, 'a+') + if self.lock_pidfile: + try: + fcntl.flock(self.fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except IOError as exc: + self.close(cleanup=False) + if self.allow_samepid: + return + raise PidFileAlreadyLockedError(exc) + + check_result = self.check() + if check_result == PID_CHECK_SAMEPID: + return + + if self.chmod: + os.fchmod(self.fh.fileno(), self.chmod) + if self.uid >= 0 or self.gid >= 0: + os.fchown(self.fh.fileno(), self.uid, self.gid) + self.fh.seek(0) + self.fh.truncate() + # pidfile must consist of the pid and a newline character + self.fh.write("%d\n" % self.pid) + self.fh.flush() + self.fh.seek(0) + atexit.register(self.close) + + def close(self, fh=None, cleanup=True): + self.logger.debug("%r closing pidfile: %s", self, self.filename) + + if not fh: + fh = self.fh + try: + if fh is None: + return + fh.close() + except IOError as exc: + # ignore error when file was already closed + if exc.errno != errno.EBADF: + raise + finally: + if self.filename and os.path.isfile(self.filename) and cleanup: + os.remove(self.filename) + + def __enter__(self): + self.create() + return self + + def __exit__(self, exc_type=None, exc_value=None, exc_tb=None): + self.close() diff --git a/pid/decorator.py b/pid/decorator.py new file mode 100644 index 0000000..99a0ae2 --- /dev/null +++ b/pid/decorator.py @@ -0,0 +1,16 @@ +import types +from functools import wraps +from . import PidFile + + +def pidfile(*pid_args, **pid_kwargs): + if len(pid_args) > 0: + assert not isinstance(pid_args[0], types.FunctionType), "pidfile decorator must be called with parentheses, like: @pidfile()" + + def wrapper(func): + @wraps(func) + def decorator(*func_args, **func_kwargs): + with PidFile(*pid_args, **pid_kwargs): + return func(*func_args, **func_kwargs) + return decorator + return wrapper diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..c0427e3 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,14 @@ +[bdist_wheel] +universal = 1 + +[pep8] +ignore = E501 + +[flake8] +ignore = E501 + +[egg_info] +tag_build = +tag_date = 0 +tag_svn_revision = 0 + diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..3f7c7cb --- /dev/null +++ b/setup.py @@ -0,0 +1,58 @@ +import os +import re +import codecs +from setuptools import setup + +here = os.path.abspath(os.path.dirname(__file__)) + + +# Read the version number from a source file. +# Why read it, and not import? +# see https://groups.google.com/d/topic/pypa-dev/0PkjVpcxTzQ/discussion +def find_version(*file_paths): + # Open in Latin-1 so that we avoid encoding errors. + # Use codecs.open for Python 2 compatibility + with codecs.open(os.path.join(here, *file_paths), 'r', 'latin1') as f: + version_file = f.read() + + # The version line must have the form + # __version__ = 'ver' + version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", + version_file, re.M) + if version_match: + return version_match.group(1) + raise RuntimeError("Unable to find version string.") + + +# Get the long description from the relevant file +with codecs.open('README.rst', encoding='utf-8') as f: + long_description = f.read() + +setup( + name="pid", + version=find_version('pid/__init__.py'), + description="Pidfile featuring stale detection and file-locking, can also be used as context-manager or decorator", + long_description=long_description, + url='https://github.com/trbs/pid/', + author='Trbs', + author_email='trbs@trbs.net', + license='ASL', + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Apache Software License', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.6', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: Implementation :: PyPy', + ], + keywords='pid pidfile context manager decorator', + packages=["pid"], + install_requires=[], + test_suite='nose.collector', + setup_requires=['nose>=1.0'], +)