├── .gitignore ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── daemonize.py ├── docs ├── conf.py └── index.rst ├── setup.cfg ├── setup.py └── tests ├── daemon_chdir.py ├── daemon_keep_fds.py ├── daemon_privileged_action.py ├── daemon_sigterm.py ├── daemon_uid_gid.py ├── daemon_uid_gid_action.py └── test.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .ropeproject 3 | __pycache__ 4 | docs/_build 5 | build 6 | daemonize.egg-info 7 | dist 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.6" 4 | - "2.7" 5 | - "3.3" 6 | - "3.4" 7 | - "3.5" 8 | install: sudo pip install nose sphinx sphinx_rtd_theme; sudo pip install . 9 | script: sudo nosetests && sudo make docs 10 | notifications: 11 | webhooks: 12 | - https://heimdallr.mournival.net/travis 13 | sudo: true 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012, 2013, 2014 Ilya Otyutskiy 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include MANIFEST.in 2 | include README.rst 3 | include LICENSE 4 | 5 | graft docs 6 | recursive-exclude docs *.pyc *.pyo -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: clean upload 2 | 3 | clean: 4 | rm -rf dist daemonize.egg-info 5 | 6 | upload: 7 | python setup.py sdist bdist_wheel 8 | twine upload dist/* 9 | 10 | docs: 11 | sphinx-build -b html docs docs/_build 12 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | daemonize 2 | ======================== 3 | 4 | 5 | .. image:: https://readthedocs.org/projects/daemonize/badge/?version=latest 6 | :target: http://daemonize.readthedocs.org/en/latest/?badge=latest 7 | :alt: Latest version 8 | 9 | .. image:: https://img.shields.io/travis/thesharp/daemonize.svg 10 | :target: http://travis-ci.org/thesharp/daemonize 11 | :alt: Travis CI 12 | 13 | .. image:: https://img.shields.io/pypi/dm/daemonize.svg 14 | :target: https://pypi.python.org/pypi/daemonize 15 | :alt: PyPI montly downloads 16 | 17 | .. image:: https://img.shields.io/pypi/v/daemonize.svg 18 | :target: https://pypi.python.org/pypi/daemonize 19 | :alt: PyPI last version available 20 | 21 | .. image:: https://img.shields.io/pypi/l/daemonize.svg 22 | :target: https://pypi.python.org/pypi/daemonize 23 | :alt: PyPI license 24 | 25 | 26 | **daemonize** is a library for writing system daemons in Python. It is 27 | distributed under MIT license. Latest version can be downloaded from 28 | `PyPI `__. Full documentation can 29 | be found at 30 | `ReadTheDocs `__. 31 | 32 | Dependencies 33 | ------------ 34 | 35 | It is tested under following Python versions: 36 | 37 | - 2.6 38 | - 2.7 39 | - 3.3 40 | - 3.4 41 | - 3.5 42 | 43 | Installation 44 | ------------ 45 | 46 | You can install it from Python Package Index (PyPI): 47 | 48 | :: 49 | 50 | $ pip install daemonize 51 | 52 | Usage 53 | ----- 54 | 55 | .. code-block:: python 56 | 57 | from time import sleep 58 | from daemonize import Daemonize 59 | 60 | pid = "/tmp/test.pid" 61 | 62 | 63 | def main(): 64 | while True: 65 | sleep(5) 66 | 67 | daemon = Daemonize(app="test_app", pid=pid, action=main) 68 | daemon.start() 69 | 70 | File descriptors 71 | ---------------- 72 | 73 | Daemonize object's constructor understands the optional argument 74 | **keep\_fds** which contains a list of FDs which should not be closed. 75 | For example: 76 | 77 | .. code-block:: python 78 | 79 | import logging 80 | from daemonize import Daemonize 81 | 82 | pid = "/tmp/test.pid" 83 | logger = logging.getLogger(__name__) 84 | logger.setLevel(logging.DEBUG) 85 | logger.propagate = False 86 | fh = logging.FileHandler("/tmp/test.log", "w") 87 | fh.setLevel(logging.DEBUG) 88 | logger.addHandler(fh) 89 | keep_fds = [fh.stream.fileno()] 90 | 91 | 92 | def main(): 93 | logger.debug("Test") 94 | 95 | daemon = Daemonize(app="test_app", pid=pid, action=main, keep_fds=keep_fds) 96 | daemon.start() 97 | -------------------------------------------------------------------------------- /daemonize.py: -------------------------------------------------------------------------------- 1 | # #!/usr/bin/python 2 | 3 | import fcntl 4 | import os 5 | import pwd 6 | import grp 7 | import sys 8 | import signal 9 | import resource 10 | import logging 11 | import atexit 12 | from logging import handlers 13 | import traceback 14 | 15 | 16 | __version__ = "2.5.0" 17 | 18 | 19 | class Daemonize(object): 20 | """ 21 | Daemonize object. 22 | 23 | Object constructor expects three arguments. 24 | 25 | :param app: contains the application name which will be sent to syslog. 26 | :param pid: path to the pidfile. 27 | :param action: your custom function which will be executed after daemonization. 28 | :param keep_fds: optional list of fds which should not be closed. 29 | :param auto_close_fds: optional parameter to not close opened fds. 30 | :param privileged_action: action that will be executed before drop privileges if user or 31 | group parameter is provided. 32 | If you want to transfer anything from privileged_action to action, such as 33 | opened privileged file descriptor, you should return it from 34 | privileged_action function and catch it inside action function. 35 | :param user: drop privileges to this user if provided. 36 | :param group: drop privileges to this group if provided. 37 | :param verbose: send debug messages to logger if provided. 38 | :param logger: use this logger object instead of creating new one, if provided. 39 | :param foreground: stay in foreground; do not fork (for debugging) 40 | :param chdir: change working directory if provided or / 41 | """ 42 | def __init__(self, app, pid, action, 43 | keep_fds=None, auto_close_fds=True, privileged_action=None, 44 | user=None, group=None, verbose=False, logger=None, 45 | foreground=False, chdir="/"): 46 | self.app = app 47 | self.pid = os.path.abspath(pid) 48 | self.action = action 49 | self.keep_fds = keep_fds or [] 50 | self.privileged_action = privileged_action or (lambda: ()) 51 | self.user = user 52 | self.group = group 53 | self.logger = logger 54 | self.verbose = verbose 55 | self.auto_close_fds = auto_close_fds 56 | self.foreground = foreground 57 | self.chdir = chdir 58 | 59 | def sigterm(self, signum, frame): 60 | """ 61 | These actions will be done after SIGTERM. 62 | """ 63 | self.logger.warning("Caught signal %s. Stopping daemon." % signum) 64 | sys.exit(0) 65 | 66 | def exit(self): 67 | """ 68 | Cleanup pid file at exit. 69 | """ 70 | self.logger.warning("Stopping daemon.") 71 | os.remove(self.pid) 72 | sys.exit(0) 73 | 74 | def start(self): 75 | """ 76 | Start daemonization process. 77 | """ 78 | # If pidfile already exists, we should read pid from there; to overwrite it, if locking 79 | # will fail, because locking attempt somehow purges the file contents. 80 | if os.path.isfile(self.pid): 81 | with open(self.pid, "r") as old_pidfile: 82 | old_pid = old_pidfile.read() 83 | # Create a lockfile so that only one instance of this daemon is running at any time. 84 | try: 85 | lockfile = open(self.pid, "w") 86 | except IOError: 87 | print("Unable to create the pidfile.") 88 | sys.exit(1) 89 | try: 90 | # Try to get an exclusive lock on the file. This will fail if another process has the file 91 | # locked. 92 | fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB) 93 | except IOError: 94 | print("Unable to lock on the pidfile.") 95 | # We need to overwrite the pidfile if we got here. 96 | with open(self.pid, "w") as pidfile: 97 | pidfile.write(old_pid) 98 | sys.exit(1) 99 | 100 | # skip fork if foreground is specified 101 | if not self.foreground: 102 | # Fork, creating a new process for the child. 103 | try: 104 | process_id = os.fork() 105 | except OSError as e: 106 | self.logger.error("Unable to fork, errno: {0}".format(e.errno)) 107 | sys.exit(1) 108 | if process_id != 0: 109 | if self.keep_fds: 110 | # This is the parent process. Exit without cleanup, 111 | # see https://github.com/thesharp/daemonize/issues/46 112 | os._exit(0) 113 | else: 114 | sys.exit(0) 115 | # This is the child process. Continue. 116 | 117 | # Stop listening for signals that the parent process receives. 118 | # This is done by getting a new process id. 119 | # setpgrp() is an alternative to setsid(). 120 | # setsid puts the process in a new parent group and detaches its controlling terminal. 121 | process_id = os.setsid() 122 | if process_id == -1: 123 | # Uh oh, there was a problem. 124 | sys.exit(1) 125 | 126 | # Add lockfile to self.keep_fds. 127 | self.keep_fds.append(lockfile.fileno()) 128 | 129 | # Close all file descriptors, except the ones mentioned in self.keep_fds. 130 | devnull = "/dev/null" 131 | if hasattr(os, "devnull"): 132 | # Python has set os.devnull on this system, use it instead as it might be different 133 | # than /dev/null. 134 | devnull = os.devnull 135 | 136 | if self.auto_close_fds: 137 | for fd in range(3, resource.getrlimit(resource.RLIMIT_NOFILE)[0]): 138 | if fd not in self.keep_fds: 139 | try: 140 | os.close(fd) 141 | except OSError: 142 | pass 143 | 144 | devnull_fd = os.open(devnull, os.O_RDWR) 145 | os.dup2(devnull_fd, 0) 146 | os.dup2(devnull_fd, 1) 147 | os.dup2(devnull_fd, 2) 148 | os.close(devnull_fd) 149 | 150 | if self.logger is None: 151 | # Initialize logging. 152 | self.logger = logging.getLogger(self.app) 153 | self.logger.setLevel(logging.DEBUG) 154 | # Display log messages only on defined handlers. 155 | self.logger.propagate = False 156 | 157 | # Initialize syslog. 158 | # It will correctly work on OS X, Linux and FreeBSD. 159 | if sys.platform == "darwin": 160 | syslog_address = "/var/run/syslog" 161 | else: 162 | syslog_address = "/dev/log" 163 | 164 | # We will continue with syslog initialization only if actually have such capabilities 165 | # on the machine we are running this. 166 | if os.path.exists(syslog_address): 167 | syslog = handlers.SysLogHandler(syslog_address) 168 | if self.verbose: 169 | syslog.setLevel(logging.DEBUG) 170 | else: 171 | syslog.setLevel(logging.INFO) 172 | # Try to mimic to normal syslog messages. 173 | formatter = logging.Formatter("%(asctime)s %(name)s: %(message)s", 174 | "%b %e %H:%M:%S") 175 | syslog.setFormatter(formatter) 176 | 177 | self.logger.addHandler(syslog) 178 | 179 | # Set umask to default to safe file permissions when running as a root daemon. 027 is an 180 | # octal number which we are typing as 0o27 for Python3 compatibility. 181 | os.umask(0o27) 182 | 183 | # Change to a known directory. If this isn't done, starting a daemon in a subdirectory that 184 | # needs to be deleted results in "directory busy" errors. 185 | os.chdir(self.chdir) 186 | 187 | # Execute privileged action 188 | privileged_action_result = self.privileged_action() 189 | if not privileged_action_result: 190 | privileged_action_result = [] 191 | 192 | # Change owner of pid file, it's required because pid file will be removed at exit. 193 | uid, gid = -1, -1 194 | 195 | if self.group: 196 | try: 197 | gid = grp.getgrnam(self.group).gr_gid 198 | except KeyError: 199 | self.logger.error("Group {0} not found".format(self.group)) 200 | sys.exit(1) 201 | 202 | if self.user: 203 | try: 204 | uid = pwd.getpwnam(self.user).pw_uid 205 | except KeyError: 206 | self.logger.error("User {0} not found.".format(self.user)) 207 | sys.exit(1) 208 | 209 | if uid != -1 or gid != -1: 210 | os.chown(self.pid, uid, gid) 211 | 212 | # Change gid 213 | if self.group: 214 | try: 215 | os.setgid(gid) 216 | except OSError: 217 | self.logger.error("Unable to change gid.") 218 | sys.exit(1) 219 | 220 | # Change uid 221 | if self.user: 222 | try: 223 | uid = pwd.getpwnam(self.user).pw_uid 224 | except KeyError: 225 | self.logger.error("User {0} not found.".format(self.user)) 226 | sys.exit(1) 227 | try: 228 | os.setuid(uid) 229 | except OSError: 230 | self.logger.error("Unable to change uid.") 231 | sys.exit(1) 232 | 233 | try: 234 | lockfile.write("%s" % (os.getpid())) 235 | lockfile.flush() 236 | except IOError: 237 | self.logger.error("Unable to write pid to the pidfile.") 238 | print("Unable to write pid to the pidfile.") 239 | sys.exit(1) 240 | 241 | # Set custom action on SIGTERM. 242 | signal.signal(signal.SIGTERM, self.sigterm) 243 | atexit.register(self.exit) 244 | 245 | self.logger.warning("Starting daemon.") 246 | 247 | try: 248 | self.action(*privileged_action_result) 249 | except Exception: 250 | for line in traceback.format_exc().split("\n"): 251 | self.logger.error(line) 252 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # daemonize documentation build configuration file, created by 4 | # sphinx-quickstart on Mon Nov 2 17:36:41 2015. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | sys.path.insert(0, os.path.abspath('.')) 22 | sys.path.insert(0, os.path.abspath('..')) 23 | 24 | # -- General configuration ------------------------------------------------ 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | #needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = [ 33 | 'sphinx.ext.autodoc', 34 | 'sphinx.ext.viewcode', 35 | ] 36 | 37 | # Add any paths that contain templates here, relative to this directory. 38 | templates_path = ['_templates'] 39 | 40 | # The suffix of source filenames. 41 | source_suffix = '.rst' 42 | 43 | # The encoding of source files. 44 | #source_encoding = 'utf-8-sig' 45 | 46 | # The master toctree document. 47 | master_doc = 'index' 48 | 49 | # General information about the project. 50 | project = u'daemonize' 51 | copyright = u'2015, Ilya Otyutskiy' 52 | 53 | # The version info for the project you're documenting, acts as replacement for 54 | # |version| and |release|, also used in various other places throughout the 55 | # built documents. 56 | 57 | from daemonize import __version__ 58 | 59 | version = __version__ 60 | release = __version__ 61 | # The full version, including alpha/beta/rc tags. 62 | 63 | # The language for content autogenerated by Sphinx. Refer to documentation 64 | # for a list of supported languages. 65 | #language = None 66 | 67 | # There are two options for replacing |today|: either, you set today to some 68 | # non-false value, then it is used: 69 | #today = '' 70 | # Else, today_fmt is used as the format for a strftime call. 71 | #today_fmt = '%B %d, %Y' 72 | 73 | # List of patterns, relative to source directory, that match files and 74 | # directories to ignore when looking for source files. 75 | exclude_patterns = ['_build'] 76 | 77 | # The reST default role (used for this markup: `text`) to use for all 78 | # documents. 79 | #default_role = None 80 | 81 | # If true, '()' will be appended to :func: etc. cross-reference text. 82 | #add_function_parentheses = True 83 | 84 | # If true, the current module name will be prepended to all description 85 | # unit titles (such as .. function::). 86 | #add_module_names = True 87 | 88 | # If true, sectionauthor and moduleauthor directives will be shown in the 89 | # output. They are ignored by default. 90 | #show_authors = False 91 | 92 | # The name of the Pygments (syntax highlighting) style to use. 93 | pygments_style = 'sphinx' 94 | 95 | # A list of ignored prefixes for module index sorting. 96 | #modindex_common_prefix = [] 97 | 98 | # If true, keep warnings as "system message" paragraphs in the built documents. 99 | #keep_warnings = False 100 | 101 | 102 | # -- Options for HTML output ---------------------------------------------- 103 | 104 | # The theme to use for HTML and HTML Help pages. See the documentation for 105 | # a list of builtin themes. 106 | import sphinx_rtd_theme 107 | 108 | html_theme = "sphinx_rtd_theme" 109 | 110 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] 111 | 112 | # Theme options are theme-specific and customize the look and feel of a theme 113 | # further. For a list of options available for each theme, see the 114 | # documentation. 115 | #html_theme_options = {} 116 | 117 | # Add any paths that contain custom themes here, relative to this directory. 118 | #html_theme_path = [] 119 | 120 | # The name for this set of Sphinx documents. If None, it defaults to 121 | # " v documentation". 122 | #html_title = None 123 | 124 | # A shorter title for the navigation bar. Default is the same as html_title. 125 | #html_short_title = None 126 | 127 | # The name of an image file (relative to this directory) to place at the top 128 | # of the sidebar. 129 | #html_logo = None 130 | 131 | # The name of an image file (within the static path) to use as favicon of the 132 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 133 | # pixels large. 134 | #html_favicon = None 135 | 136 | # Add any paths that contain custom static files (such as style sheets) here, 137 | # relative to this directory. They are copied after the builtin static files, 138 | # so a file named "default.css" will overwrite the builtin "default.css". 139 | html_static_path = ['_static'] 140 | 141 | # Add any extra paths that contain custom files (such as robots.txt or 142 | # .htaccess) here, relative to this directory. These files are copied 143 | # directly to the root of the documentation. 144 | #html_extra_path = [] 145 | 146 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 147 | # using the given strftime format. 148 | #html_last_updated_fmt = '%b %d, %Y' 149 | 150 | # If true, SmartyPants will be used to convert quotes and dashes to 151 | # typographically correct entities. 152 | #html_use_smartypants = True 153 | 154 | # Custom sidebar templates, maps document names to template names. 155 | #html_sidebars = {} 156 | 157 | # Additional templates that should be rendered to pages, maps page names to 158 | # template names. 159 | #html_additional_pages = {} 160 | 161 | # If false, no module index is generated. 162 | #html_domain_indices = True 163 | 164 | # If false, no index is generated. 165 | #html_use_index = True 166 | 167 | # If true, the index is split into individual pages for each letter. 168 | #html_split_index = False 169 | 170 | # If true, links to the reST sources are added to the pages. 171 | #html_show_sourcelink = True 172 | 173 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 174 | #html_show_sphinx = True 175 | 176 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 177 | #html_show_copyright = True 178 | 179 | # If true, an OpenSearch description file will be output, and all pages will 180 | # contain a tag referring to it. The value of this option must be the 181 | # base URL from which the finished HTML is served. 182 | #html_use_opensearch = '' 183 | 184 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 185 | #html_file_suffix = None 186 | 187 | # Output file base name for HTML help builder. 188 | htmlhelp_basename = 'daemonizedoc' 189 | 190 | 191 | # -- Options for LaTeX output --------------------------------------------- 192 | 193 | latex_elements = { 194 | # The paper size ('letterpaper' or 'a4paper'). 195 | #'papersize': 'letterpaper', 196 | 197 | # The font size ('10pt', '11pt' or '12pt'). 198 | #'pointsize': '10pt', 199 | 200 | # Additional stuff for the LaTeX preamble. 201 | #'preamble': '', 202 | } 203 | 204 | # Grouping the document tree into LaTeX files. List of tuples 205 | # (source start file, target name, title, 206 | # author, documentclass [howto, manual, or own class]). 207 | latex_documents = [ 208 | ('index', 'daemonize.tex', u'daemonize Documentation', 209 | u'Ilya Otyutskiy', 'manual'), 210 | ] 211 | 212 | # The name of an image file (relative to this directory) to place at the top of 213 | # the title page. 214 | #latex_logo = None 215 | 216 | # For "manual" documents, if this is true, then toplevel headings are parts, 217 | # not chapters. 218 | #latex_use_parts = False 219 | 220 | # If true, show page references after internal links. 221 | #latex_show_pagerefs = False 222 | 223 | # If true, show URL addresses after external links. 224 | #latex_show_urls = False 225 | 226 | # Documents to append as an appendix to all manuals. 227 | #latex_appendices = [] 228 | 229 | # If false, no module index is generated. 230 | #latex_domain_indices = True 231 | 232 | 233 | # -- Options for manual page output --------------------------------------- 234 | 235 | # One entry per manual page. List of tuples 236 | # (source start file, name, description, authors, manual section). 237 | man_pages = [ 238 | ('index', 'daemonize', u'daemonize Documentation', 239 | [u'Ilya Otyutskiy'], 1) 240 | ] 241 | 242 | # If true, show URL addresses after external links. 243 | #man_show_urls = False 244 | 245 | 246 | # -- Options for Texinfo output ------------------------------------------- 247 | 248 | # Grouping the document tree into Texinfo files. List of tuples 249 | # (source start file, target name, title, author, 250 | # dir menu entry, description, category) 251 | texinfo_documents = [ 252 | ('index', 'daemonize', u'daemonize Documentation', 253 | u'Ilya Otyutskiy', 'daemonize', 'One line description of project.', 254 | 'Miscellaneous'), 255 | ] 256 | 257 | # Documents to append as an appendix to all manuals. 258 | #texinfo_appendices = [] 259 | 260 | # If false, no module index is generated. 261 | #texinfo_domain_indices = True 262 | 263 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 264 | #texinfo_show_urls = 'footnote' 265 | 266 | # If true, do not generate a @detailmenu in the "Top" node's menu. 267 | #texinfo_no_detailmenu = False 268 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. daemonize documentation master file, created by 2 | sphinx-quickstart on Mon Nov 2 17:36:41 2015. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | .. include:: ../README.rst 7 | 8 | API 9 | --- 10 | 11 | .. automodule:: daemonize 12 | :members: 13 | 14 | 15 | Indices and tables 16 | ================== 17 | 18 | * :ref:`genindex` 19 | * :ref:`modindex` 20 | * :ref:`search` 21 | 22 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal = 1 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import re 4 | import ast 5 | 6 | from setuptools import setup, find_packages 7 | 8 | _version_re = re.compile(r'__version__\s+=\s+(.*)') 9 | 10 | 11 | with open('daemonize.py', 'rb') as f: 12 | version = str(ast.literal_eval(_version_re.search( 13 | f.read().decode('utf-8')).group(1))) 14 | 15 | setup( 16 | name="daemonize", 17 | version=version, 18 | py_modules=["daemonize"], 19 | author="Ilya Otyutskiy", 20 | author_email="ilya.otyutskiy@icloud.com", 21 | maintainer="Ilya Otyutskiy", 22 | url="https://github.com/thesharp/daemonize", 23 | description="Library to enable your code run as a daemon process on Unix-like systems.", 24 | license="MIT", 25 | classifiers=["Development Status :: 5 - Production/Stable", 26 | "Environment :: Console", 27 | "Intended Audience :: Developers", 28 | "License :: OSI Approved :: MIT License", 29 | "Operating System :: MacOS :: MacOS X", 30 | "Operating System :: POSIX :: Linux", 31 | "Operating System :: POSIX :: BSD :: FreeBSD", 32 | "Operating System :: POSIX :: BSD :: OpenBSD", 33 | "Operating System :: POSIX :: BSD :: NetBSD", 34 | "Programming Language :: Python", 35 | "Programming Language :: Python :: 2.6", 36 | "Programming Language :: Python :: 2.7", 37 | "Programming Language :: Python :: 3", 38 | "Programming Language :: Python :: 3.3", 39 | "Programming Language :: Python :: 3.4", 40 | "Programming Language :: Python :: 3.5", 41 | "Topic :: Software Development"] 42 | ) 43 | -------------------------------------------------------------------------------- /tests/daemon_chdir.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | 5 | from daemonize import Daemonize 6 | 7 | pid = argv[1] 8 | working_dir = argv[2] 9 | file_name = argv[3] 10 | 11 | 12 | def main(): 13 | with open(file_name, "w") as f: 14 | f.write("test") 15 | 16 | 17 | daemon = Daemonize(app="test_app", pid=pid, action=main, chdir=working_dir) 18 | daemon.start() 19 | -------------------------------------------------------------------------------- /tests/daemon_keep_fds.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import logging 4 | from sys import argv 5 | 6 | from daemonize import Daemonize 7 | 8 | pid = argv[1] 9 | logger = logging.getLogger(__name__) 10 | logger.setLevel(logging.DEBUG) 11 | logger.propagate = False 12 | fh = logging.FileHandler(argv[2], "w") 13 | fh.setLevel(logging.DEBUG) 14 | logger.addHandler(fh) 15 | keep_fds = [fh.stream.fileno()] 16 | 17 | 18 | def main(): 19 | logger.debug("Test") 20 | 21 | daemon = Daemonize(app="test_app", pid=pid, action=main, keep_fds=keep_fds) 22 | daemon.start() 23 | -------------------------------------------------------------------------------- /tests/daemon_privileged_action.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from sys import argv 3 | 4 | from daemonize import Daemonize 5 | 6 | 7 | pid = argv[1] 8 | log = argv[2] 9 | 10 | logger = logging.getLogger(__name__) 11 | logger.setLevel(logging.DEBUG) 12 | logger.propagate = False 13 | fh = logging.FileHandler(log, "w") 14 | fh.setLevel(logging.DEBUG) 15 | logger.addHandler(fh) 16 | keep_fds = [fh.stream.fileno()] 17 | 18 | 19 | def privileged_action(): 20 | logger.info("Privileged action.") 21 | 22 | 23 | def action(): 24 | logger.info("Action.") 25 | 26 | 27 | daemon = Daemonize(app="issue-22", pid=pid, action=action, 28 | privileged_action=privileged_action, logger=logger, keep_fds=keep_fds) 29 | daemon.start() 30 | -------------------------------------------------------------------------------- /tests/daemon_sigterm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | from time import sleep 5 | 6 | from daemonize import Daemonize 7 | 8 | pid = argv[1] 9 | 10 | 11 | def main(): 12 | while True: 13 | sleep(5) 14 | 15 | daemon = Daemonize(app="test_app", pid=pid, action=main) 16 | daemon.start() 17 | -------------------------------------------------------------------------------- /tests/daemon_uid_gid.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from os import getuid, geteuid, getgid, getegid, path 4 | from sys import argv 5 | from time import sleep 6 | 7 | from daemonize import Daemonize 8 | 9 | pid = argv[1] 10 | log = argv[2] 11 | 12 | 13 | def main(): 14 | uids = getuid(), geteuid() 15 | gids = getgid(), getegid() 16 | with open(log, "w") as f: 17 | f.write(" ".join(map(str, uids + gids))) 18 | 19 | 20 | group = "nogroup" if path.exists("/etc/debian_version") else "nobody" 21 | 22 | daemon = Daemonize(app="test_app", pid=pid, action=main, user="nobody", group=group) 23 | daemon.start() 24 | -------------------------------------------------------------------------------- /tests/daemon_uid_gid_action.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from os import getuid, geteuid, getgid, getegid, path 4 | from sys import argv 5 | from time import sleep 6 | 7 | from daemonize import Daemonize 8 | 9 | pid = argv[1] 10 | log = argv[2] 11 | 12 | 13 | def priv(): 14 | return open(log, "w"), 15 | 16 | 17 | def main(f): 18 | uids = getuid(), geteuid() 19 | gids = getgid(), getegid() 20 | f.write(" ".join(map(str, uids + gids))) 21 | 22 | 23 | group = "nogroup" if path.exists("/etc/debian_version") else "nobody" 24 | 25 | daemon = Daemonize(app="test_app", pid=pid, action=main, user="nobody", group=group, 26 | privileged_action=priv) 27 | daemon.start() 28 | -------------------------------------------------------------------------------- /tests/test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import os 3 | import pwd 4 | import grp 5 | import subprocess 6 | 7 | from tempfile import mkstemp 8 | from time import sleep 9 | from os.path import split 10 | 11 | NOBODY_UID = pwd.getpwnam("nobody").pw_uid 12 | if os.path.exists("/etc/debian_version"): 13 | NOBODY_GID = grp.getgrnam("nogroup").gr_gid 14 | else: 15 | NOBODY_GID = grp.getgrnam("nobody").gr_gid 16 | 17 | 18 | class DaemonizeTest(unittest.TestCase): 19 | def setUp(self): 20 | self.pidfile = mkstemp()[1] 21 | os.system("python tests/daemon_sigterm.py %s" % self.pidfile) 22 | sleep(.1) 23 | 24 | def tearDown(self): 25 | os.system("kill `cat %s`" % self.pidfile) 26 | sleep(.1) 27 | 28 | def test_is_working(self): 29 | sleep(10) 30 | proc = subprocess.Popen("ps ax | awk '{print $1}' | grep `cat %s`" % self.pidfile, 31 | shell=True, stdout=subprocess.PIPE) 32 | ps_pid = proc.communicate()[0].decode() 33 | with open(self.pidfile, "r") as pidfile: 34 | pid = pidfile.read() 35 | self.assertEqual("%s\n" % pid, ps_pid) 36 | 37 | def test_pidfile_presense(self): 38 | sleep(10) 39 | self.assertTrue(os.path.isfile(self.pidfile)) 40 | 41 | 42 | class LockingTest(unittest.TestCase): 43 | def setUp(self): 44 | self.pidfile = mkstemp()[1] 45 | print("First daemonize process started") 46 | os.system("python tests/daemon_sigterm.py %s" % self.pidfile) 47 | sleep(.1) 48 | 49 | def tearDown(self): 50 | os.system("kill `cat %s`" % self.pidfile) 51 | sleep(.1) 52 | 53 | def test_locking(self): 54 | sleep(10) 55 | print("Attempting to start second daemonize process") 56 | proc = subprocess.call(["python", "tests/daemon_sigterm.py", self.pidfile]) 57 | self.assertEqual(proc, 1) 58 | 59 | 60 | class KeepFDsTest(unittest.TestCase): 61 | def setUp(self): 62 | self.pidfile = mkstemp()[1] 63 | self.logfile = mkstemp()[1] 64 | os.system("python tests/daemon_keep_fds.py %s %s" % (self.pidfile, self.logfile)) 65 | sleep(1) 66 | 67 | def tearDown(self): 68 | os.system("kill `cat %s`" % self.pidfile) 69 | os.remove(self.logfile) 70 | sleep(.1) 71 | 72 | def test_keep_fds(self): 73 | log = open(self.logfile, "r").read() 74 | self.assertEqual(log, "Test\n") 75 | 76 | 77 | class UidGidTest(unittest.TestCase): 78 | def setUp(self): 79 | self.expected = " ".join(map(str, [NOBODY_UID] * 2 + [NOBODY_GID] * 2)) 80 | self.pidfile = mkstemp()[1] 81 | self.logfile = mkstemp()[1] 82 | 83 | def tearDown(self): 84 | os.remove(self.logfile) 85 | 86 | def test_uid_gid(self): 87 | # Skip test if user is not root 88 | if os.getuid() != 0: 89 | return True 90 | 91 | os.chown(self.logfile, NOBODY_UID, NOBODY_GID) 92 | 93 | os.system("python tests/daemon_uid_gid.py %s %s" % (self.pidfile, self.logfile)) 94 | sleep(1) 95 | 96 | with open(self.logfile, "r") as f: 97 | self.assertEqual(f.read(), self.expected) 98 | self.assertFalse(os.access(self.pidfile, os.F_OK)) 99 | 100 | def test_uid_gid_action(self): 101 | # Skip test if user is not root 102 | if os.getuid() != 0: 103 | return True 104 | 105 | os.chown(self.pidfile, NOBODY_UID, NOBODY_GID) 106 | 107 | os.system("python tests/daemon_uid_gid_action.py %s %s" % (self.pidfile, self.logfile)) 108 | sleep(1) 109 | 110 | with open(self.logfile, "r") as f: 111 | self.assertEqual(f.read(), self.expected) 112 | 113 | 114 | class PrivilegedActionTest(unittest.TestCase): 115 | def setUp(self): 116 | self.correct_log = """Privileged action. 117 | Starting daemon. 118 | Action. 119 | Stopping daemon. 120 | """ 121 | self.pidfile = mkstemp()[1] 122 | self.logfile = mkstemp()[1] 123 | os.system("python tests/daemon_privileged_action.py %s %s" % (self.pidfile, self.logfile)) 124 | sleep(.1) 125 | 126 | def tearDown(self): 127 | os.system("kill `cat %s`" % self.pidfile) 128 | sleep(.1) 129 | 130 | def test_privileged_action(self): 131 | sleep(5) 132 | with open(self.logfile, "r") as contents: 133 | self.assertEqual(contents.read(), self.correct_log) 134 | 135 | 136 | class ChdirTest(unittest.TestCase): 137 | def setUp(self): 138 | self.pidfile = mkstemp()[1] 139 | self.target = mkstemp()[1] 140 | base, file = split(self.target) 141 | 142 | os.system("python tests/daemon_chdir.py %s %s %s" % (self.pidfile, base, file)) 143 | sleep(1) 144 | 145 | def tearDown(self): 146 | os.system("kill `cat %s`" % self.pidfile) 147 | sleep(.1) 148 | 149 | def test_keep_fds(self): 150 | log = open(self.target, "r").read() 151 | self.assertEqual(log, "test") 152 | 153 | if __name__ == '__main__': 154 | unittest.main() 155 | --------------------------------------------------------------------------------