[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
authorAdrien Di Mascio <Adrien.DiMascio@logilab.fr>
Mon, 03 Aug 2009 09:24:50 +0200
changeset 2654 6512522860aa
parent 2653 51bf32bbe78d
child 2655 48cd71bdb5cd
child 2671 ee5538bdf0ea
[twisted] don't use twistd anymore, all-in-one.py file is needed anymore
cwconfig.py
cwctl.py
etwist/server.py
etwist/twctl.py
--- a/cwconfig.py	Sun Aug 02 20:59:57 2009 +0200
+++ b/cwconfig.py	Mon Aug 03 09:24:50 2009 +0200
@@ -777,7 +777,7 @@
             return
         self._logging_initialized = True
         CubicWebNoAppConfiguration.init_log(self, logthreshold, debug,
-                                         logfile=self.get('log-file'))
+                                            logfile=self.get('log-file'))
         # read a config file if it exists
         logconfig = join(self.apphome, 'logging.conf')
         if exists(logconfig):
--- a/cwctl.py	Sun Aug 02 20:59:57 2009 +0200
+++ b/cwctl.py	Mon Aug 03 09:24:50 2009 +0200
@@ -382,6 +382,11 @@
           'default': None,
           'help': 'profile code and use the specified file to store stats',
           }),
+        ('loglevel',
+         {'short': 'l', 'type' : 'choice', 'metavar': '<log level>',
+          'default': None, 'choices': ('debug', 'info', 'warning', 'error'),
+          'help': 'debug if -D is set, error otherwise',
+          }),
         )
 
     def start_instance(self, appid):
@@ -390,7 +395,12 @@
         # without all options defined
         debug = self.get('debug')
         force = self.get('force')
+        loglevel = self.get('loglevel')
         config = cwcfg.config_for(appid)
+        if loglevel is not None:
+            loglevel = 'LOG_%s' % loglevel.upper()
+            config.global_set_option('log-threshold', loglevel)
+            config.init_log(loglevel, debug=debug, force=True)
         if self.get('profile'):
             config.global_set_option('profile', self.config.profile)
         helper = self.config_helper(config, cmdname='start')
@@ -399,16 +409,7 @@
             msg = "%s seems to be running. Remove %s by hand if necessary or use \
 the --force option."
             raise ExecutionError(msg % (appid, pidf))
-        command = helper.start_command(config, debug)
-        if debug:
-            print "starting server with command :"
-            print command
-        if system(command):
-            print 'an error occured while starting the instance, not started'
-            print
-            return False
-        if not debug:
-            print '-> instance %s started.' % appid
+        helper.start_command(config, debug)
         return True
 
 
--- a/etwist/server.py	Sun Aug 02 20:59:57 2009 +0200
+++ b/etwist/server.py	Mon Aug 03 09:24:50 2009 +0200
@@ -8,12 +8,15 @@
 __docformat__ = "restructuredtext en"
 
 import sys
+import os
 import select
 from time import mktime
 from datetime import date, timedelta
 from urlparse import urlsplit, urlunsplit
+import hotshot
 
 from twisted.application import service, strports
+from twisted.scripts._twistd_unix import daemonize
 from twisted.internet import reactor, task, threads
 from twisted.internet.defer import maybeDeferred
 from twisted.web2 import channel, http, server, iweb
@@ -268,35 +271,6 @@
             content = self.appli.need_login_content(req)
         return http.Response(code, req.headers_out, content)
 
-
-# This part gets run when you run this file via: "twistd -noy demo.py"
-def main(appid, cfgname):
-    """Starts an cubicweb  twisted server for an instance
-
-    appid: instance's identifier
-    cfgname: name of the configuration to use (twisted or all-in-one)
-    """
-    from cubicweb.cwconfig import CubicWebConfiguration
-    from cubicweb.etwist import twconfig # trigger configuration registration
-    config = CubicWebConfiguration.config_for(appid, cfgname)
-    # XXX why calling init_available_cubes here ?
-    config.init_available_cubes()
-    # create the site and application objects
-    if '-n' in sys.argv: # debug mode
-        cubicweb = CubicWebRootResource(config, debug=True)
-    else:
-        cubicweb = CubicWebRootResource(config)
-    #toplevel = vhost.VHostURIRewrite(base_url, cubicweb)
-    toplevel = cubicweb
-    website = server.Site(toplevel)
-    application = service.Application("cubicweb")
-    # serve it via standard HTTP on port set in the configuration
-    s = strports.service('tcp:%04d' % (config['port'] or 8080),
-                         channel.HTTPFactory(website))
-    s.setServiceParent(application)
-    return application
-
-
 from twisted.python import failure
 from twisted.internet import defer
 from twisted.web2 import fileupload
@@ -378,3 +352,22 @@
     ocount = sorted(ocount.items(), key=lambda x: x[1], reverse=True)[:20]
     pprint(ocount)
     print 'UNREACHABLE', gc.garbage
+
+def run(config, debug):
+    # create the site
+    root_resource = CubicWebRootResource(config, debug)
+    website = server.Site(root_resource)
+    # serve it via standard HTTP on port set in the configuration
+    port = config['port'] or 8080
+    reactor.listenTCP(port, channel.HTTPFactory(website))
+    baseurl = config['base-url'] or config.default_base_url()
+    print "-> Instance started on", baseurl
+    if not debug:
+        daemonize()
+        if config['pid-file']:
+            file(config['pid-file'], 'w').write(str(os.getpid()))
+    if config['profile']:
+        prof = hotshot.Profile(config['profile'])
+        prof.runcall(reactor.run)
+    else:
+        reactor.run()
--- a/etwist/twctl.py	Sun Aug 02 20:59:57 2009 +0200
+++ b/etwist/twctl.py	Mon Aug 03 09:24:50 2009 +0200
@@ -10,50 +10,17 @@
 
 from cubicweb import underline_title
 from cubicweb.toolsutils import CommandHandler
-from cubicweb.web.webctl import WebCreateHandler
 
 # trigger configuration registration
 import cubicweb.etwist.twconfig # pylint: disable-msg=W0611
 
-
-class TWCreateHandler(WebCreateHandler):
-    cfgname = 'twisted'
-
-    def bootstrap(self, cubes, inputlevel=0):
-        """bootstrap this configuration"""
-        print '\n'+underline_title('Configuring Twisted')
-        mainpyfile = self.config.server_file()
-        mainpy = open(mainpyfile, 'w')
-        mainpy.write('''
-from cubicweb.etwist import server
-application = server.main(%r, %r)
-''' % (self.config.appid, self.config.name))
-        mainpy.close()
-        print '-> generated %s' % mainpyfile
-        super(TWCreateHandler, self).bootstrap(cubes, inputlevel)
-
-
 class TWStartHandler(CommandHandler):
     cmdname = 'start'
     cfgname = 'twisted'
 
     def start_command(self, config, debug):
-        command = ['%s `which twistd`' % sys.executable]
-        for ctl_opt, server_opt in (('pid-file', 'pidfile'),
-                                    ('uid', 'uid'),
-                                    ('log-file', 'logfile',)):
-            value = config[ctl_opt]
-            if not value or (debug and ctl_opt == 'log-file'):
-                continue
-            command.append('--%s %s' % (server_opt, value))
-        if debug:
-            command.append('-n')
-        if config['profile']:
-            command.append('-p %s --savestats' % config['profile'])
-        command.append('-oy')
-        command.append(self.config.server_file())
-        return ' '.join(command)
-
+        from cubicweb.etwist import server
+        server.run(config, debug)
 
 class TWStopHandler(CommandHandler):
     cmdname = 'stop'
@@ -63,7 +30,7 @@
 try:
     from cubicweb.server import serverctl
 
-    class AllInOneCreateHandler(serverctl.RepositoryCreateHandler, TWCreateHandler):
+    class AllInOneCreateHandler(serverctl.RepositoryCreateHandler):
         """configuration to get an instance running in a twisted web server
         integrating a repository server in the same process
         """
@@ -72,7 +39,6 @@
         def bootstrap(self, cubes, inputlevel=0):
             """bootstrap this configuration"""
             serverctl.RepositoryCreateHandler.bootstrap(self, cubes, inputlevel)
-            TWCreateHandler.bootstrap(self, cubes, inputlevel)
 
     class AllInOneStartHandler(TWStartHandler):
         cmdname = 'start'