iro/iro.py
changeset 302 3f4bdea2abbf
parent 67 d1912509f375
parent 298 503ed1a61543
child 308 a891fdd0c1a9
--- a/iro/iro.py	Wed Dec 21 22:07:48 2011 +0100
+++ b/iro/iro.py	Thu Sep 27 17:15:46 2012 +0200
@@ -1,177 +1,82 @@
-# -*- coding: utf-8 -*-
-#Copyright (C) 2009  Sandro Knauß <bugs@sandroknauss.de>
-
-#This program is free software; you can redistribute it and/or modify it under the terms
-#of the GNU General Public License as published by the Free Software Foundation;
-#either version 3 of the License, or any later version.
-#This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
-#without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-#See the GNU General Public License for more details.
-
-#You should have received a copy of the GNU General Public License
-#along with this program; if not, see <http://www.gnu.org/licenses/>.
-
-import multiprocessing, logging 
-#logging anfangen
-logger=logging.getLogger("iro")
-logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)s(%(processName)s)-%(levelname)s: %(message)s')
-
-
-# Server code
-from xmlrpc import SecureUserDBXMLRPCServer,UserDB
-
-from user import User, Admin
-import anbieter
-import ConfigParser
-
-from job import SMSJob, FAXJob, MailJob
-from joblist import Joblist
-from providerlist import Providerlist
-from acounting import Acounting
-
-class MyUserDB(UserDB):
-    def __init__(self, userlist,jobqueue):
-        UserDB.__init__(self, None,userlist,jobqueue)
-        
-    def createUser(self, user):
-        self.userlist[self.createHash(user)]=user["class"](user["name"],self.jobqueue)
-
-
- 
+# Copyright (c) 2012 netzguerilla.net <iro@netzguerilla.net>
+# 
+# This file is part of Iro.
+# 
+# Permission is hereby granted, free of charge, to any person obtaining a copy of
+# this software and associated documentation files (the "Software"), to deal in
+# the Software without restriction, including without limitation the rights to use,
+# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+# #Software, and to permit persons to whom the Software is furnished to do so,
+# subject to the following conditions:
+# 
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+# 
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
-class MySipgate(anbieter.sipgate):
-    
-    def __init__(self,user="",password="" ):
-        anbieter.sipgate.__init__(self, user, password)
-    
-    def setJob(self, job):
-        self.job=job
-    
-    def updateStatus(self, arranged=None, failed=None):
-        if arranged:
-            self.job.addGood(arranged)
-        
-        if failed:
-            self.job.addFailed(failed)
-            
-class MySMTP(anbieter.SMTP):
-    
-    def __init__(self,config_filename=None,section="smtp"):
-        anbieter.SMTP.__init__(self,config_filename,section)
-    
-    def setJob(self, job):
-        self.job=job
-    
-    def updateStatus(self, arranged=None, failed=None):
-        if arranged:
-            self.job.addGood(arranged)
-        
-        if failed:
-            self.job.addFailed(failed)
-    
-class MySmstrade(anbieter.smstrade):
-    
-    def __init__(self ):
-        anbieter.smstrade.__init__(self )
-    
-    def setJob(self, job):
-        self.job=job
-    
-    def updateStatus(self, arranged=None, failed=None):
-        if arranged:
-            self.job.addGood(arranged)
-        
-        if failed:
-            self.job.addFailed(failed)
+from twisted.application.service import Service, MultiService
+from twisted.application import internet
+from twisted.web import resource, server
+from twisted.internet import reactor
+from twisted.python import log
+
+from sqlalchemy import create_engine, pool
 
+import config, install
+from .view import xmlrpc, jsonrpc, jsonresource
+from .model import setEngine, setPool
+from .controller.pool import startPool, dbPool
+
+class IroService(Service):
+    def startService(self):
+        log.msg("Starting service...")
+        engine = create_engine(config.main.dburl,
+               poolclass = pool.SingletonThreadPool,  pool_size=dbPool.maxthreads, pool_recycle=3600)
+
+        setEngine(engine)
+        startPool(reactor)
+        setPool(dbPool)
+        reactor.callWhenRunning(config.readConfig)
+        Service.startService(self)
 
 
-def start(userlist):
-    from multiprocessing import Queue
-    from multiprocessing.managers import BaseManager
-
-    
-    class MyManager(BaseManager):
-        pass
-    
-    MyManager.register('SMSJob', SMSJob) 
-    MyManager.register('FaxJob', FAXJob) 
-    MyManager.register('MailJob',MailJob) 
-    MyManager.register('Providerlist',Providerlist) 
-    MyManager.register('Acounting',Acounting)
-    manager = MyManager()
-    manager.start()
-    
-    
-    conf=["iro.conf", "~/iro.conf","/etc/iro/iro.conf"]
+def makeService(cfg):
+    top_service = MultiService()
+    config.confFiles.insert(0, cfg["config"])
+    if not install.checkConfig():
+        log.err("You can create a sample configuration file by running iro-install")
+        raise Exception("Please update or create your configuration file %s." % cfg["config"])
+    config.init()
 
-    #anbieter erzeugen und konfigurieren
-
-    sip=MySipgate()
-    sip.read_basic_config(conf)
-    
-    localhost=MySMTP()
-    localhost.read_basic_config(conf)
-
-    smstrade=MySmstrade()
-    smstrade.read_basic_config(conf)
-
-    cp = ConfigParser.ConfigParser()
-    cp.read(conf)
-    dbconn={'type':cp.get('db', 'type'),
-            'host':cp.get('db', 'host'),
-            'db':cp.get('db', 'db'),
-            'user':cp.get('db', 'user'),
-            'passwd':cp.get('db', 'passwd'),
-            'table':cp.get('db', 'table'),
-    }
-    
+    if not install.checkDatabaseConnection():
+        raise Exception("Can't connect to database")
     
-    #Benutzerdatenbank erstellen
-    queue = Queue()
-    provider=manager.Providerlist()
-    provider.add("sipgate", sip, ["sms", "fax", ])
-    provider.add("smstrade", smstrade, ["sms", ])
-    #provider.add("geonet", None, ["sms", "fax", ])
-    #provider.add("fax.de", None, ["sms", "fax", ])
-    provider.add("localhost", localhost, ["mail", ])
-    provider.setDefault("sms","smstrade")
-    provider.setDefault("fax","sipgate")
-    provider.setDefault("mail","localhost")
-    jobqueue=Joblist(manager,  queue, provider,dbconn)
-   
-    userdb=MyUserDB(userlist,jobqueue)
+    if not install.checkDatabase():
+        raise Exception("Database not in right format. Please run iro-install --install")
 
-    #working thread erstellen
-    from worker import Worker
-    worker=Worker(queue)
-    worker.start()
+    routes = [ s for s in config.configParser.sections() if not s in ["main",]]
+    ao =  install.getAllRoutes(routes, False)
+    for o in  ao["orphand"]:
+        log.msg("Offer(%s) is orphand (no route using this offer)."%o)
+    if ao["added"]:
+        raise Exception("offerlist is not up-to-date.\nPlease run iro-install --update")
 
-    #Server starten
-    cp = ConfigParser.ConfigParser()
-    cp.read(conf)
-    cert=cp.get('server', 'cert')
-    key=cp.get('server', 'key')
-    server = SecureUserDBXMLRPCServer(addr=("localhost", 8000), 
-                                      userdb=userdb,
-                                      certificate=cert,privatekey=key)
-    server.relam="xmlrpc"
+    root = resource.Resource()
+    xmlrpc.appendResource(root)
+    jsonrpc.appendResource(root)
+    jsonresource.appendResource(root)
     
-    logger.info('Server gestartet...')
-    try:
-        server.serve_forever()
-    except KeyboardInterrupt:
-        pass
-    except:
-        logger.exception('Äh, ein Fehler ist aufgetreten')
-    finally:    
-        logger.info('Server wird beendet...')
-        queue.close()
-        worker.terminate()
+    v2 = resource.Resource()
+    xmlrpc.appendResource(v2)
+    jsonrpc.appendResource(v2)
+    jsonresource.appendResource(v2)
+    root.putChild('1.0a', v2)
 
-if __name__ == '__main__':
-    userlist=[{"name":"test","password":"test",  "class":User},
-	      {"name":"test2","password":"test2", "class": Admin}]
-    start(userlist)
-
-
+    internet.TCPServer(config.main.port, server.Site(root)).setServiceParent(top_service)
+    IroService().setServiceParent(top_service)
+    return top_service