Skip to content

Commit

Permalink
Write nikola serve -d PID to file
Browse files Browse the repository at this point in the history
Signed-off-by: Chris Warrick <kwpolska@gmail.com>
  • Loading branch information
Kwpolska committed Feb 25, 2017
1 parent ca1ab1b commit 8c43807
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGES.txt
Expand Up @@ -4,6 +4,8 @@ New in master
Features
--------

* Write PID of detached ``nikola serve`` process to a file called
``nikolaserve.pid``
* Append file name (generated from title) if ``nikola new_post``
receives directory name as path (Issue #2651)
* Add a ``require_all_tags`` parameter to the ``post-list`` directive to
Expand Down
26 changes: 22 additions & 4 deletions nikola/plugins/command/serve.py
Expand Up @@ -28,7 +28,9 @@

from __future__ import print_function
import os
import sys
import re
import signal
import socket
import webbrowser
try:
Expand Down Expand Up @@ -106,13 +108,25 @@ class CommandServe(Command):
},
)

def shutdown(self, signum=None, _frame=None):
"""Shut down the server that is running detached."""
if self.dns_sd:
self.dns_sd.Reset()
if os.path.exists(self.serve_pidfile):
os.remove(self.serve_pidfile)
if not self.detached:
self.logger.info("Server is shutting down.")
if signum:
sys.exit(0)

def _execute(self, options, args):
"""Start test server."""
self.logger = get_logger('serve', STDERR_HANDLER)
out_dir = self.site.config['OUTPUT_FOLDER']
if not os.path.isdir(out_dir):
self.logger.error("Missing '{0}' folder?".format(out_dir))
else:
self.serve_pidfile = os.path.abspath('nikolaserve.pid')
os.chdir(out_dir)
if '[' in options['address']:
options['address'] = options['address'].strip('[').strip(']')
Expand All @@ -137,26 +151,30 @@ def _execute(self, options, args):
self.logger.info("Opening {0} in the default web browser...".format(server_url))
webbrowser.open(server_url)
if options['detach']:
self.detached = True
OurHTTPRequestHandler.quiet = True
try:
pid = os.fork()
if pid == 0:
signal.signal(signal.SIGTERM, self.shutdown)
httpd.serve_forever()
else:
self.logger.info("Detached with PID {0}. Run `kill {0}` to stop the server.".format(pid))
with open(self.serve_pidfile, 'w') as fh:
fh.write('{0}\n'.format(pid))
self.logger.info("Detached with PID {0}. Run `kill {0}` or `kill $(cat nikolaserve.pid)` to stop the server.".format(pid))
except AttributeError as e:
if os.name == 'nt':
self.logger.warning("Detaching is not available on Windows, server is running in the foreground.")
else:
raise e
else:
self.detached = False
try:
self.dns_sd = dns_sd(options['port'], (options['ipv6'] or '::' in options['address']))
signal.signal(signal.SIGTERM, self.shutdown)
httpd.serve_forever()
except KeyboardInterrupt:
self.logger.info("Server is shutting down.")
if self.dns_sd:
self.dns_sd.Reset()
self.shutdown()
return 130


Expand Down

0 comments on commit 8c43807

Please sign in to comment.