managament/commands/runcogen.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from django.core.management.base import BaseCommand, CommandError
from django.utils.daemonize import become_daemon
from django.utils.termcolors import colorize
from django.core.handlers.wsgi import WSGIHandler
from django.conf import settings
from django.utils import translation
from optparse import make_option
import os, sys, signal
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--foreground', action='store_false', dest='daemonize', default=True,
help="Don't daemonize (and hide output)." ),
make_option('--debug', action='store_true', dest='debug', default=False,
help="Start server in debug mode (implies --foreground)."),
)
def handle(self, addrport='', *args, **options):
try:
from cogen.web import wsgi, async
from cogen.common import Scheduler, priority
except ImportError:
print "cogen not installed."
return False
if not addrport:
addr = ''
port = getattr(settings, 'SERVER_PORT', 8000)
else:
try:
addr, port = addrport.split(':')
except ValueError:
addr, port = '', addrport
if not addr:
addr = getattr(settings, 'SERVER_ADDR', '127.0.0.1')
try:
port = int(port)
except:
raise CommandError("%r is not a valid port number." % port)
pidfile = getattr(settings, 'SERVER_PID', None)
if pidfile:
try:
oldpid = int(open(pidfile).read())
os.kill(oldpid, 0)
print colorize("Found old alive daemon (PID %s)" % oldpid,
fg='yellow', opts=('bold',))
os.kill(oldpid, signal.SIGHUP)
from time import sleep
while True:
sleep(1)
os.kill(oldpid, 0)
except (IOError, OSError):
pass
print colorize('Starting server at %s:%s' % (addr, port),
fg='green', opts=('bold',))
if options['debug']:
settings.DEBUG = True
options['daemonize'] = False
if options['daemonize']:
become_daemon()
pid = os.getpid()
open('/opt/market/var/run/server.pid', 'w').write(str(pid))
try:
# Activate the current language, because it won't get activated later.
try:
translation.activate(settings.LANGUAGE_CODE)
except AttributeError:
pass
application = WSGIHandler()
scheduler = Scheduler(default_priority=priority.LAST, default_timeout=15)
server = wsgi.WSGIServer(
(addr, port),
async.sync_input(application),
scheduler,
server_name='localhost')
scheduler.add(server.serve)
scheduler.run()
except (KeyboardInterrupt, SystemExit):
pass