Wednesday, 31 January 2018

Demonizing a Python process

Properly demonizing a Python process is not easy, even on *nix, and although various sources of good material can be found on the internet (for example here and here) it didn't quite match my requirements and/or I didn't understand it completely.
I therefore decided to create both a daemon module and a http server to test it.

Code availability

Both modules are available on GitHub
The daemon module is called daemon.py and the httpserver is called restrictedhttpserver.py. Both have a fair amount of comments in their source code that are the result of me trying to fully understand what is required to get things working.

A small word of warning here: I only tested it with Python3 on Ubuntu and Raspbian and I do not expect it to work on any other operating system (although most *nix like systems probably will work) and in my world Python2 is no longer a valid option.

Also, the Daemon class makes use of an undocumented attribute in the logging.FileHandler class  (the stream.fileno attribute) which is necessary in order not to close this stream when forking a child process. Theoretically this might break in the future but I did want all logging to happen outside the chroot jail so that the process running as a daemon can log but does not have access to the logging. Whether this is a valid approach remains to be seen as this also prevents proper log rotation.

The Daemon class

The basic requirement are all implemented, an instance of a Daemon class can:
run in a chrooted jail
so it cannot access files outside a given directory
run with lowered privileges
so the risk of accessing files not owned by a specific user is lowered
can have a umask of your choice
which will ensure that newly created files by the daemon are not open to all
log outside its jail
so that we can log events without offering the process managed by daemon any way of altering the logging
and maintains a configurable pid file
so that we can prevent the daemon from starting more than once and providing a way the fond out the process id so that we can terminate the daemon
We also made the Daemon class follow the Singleton pattern, i.e. there can only be one instanced object of the class. This is sensible because a process can only be daemonized once. We also implemented to required methods to facilitate use as a context manager. A typical, minimal code snippet would look something like:
from daemon import Daemon

dm = Daemon()
with dm:
    ... do something forever ...
All configurable options have sensible defaults, but a call could look like this:
from daemon import Daemon

dm = Daemon(user='httpserver', rootdir='/var/www', umask=0o27,
             pidfile='/var/lockhttpserver.pid',
             logfile='/var/log/httpserver.log',
             name="Http Server")
with dm:
    ... do something forever ...
It is important to understand that when the Daemon object is created, the process is not immediately daemonized. This is handled by the context manager (or you could call the daemonize() method directly). There is also a stop() method provided that will check for a running daemon process and terminate it. This could look like this:
from daemon import Daemon
import argparse

parser = argparse.ArgumentParser(description="Example Daemon")
parser.add_argument('-s', '--stop', action='store_true', help='stop a running server')
args = parser.parse_args()

dm = Daemon()
if args.stop:
    dm.stop()
else:
    with dm:
        ... do something forever ...

More code

In a future article I will highlight the small http server that I implemented to test the daemon module.

12 comments:

  1. Thank you for providing useful information and its best blog for the students to make good career.learn Python training course.
    Python Training in Hyderabad

    ReplyDelete
  2. Thank you for sharing valuable article with good information in this blog.learn Data science course and make good career.
    Data Science Training in Hyderabad

    ReplyDelete
  3. I think you did an awesome job explaining it. Sure beats having to research it on my own. Thanks
    Delhi University BCOM 1st, 2nd & 3rd Year TimeTable 2020

    ReplyDelete
  4. This professional hacker is absolutely reliable and I strongly recommend him for any type of hack you require. I know this because I have hired him severally for various hacks and he has never disappointed me nor any of my friends who have hired him too, he can help you with any of the following hacks:

    -Phone hacks (remotely)
    -Credit repair
    -Bitcoin recovery (any cryptocurrency)
    -Make money from home (USA only)
    -Social media hacks
    -Website hacks
    -Erase criminal records (USA & Canada only)
    -Grade change
    -funds recovery

    Email: onlineghosthacker247@ gmail .com

    ReplyDelete
  5. Impressive writing. You have the power to keep the reader occupied with your quality content and style of writing. I encourage you to write more.

    VBSPU BSc 3rd year result

    ReplyDelete
  6. Thanks. This exactly what I am looking for.
    For highest returns on your investment please click on this link
    Best open plots for sale in hyderabad

    Best open plots for sale @ shadnagar

    ReplyDelete
  7. Do you want to know about Harry Lewis Net Worth, his early life biography career, and relationship status?

    ReplyDelete
  8. Unlock the power of programming with our Python Training In Chennai at Infycle Technologies! Dive into the world of coding excellence and empower your career with this versatile language. Our course is designed to make learning Python easy and enjoyable, catering to beginners and experienced enthusiasts alike. Gain hands-on experience with real-time projects and expert guidance to master Python's applications in data science, web development, and more. Join us and embark on a journey that's as thrilling as educational. Develop your coding prowess, elevate your career prospects, and become a Python pro with Infycle Technologies! To know more, call us at +91-7502633633 or +91-7504633633.

    ReplyDelete
  9. Looking for Powerlifting coaches georgetown tx? We've got you covered! Our team of experienced powerlifting coaches in Georgetown is here to help you reach your fitness goals. Whether you're a beginner or an advanced lifter, our coaches will provide you with personalized training programs and expert guidance to help you maximize your strength and performance. Get started on your powerlifting journey with our dedicated coaches in Georgetown, TX today!

    Our coaches in Georgetown, TX are passionate about powerlifting and will work closely with you to ensure you're making progress and achieving your goals. Don't wait any longer – start your powerlifting training with our experienced coaches today!

    ReplyDelete