summaryrefslogtreecommitdiff
path: root/cherrypy/process
diff options
context:
space:
mode:
Diffstat (limited to 'cherrypy/process')
-rw-r--r--cherrypy/process/plugins.py68
-rw-r--r--cherrypy/process/servers.py48
-rw-r--r--cherrypy/process/win32.py12
-rw-r--r--cherrypy/process/wspbus.py26
4 files changed, 77 insertions, 77 deletions
diff --git a/cherrypy/process/plugins.py b/cherrypy/process/plugins.py
index 97d559d6..31e7d768 100644
--- a/cherrypy/process/plugins.py
+++ b/cherrypy/process/plugins.py
@@ -104,8 +104,8 @@ class SignalHandler(object):
if sys.platform[:4] == 'java':
del self.handlers['SIGUSR1']
self.handlers['SIGUSR2'] = self.bus.graceful
- self.bus.log("SIGUSR1 cannot be set on the JVM platform. "
- "Using SIGUSR2 instead.")
+ self.bus.log('SIGUSR1 cannot be set on the JVM platform. '
+ 'Using SIGUSR2 instead.')
self.handlers['SIGINT'] = self._jython_SIGINT_handler
self._previous_handlers = {}
@@ -152,19 +152,19 @@ class SignalHandler(object):
signame = self.signals[signum]
if handler is None:
- self.bus.log("Restoring %s handler to SIG_DFL." % signame)
+ self.bus.log('Restoring %s handler to SIG_DFL.' % signame)
handler = _signal.SIG_DFL
else:
- self.bus.log("Restoring %s handler %r." % (signame, handler))
+ self.bus.log('Restoring %s handler %r.' % (signame, handler))
try:
our_handler = _signal.signal(signum, handler)
if our_handler is None:
- self.bus.log("Restored old %s handler %r, but our "
- "handler was not registered." %
+ self.bus.log('Restored old %s handler %r, but our '
+ 'handler was not registered.' %
(signame, handler), level=30)
except ValueError:
- self.bus.log("Unable to restore %s handler %r." %
+ self.bus.log('Unable to restore %s handler %r.' %
(signame, handler), level=40, traceback=True)
def set_handler(self, signal, listener=None):
@@ -179,36 +179,36 @@ class SignalHandler(object):
if isinstance(signal, text_or_bytes):
signum = getattr(_signal, signal, None)
if signum is None:
- raise ValueError("No such signal: %r" % signal)
+ raise ValueError('No such signal: %r' % signal)
signame = signal
else:
try:
signame = self.signals[signal]
except KeyError:
- raise ValueError("No such signal: %r" % signal)
+ raise ValueError('No such signal: %r' % signal)
signum = signal
prev = _signal.signal(signum, self._handle_signal)
self._previous_handlers[signum] = prev
if listener is not None:
- self.bus.log("Listening for %s." % signame)
+ self.bus.log('Listening for %s.' % signame)
self.bus.subscribe(signame, listener)
def _handle_signal(self, signum=None, frame=None):
"""Python signal handler (self.set_handler subscribes it for you)."""
signame = self.signals[signum]
- self.bus.log("Caught signal %s." % signame)
+ self.bus.log('Caught signal %s.' % signame)
self.bus.publish(signame)
def handle_SIGHUP(self):
"""Restart if daemonized, else exit."""
if self._is_daemonized():
- self.bus.log("SIGHUP caught while daemonized. Restarting.")
+ self.bus.log('SIGHUP caught while daemonized. Restarting.')
self.bus.restart()
else:
# not daemonized (may be foreground or background)
- self.bus.log("SIGHUP caught but not daemonized. Exiting.")
+ self.bus.log('SIGHUP caught but not daemonized. Exiting.')
self.bus.exit()
@@ -239,14 +239,14 @@ class DropPrivileges(SimplePlugin):
def _set_uid(self, val):
if val is not None:
if pwd is None:
- self.bus.log("pwd module not available; ignoring uid.",
+ self.bus.log('pwd module not available; ignoring uid.',
level=30)
val = None
elif isinstance(val, text_or_bytes):
val = pwd.getpwnam(val)[2]
self._uid = val
uid = property(_get_uid, _set_uid,
- doc="The uid under which to run. Availability: Unix.")
+ doc='The uid under which to run. Availability: Unix.')
def _get_gid(self):
return self._gid
@@ -254,14 +254,14 @@ class DropPrivileges(SimplePlugin):
def _set_gid(self, val):
if val is not None:
if grp is None:
- self.bus.log("grp module not available; ignoring gid.",
+ self.bus.log('grp module not available; ignoring gid.',
level=30)
val = None
elif isinstance(val, text_or_bytes):
val = grp.getgrnam(val)[2]
self._gid = val
gid = property(_get_gid, _set_gid,
- doc="The gid under which to run. Availability: Unix.")
+ doc='The gid under which to run. Availability: Unix.')
def _get_umask(self):
return self._umask
@@ -271,7 +271,7 @@ class DropPrivileges(SimplePlugin):
try:
os.umask
except AttributeError:
- self.bus.log("umask function not available; ignoring umask.",
+ self.bus.log('umask function not available; ignoring umask.',
level=30)
val = None
self._umask = val
@@ -393,7 +393,7 @@ class Daemonizer(SimplePlugin):
except OSError:
# Python raises OSError rather than returning negative numbers.
exc = sys.exc_info()[1]
- sys.exit("%s: fork #1 failed: (%d) %s\n"
+ sys.exit('%s: fork #1 failed: (%d) %s\n'
% (sys.argv[0], exc.errno, exc.strerror))
os.setsid()
@@ -406,15 +406,15 @@ class Daemonizer(SimplePlugin):
os._exit(0) # Exit second parent
except OSError:
exc = sys.exc_info()[1]
- sys.exit("%s: fork #2 failed: (%d) %s\n"
+ sys.exit('%s: fork #2 failed: (%d) %s\n'
% (sys.argv[0], exc.errno, exc.strerror))
- os.chdir("/")
+ os.chdir('/')
os.umask(0)
- si = open(self.stdin, "r")
- so = open(self.stdout, "a+")
- se = open(self.stderr, "a+")
+ si = open(self.stdin, 'r')
+ so = open(self.stdout, 'a+')
+ se = open(self.stderr, 'a+')
# os.dup2(fd, fd2) will close fd2 if necessary,
# so we don't explicitly close stdin/out/err.
@@ -442,7 +442,7 @@ class PIDFile(SimplePlugin):
if self.finalized:
self.bus.log('PID %r already written to %r.' % (pid, self.pidfile))
else:
- open(self.pidfile, "wb").write(ntob("%s\n" % pid, 'utf8'))
+ open(self.pidfile, 'wb').write(ntob('%s\n' % pid, 'utf8'))
self.bus.log('PID %r written to %r.' % (pid, self.pidfile))
self.finalized = True
start.priority = 70
@@ -481,7 +481,7 @@ class PerpetualTimer(Timer):
except Exception:
if self.bus:
self.bus.log(
- "Error in perpetual timer thread function %r." %
+ 'Error in perpetual timer thread function %r.' %
self.function, level=40, traceback=True)
# Quit on first error to avoid massive logs.
raise
@@ -523,7 +523,7 @@ class BackgroundTask(threading.Thread):
self.function(*self.args, **self.kwargs)
except Exception:
if self.bus:
- self.bus.log("Error in background task thread function %r."
+ self.bus.log('Error in background task thread function %r.'
% self.function, level=40, traceback=True)
# Quit on first error to avoid massive logs.
raise
@@ -560,24 +560,24 @@ class Monitor(SimplePlugin):
bus=self.bus)
self.thread.setName(threadname)
self.thread.start()
- self.bus.log("Started monitor thread %r." % threadname)
+ self.bus.log('Started monitor thread %r.' % threadname)
else:
- self.bus.log("Monitor thread %r already started." % threadname)
+ self.bus.log('Monitor thread %r already started.' % threadname)
start.priority = 70
def stop(self):
"""Stop our callback's background task thread."""
if self.thread is None:
- self.bus.log("No thread running for %s." %
+ self.bus.log('No thread running for %s.' %
self.name or self.__class__.__name__)
else:
if self.thread is not threading.currentThread():
name = self.thread.getName()
self.thread.cancel()
if not self.thread.daemon:
- self.bus.log("Joining %r" % name)
+ self.bus.log('Joining %r' % name)
self.thread.join()
- self.bus.log("Stopped thread %r." % name)
+ self.bus.log('Stopped thread %r.' % name)
self.thread = None
def graceful(self):
@@ -674,10 +674,10 @@ class Autoreloader(Monitor):
else:
if mtime is None or mtime > oldtime:
# The file has been deleted or modified.
- self.bus.log("Restarting because %s changed." %
+ self.bus.log('Restarting because %s changed.' %
filename)
self.thread.cancel()
- self.bus.log("Stopped thread %r." %
+ self.bus.log('Stopped thread %r.' %
self.thread.getName())
self.bus.restart()
return
diff --git a/cherrypy/process/servers.py b/cherrypy/process/servers.py
index 83304efd..7d6ec6c9 100644
--- a/cherrypy/process/servers.py
+++ b/cherrypy/process/servers.py
@@ -152,19 +152,19 @@ class ServerAdapter(object):
def start(self):
"""Start the HTTP server."""
if self.bind_addr is None:
- on_what = "unknown interface (dynamic?)"
+ on_what = 'unknown interface (dynamic?)'
elif isinstance(self.bind_addr, tuple):
on_what = self._get_base()
else:
- on_what = "socket file: %s" % self.bind_addr
+ on_what = 'socket file: %s' % self.bind_addr
if self.running:
- self.bus.log("Already serving on %s" % on_what)
+ self.bus.log('Already serving on %s' % on_what)
return
self.interrupt = None
if not self.httpserver:
- raise ValueError("No HTTP server has been created.")
+ raise ValueError('No HTTP server has been created.')
if not os.environ.get('LISTEN_PID', None):
# Start the httpserver in a new thread.
@@ -173,12 +173,12 @@ class ServerAdapter(object):
import threading
t = threading.Thread(target=self._start_http_thread)
- t.setName("HTTPServer " + t.getName())
+ t.setName('HTTPServer ' + t.getName())
t.start()
self.wait()
self.running = True
- self.bus.log("Serving on %s" % on_what)
+ self.bus.log('Serving on %s' % on_what)
start.priority = 75
def _get_base(self):
@@ -186,15 +186,15 @@ class ServerAdapter(object):
return ''
host, port = self.bind_addr
if getattr(self.httpserver, 'ssl_adapter', None):
- scheme = "https"
+ scheme = 'https'
if port != 443:
- host += ":%s" % port
+ host += ':%s' % port
else:
- scheme = "http"
+ scheme = 'http'
if port != 80:
- host += ":%s" % port
+ host += ':%s' % port
- return "%s://%s" % (scheme, host)
+ return '%s://%s' % (scheme, host)
def _start_http_thread(self):
"""HTTP servers MUST be running in new threads, so that the
@@ -206,24 +206,24 @@ class ServerAdapter(object):
try:
self.httpserver.start()
except KeyboardInterrupt:
- self.bus.log("<Ctrl-C> hit: shutting down HTTP server")
+ self.bus.log('<Ctrl-C> hit: shutting down HTTP server')
self.interrupt = sys.exc_info()[1]
self.bus.exit()
except SystemExit:
- self.bus.log("SystemExit raised: shutting down HTTP server")
+ self.bus.log('SystemExit raised: shutting down HTTP server')
self.interrupt = sys.exc_info()[1]
self.bus.exit()
raise
except:
self.interrupt = sys.exc_info()[1]
- self.bus.log("Error in HTTP server: shutting down",
+ self.bus.log('Error in HTTP server: shutting down',
traceback=True, level=40)
self.bus.exit()
raise
def wait(self):
"""Wait until the HTTP server is ready to receive requests."""
- while not getattr(self.httpserver, "ready", False):
+ while not getattr(self.httpserver, 'ready', False):
if self.interrupt:
raise self.interrupt
time.sleep(.1)
@@ -245,9 +245,9 @@ class ServerAdapter(object):
if isinstance(self.bind_addr, tuple):
wait_for_free_port(*self.bind_addr)
self.running = False
- self.bus.log("HTTP Server %s shut down" % self.httpserver)
+ self.bus.log('HTTP Server %s shut down' % self.httpserver)
else:
- self.bus.log("HTTP Server %s already shut down" % self.httpserver)
+ self.bus.log('HTTP Server %s already shut down' % self.httpserver)
stop.priority = 25
def restart(self):
@@ -394,10 +394,10 @@ def check_port(host, port, timeout=1.0):
except socket.gaierror:
if ':' in host:
info = [(
- socket.AF_INET6, socket.SOCK_STREAM, 0, "", (host, port, 0, 0)
+ socket.AF_INET6, socket.SOCK_STREAM, 0, '', (host, port, 0, 0)
)]
else:
- info = [(socket.AF_INET, socket.SOCK_STREAM, 0, "", (host, port))]
+ info = [(socket.AF_INET, socket.SOCK_STREAM, 0, '', (host, port))]
for res in info:
af, socktype, proto, canonname, sa = res
@@ -413,8 +413,8 @@ def check_port(host, port, timeout=1.0):
if s:
s.close()
else:
- raise IOError("Port %s is in use on %s; perhaps the previous "
- "httpserver did not shut down properly." %
+ raise IOError('Port %s is in use on %s; perhaps the previous '
+ 'httpserver did not shut down properly.' %
(repr(port), repr(host)))
@@ -440,7 +440,7 @@ def wait_for_free_port(host, port, timeout=None):
else:
return
- raise IOError("Port %r not free on %r" % (port, host))
+ raise IOError('Port %r not free on %r' % (port, host))
def wait_for_occupied_port(host, port, timeout=None):
@@ -460,11 +460,11 @@ def wait_for_occupied_port(host, port, timeout=None):
time.sleep(timeout)
if host == client_host(host):
- raise IOError("Port %r not bound on %r" % (port, host))
+ raise IOError('Port %r not bound on %r' % (port, host))
# On systems where a loopback interface is not available and the
# server is bound to all interfaces, it's difficult to determine
# whether the server is in fact occupying the port. In this case,
# just issue a warning and move on. See issue #1100.
- msg = "Unable to verify that the server is bound on %r" % port
+ msg = 'Unable to verify that the server is bound on %r' % port
warnings.warn(msg)
diff --git a/cherrypy/process/win32.py b/cherrypy/process/win32.py
index 4afd3f14..edaf48b2 100644
--- a/cherrypy/process/win32.py
+++ b/cherrypy/process/win32.py
@@ -85,7 +85,7 @@ class Win32Bus(wspbus.Bus):
return self.events[state]
except KeyError:
event = win32event.CreateEvent(None, 0, 0,
- "WSPBus %s Event (pid=%r)" %
+ 'WSPBus %s Event (pid=%r)' %
(state.name, os.getpid()))
self.events[state] = event
return event
@@ -135,7 +135,7 @@ class _ControlCodes(dict):
for key, val in self.items():
if val is obj:
return key
- raise ValueError("The given object could not be found: %r" % obj)
+ raise ValueError('The given object could not be found: %r' % obj)
control_codes = _ControlCodes({'graceful': 138})
@@ -153,14 +153,14 @@ class PyWebService(win32serviceutil.ServiceFramework):
"""Python Web Service."""
- _svc_name_ = "Python Web Service"
- _svc_display_name_ = "Python Web Service"
+ _svc_name_ = 'Python Web Service'
+ _svc_display_name_ = 'Python Web Service'
_svc_deps_ = None # sequence of service names on which this depends
- _exe_name_ = "pywebsvc"
+ _exe_name_ = 'pywebsvc'
_exe_args_ = None # Default to no arguments
# Only exists on Windows 2000 or later, ignored on windows NT
- _svc_description_ = "Python Web Service"
+ _svc_description_ = 'Python Web Service'
def SvcDoRun(self):
from cherrypy import process
diff --git a/cherrypy/process/wspbus.py b/cherrypy/process/wspbus.py
index 4186a96e..edd21fdc 100644
--- a/cherrypy/process/wspbus.py
+++ b/cherrypy/process/wspbus.py
@@ -117,7 +117,7 @@ class _StateEnum(object):
name = None
def __repr__(self):
- return "states.%s" % self.name
+ return 'states.%s' % self.name
def __setattr__(self, key, value):
if isinstance(value, self.State):
@@ -214,7 +214,7 @@ class Bus(object):
# Assume any further messages to 'log' will fail.
pass
else:
- self.log("Error in %r listener %r" % (channel, listener),
+ self.log('Error in %r listener %r' % (channel, listener),
level=40, traceback=True)
if exc:
raise exc
@@ -224,10 +224,10 @@ class Bus(object):
"""An atexit handler which asserts the Bus is not running."""
if self.state != states.EXITING:
warnings.warn(
- "The main thread is exiting, but the Bus is in the %r state; "
- "shutting it down automatically now. You must either call "
- "bus.block() after start(), or call bus.exit() before the "
- "main thread exits." % self.state, RuntimeWarning)
+ 'The main thread is exiting, but the Bus is in the %r state; '
+ 'shutting it down automatically now. You must either call '
+ 'bus.block() after start(), or call bus.exit() before the '
+ 'main thread exits.' % self.state, RuntimeWarning)
self.exit()
def start(self):
@@ -243,7 +243,7 @@ class Bus(object):
except (KeyboardInterrupt, SystemExit):
raise
except:
- self.log("Shutting down due to error in start listener:",
+ self.log('Shutting down due to error in start listener:',
level=40, traceback=True)
e_info = sys.exc_info()[1]
try:
@@ -320,7 +320,7 @@ class Bus(object):
# It's also good to let them all shut down before allowing
# the main thread to call atexit handlers.
# See https://github.com/cherrypy/cherrypy/issues/751.
- self.log("Waiting for child threads to terminate...")
+ self.log('Waiting for child threads to terminate...')
for t in threading.enumerate():
# Validate the we're not trying to join the MainThread
# that will cause a deadlock and the case exist when
@@ -332,13 +332,13 @@ class Bus(object):
not isinstance(t, threading._MainThread)
):
# Note that any dummy (external) threads are always daemonic.
- if hasattr(threading.Thread, "daemon"):
+ if hasattr(threading.Thread, 'daemon'):
# Python 2.6+
d = t.daemon
else:
d = t.isDaemon()
if not d:
- self.log("Waiting for thread %s." % t.getName())
+ self.log('Waiting for thread %s.' % t.getName())
t.join()
if self.execv:
@@ -415,7 +415,7 @@ class Bus(object):
)
if needs_patch:
- env["PYTHONPATH"] = path_prefix + existing_path
+ env['PYTHONPATH'] = path_prefix + existing_path
def _set_cloexec(self):
"""Set the CLOEXEC flag on all open files (except stdin/out/err).
@@ -462,10 +462,10 @@ class Bus(object):
return t
- def log(self, msg="", level=20, traceback=False):
+ def log(self, msg='', level=20, traceback=False):
"""Log the given message. Append the last traceback if requested."""
if traceback:
- msg += "\n" + "".join(_traceback.format_exception(*sys.exc_info()))
+ msg += '\n' + ''.join(_traceback.format_exception(*sys.exc_info()))
self.publish('log', msg, level)
bus = Bus()