diff options
-rw-r--r-- | .gitignore | 1 | ||||
-rw-r--r-- | Makefile | 22 | ||||
-rw-r--r-- | README.md | 51 | ||||
-rw-r--r-- | __pycache__/daemon.cpython-35.pyc | bin | 0 -> 906 bytes | |||
-rw-r--r-- | build/Dockerfile | 21 | ||||
-rw-r--r-- | build/entry.sh | 2 | ||||
-rwxr-xr-x | daemon_example.py | 63 | ||||
-rw-r--r-- | unix_doublefork.py | 37 |
8 files changed, 197 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ce3ed24 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.vimcache diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..d00ed5e --- /dev/null +++ b/Makefile @@ -0,0 +1,22 @@ +.PHONY: build + +IMAGENAME=thornycrackers/python_daemon +CONTAINERNAME=python_daemon + +help: + @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' + +build: ## Build the Docker image + docker build -t $(IMAGENAME) ./build + +up: build ## Bring the Docker container up + docker run -dP -v $(CURDIR):/app --name $(CONTAINERNAME) $(IMAGENAME) /bin/bash -c '/opt/entry.sh' + +down: ## Stop the Docker container + docker stop $(CONTAINERNAME) || echo 'No container to stop' + +enter: ## Enter the running Docker container + docker exec -it $(CONTAINERNAME) /bin/bash + +clean: down ## Remove the Docker image and any stopped containers + docker rm $(CONTAINERNAME) || echo 'No container to remove' diff --git a/README.md b/README.md new file mode 100644 index 0000000..9937b6c --- /dev/null +++ b/README.md @@ -0,0 +1,51 @@ +# What is a daemon? +- A computer program that runs as a background process, rather than being under the direct control of an interactive user. +- Generally end with a 'd' (e.g. 'sshd', 'syslogd') + +# Easiest Example +- nohup python simple server & + +# Why do the double fork? +Fork then exit, process becomes child of init. + +Session (SID) → Process Group (PGID) → Process (PID) + +a process group denotes a collection of one or more processes. +a session denotes a collection of one or more process groups. + +The first process in the process group becomes the process group leader and the +first process in the session becomes the session leader. Every session can have +one TTY associated with it. Only a session leader can take control of a TTY. +For a process to be truly daemonized (ran in the background) we should ensure +that the session leader is killed so that there is no possibility of the +session ever taking control of the TTY. + +http://stackoverflow.com/questions/881388/what-is-the-reason-for-performing-a-double-fork-when-creating-a-daemon + +# What does setsid do? +creates a new session if the calling process is not a process group leader. +The calling process is the leader of the new session, the process group leader +of the new process group, and has no controlling terminal. +http://unix.stackexchange.com/questions/240646/why-we-use-setsid-while-daemonizing-a-process + +# Pop quiz, why can't we do just a single fork? +Disallowing a process group leader from calling setsid() +prevents the possibility that a process group leader places itself in +a new session while other processes in the process group remain in +the original session; such a scenario would break the strict two- +level hierarchy of sessions and process groups. +http://man7.org/linux/man-pages/man2/setsid.2.html + +# What does nohup do? +Ignores the hangup signal. + +# How to create a daemon. +http://web.archive.org/web/20120914180018/http://www.steve.org.uk/Reference/Unix/faq_2.html#SEC16 +1. fork() so the parent can exit, this returns control to the command line or shell invoking your program. This step is required so that the new process is guaranteed not to be a process group leader. The next step, setsid(), fails if you're a process group leader. +2. setsid() to become a process group and session group leader. Since a controlling terminal is associated with a session, and this new session has not yet acquired a controlling terminal our process now has no controlling terminal, which is a Good Thing for daemons. +3. fork() again so the parent, (the session group leader), can exit. This means that we, as a non-session group leader, can never regain a controlling terminal. +4. chdir("/") to ensure that our process doesn't keep any directory in use. Failure to do this could make it so that an administrator couldn't unmount a filesystem, because it was our current directory. [Equivalently, we could change to any directory containing files important to the daemon's operation.] +5. umask(0) so that we have complete control over the permissions of anything we write. We don't know what umask we may have inherited. [This step is optional] +6. close() fds 0, 1, and 2. This releases the standard in, out, and error we inherited from our parent process. We have no way of knowing where these fds might have been redirected to. Note that many daemons use sysconf() to determine the limit _SC_OPEN_MAX. _SC_OPEN_MAX tells you the maximun open files/process. Then in a loop, the daemon can close all possible file descriptors. You have to decide if you need to do this or not. If you think that there might be file-descriptors open you should close them, since there's a limit on number of concurrent file descriptors. +7. Establish new open descriptors for stdin, stdout and stderr. Even if you don't plan to use them, it is still a good idea to have them open. The precise handling of these is a matter of taste; if you have a logfile, for example, you might wish to open it as stdout or stderr, and open `/dev/null' as stdin; alternatively, you could open `/dev/console' as stderr and/or stdout, and `/dev/null' as stdin, or any other combination that makes sense for your particular daemon. + diff --git a/__pycache__/daemon.cpython-35.pyc b/__pycache__/daemon.cpython-35.pyc Binary files differnew file mode 100644 index 0000000..e7f3506 --- /dev/null +++ b/__pycache__/daemon.cpython-35.pyc diff --git a/build/Dockerfile b/build/Dockerfile new file mode 100644 index 0000000..f9e25a8 --- /dev/null +++ b/build/Dockerfile @@ -0,0 +1,21 @@ +FROM ubuntu:16.04 +MAINTAINER Cody Hiar <codyfh@gmail.com> + +# Set a term for terminal inside the container, can't clear without it +ENV TERM xterm-256color + +# Update and install +RUN apt-get update && apt-get install -y \ + htop \ + python-dev \ + python-pip + +# Add the project requirements +ADD requirements.txt /opt/requirements.txt + +# The code should be symlinked to this directory +WORKDIR /app + +# Create the entry script +ADD entry.sh /opt/ +RUN chmod 755 /opt/entry.sh diff --git a/build/entry.sh b/build/entry.sh new file mode 100644 index 0000000..f570d44 --- /dev/null +++ b/build/entry.sh @@ -0,0 +1,2 @@ +#!/bin/bash +while true; do echo hi; sleep 1; done; diff --git a/daemon_example.py b/daemon_example.py new file mode 100755 index 0000000..0eb3a7f --- /dev/null +++ b/daemon_example.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Example on how to create a daemon. + +If you are confused on how the daemon library works you can get some ideas +from the tests. + +https://pagure.io/python-daemon/blob/master/f/test/test_runner.py +""" +from logging import FileHandler, Formatter, getLogger, info +from os import fork, setsid, getpid +from sys import exit +from time import sleep + + +class MyDaemon(object): + """Daemon class. Not for production use, example only.""" + + def __init__(self): + """Initialize the paths and the pidfile of the daemon.""" + self.stdin_path = '/dev/null' + self.stdout_path = '/dev/null' + self.stderr_path = '/dev/null' + self.pidfile_path = '/var/run/python_daemon.pid' + + def create_pidfile(self): + with open(self.pidfile_path, mode='w', encoding='utf-8') as a_file: + a_file.write(str('{}\n'.format(self.pid))) + + def detach_process(self): + """Simple method for daemonizing process.""" + newpid = fork() + if newpid > 0: + exit() + else: + setsid() + newpid = fork() + if newpid > 0: + exit() + else: + self.pid = getpid() + self.create_pidfile() + return + + def run(self): + """Entrypoint for the daemon.""" + self.detach_process() + # Setup logging + log = getLogger() + handler = FileHandler('/var/log/python_daemon.log') + formatter = Formatter('%(asctime)s %(levelname)s %(message)s') + handler.setFormatter(formatter) + log.addHandler(handler) + log.setLevel('INFO') + while True: + info('I am alive') + sleep(1) + + +# run the daemon +if __name__ == '__main__': + daemon = MyDaemon() + daemon.run() diff --git a/unix_doublefork.py b/unix_doublefork.py new file mode 100644 index 0000000..fc94a42 --- /dev/null +++ b/unix_doublefork.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +"""Example of the Unix double fork for daemons.""" +import os +import sys + + +def print_process_info(name): + """Print information about the currently executing process.""" + pid = os.getpid() + pgid = os.getpgid(pid) + sid = os.getsid(pid) + print('{} (PID:{}) (PGID:{}) (SID:{})'.format(name, pid, pgid, sid)) + + +# First Fork +newpid = os.fork() +if newpid > 0: + print_process_info('Parent') + sys.exit() +else: + print_process_info('Child') + os.setsid() + newpid = os.fork() + # Second fork + if newpid == 0: + print_process_info('Grandchild') + else: + print_process_info('Child') + sys.exit() + +# # POP QUIZ!!!! Why won't this work +# print_process_info('Parent') +# os.setsid() +# print_process_info('Parent') +# newpid = os.fork() +# if newpid == 0: +# print_process_info('Child') |