penguidomd 6.47 KB
Newer Older
1 2
#!/usr/bin/env python
###########################################################################
3
# Copyright (c) 2018- Franco (nextime) Lanza <franco@nexlab.it>
4
#
5
# Penguidom System client Daemon "penguidomd"  [https://git.nexlab.net/domotika/Penguidom]
6
#
7
# This file is part of penguidom.
8
#
9
# penguidom is free software: you can redistribute it and/or modify
10 11 12 13 14 15 16 17 18 19 20 21 22 23
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) 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/>.
#
##############################################################################

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
from twisted.internet import epollreactor
epollreactor.install()


from twisted.internet import reactor, ssl, protocol, endpoints
from twisted.application import service, internet, app, reactors
from twisted.web import server 
import logging, time, sys, os
from nexlibs.daemonizer import Daemonizer
from penguidom import penguidom
from nexlibs.utils.genutils import configFile
from logging import handlers as loghandlers

try:
   import setproctitle
   setproctitle.setproctitle('penguidomd')
   print 'Setting process title to', sys.argv[0]
except:
   pass

loglevels = {
   'info': logging.INFO,
   'warning': logging.WARNING,
   'error': logging.ERROR,
   'critical': logging.CRITICAL,
   'debug': logging.DEBUG
}

#LOGLEN=104857600 # 100 mega
#LOGLEN=10485760 # 10 mega
LOGLEN=26214400 # 25 mega

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
from OpenSSL import SSL

class PenguiSSLContext(ssl.DefaultOpenSSLContextFactory):

   def cacheContext(self):
      if self._context is None:
         ctx = self._contextFactory(self.sslmethod)
         # Disallow SSLv2!  It's insecure!  SSLv3 has been around since
         # 1996.  It's time to move on.
         ctx.set_options(SSL.OP_NO_SSLv2)
         ctx.use_certificate_chain_file(self.certificateFileName)
         ctx.use_privatekey_file(self.privateKeyFileName)
         self._context = ctx


72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

class penguidomDaemon(Daemonizer):

  def __init__(self):
    self.curdir = os.path.abspath(os.path.dirname(sys.argv[0]))
    log.debug("Reading daemon Config file")
    self.daemoncfg = configFile(self.curdir+'/conf/penguidomd.conf')
    self.daemoncfg.readConfig()
    log.debug("Daemonizing process")
    Daemonizer.__init__(self, self.curdir+'/run/penguidom.pid')

  def main_loop(self):
    log.debug("Main loop called")
    application = service.Application("penguidomd")
    PENGUIDOMServerService = penguidom.penguidomService('penguidomd', curdir=self.curdir, config=self.daemoncfg)
    serviceCollection = service.IServiceCollection(application)
    PENGUIDOMServerService.setServiceParent(serviceCollection)


    IkapServerUDP = PENGUIDOMServerService.getIkapUDP()
    IkapServerTCP = PENGUIDOMServerService.getIkapTCP()
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    WebAuthServer = PENGUIDOMServerService.getAuthWebServer()
    privkey = self.daemoncfg.get('web', 'privkey')
    cacert = self.daemoncfg.get('web', 'cacert')
    if not privkey.startswith('/'): privkey="/".join([self.curdir, privkey])
    if not cacert.startswith('/'): cacert="/".join([self.curdir, cacert])
    sslContext = PenguiSSLContext(privkey, cacert)
    if str(self.daemoncfg.get('web', 'enable')).lower() in ['yes', '1', 'y','true']:
      reactor.listenSSL(int(self.daemoncfg.get('web', 'sslport')), WebAuthServer,
             contextFactory=sslContext,
             interface=str(self.daemoncfg.get('web', 'interface')))

      if not str(self.daemoncfg.get('web', 'sslonly')).lower() in ['yes', '1', 'y','true']:
         reactor.listenTCP(int(self.daemoncfg.get('web', 'port')), WebAuthServer,
                 interface=str(self.daemoncfg.get('web', 'interface')))

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

    if str(self.daemoncfg.get('ikap', 'enable')).lower() in ['yes', '1', 'y','true']:
      reactor.listenUDP(int(self.daemoncfg.get('ikap', 'port')), IkapServerUDP, 
            interface=str(self.daemoncfg.get('ikap', 'interface')))
      if self.daemoncfg.get('ikap', 'port') != self.daemoncfg.get('ikap', 'notifyport'):
         reactor.listenUDP(int(self.daemoncfg.get('ikap', 'notifyport')), IkapServerUDP,
            interface=str(self.daemoncfg.get('ikap', 'interface')))
    if str(self.daemoncfg.get('ikap', 'tcpenable')).lower() in ['yes', '1', 'y','true']:
      reactor.listenTCP(int(self.daemoncfg.get('ikap', 'tcpport')), IkapServerTCP,
            interface=str(self.daemoncfg.get('ikap', 'tcpinterface')))


    log.debug("Running reactor")
    reactor.callWhenRunning(PENGUIDOMServerService.isStarted)
    reactor.run()

if __name__ == "__main__":
   # Starting all loggers
   # file di log da 100 mega, per 5 rotazioni 
127 128
   LOGFORMAT='%(asctime)s => %(name)-12s: %(levelname)-8s %(message)s'
   formatter = logging.Formatter(LOGFORMAT)
129 130 131

   logdict={"corelog":
            {"file":"penguidom.log","name":[("Core","general")]},
132 133
            "weblog":
            {"file":"web.log","name":[("Webgui","web")]},
134 135
            "pluginslog":
            {"file":"plugins.log","name":[("Plugins","plugins")]},
136 137 138 139 140 141 142 143 144 145 146
           "protocollog":
            {"file":"ikap.log","name":
               [("IKAProtocol","ikap"),("IKAPServer","ikap"),("DMDomain","ikap")]},
           } 

   for l in logdict.keys():
      logdict[l]["handler"] = loghandlers.RotatingFileHandler(
         os.path.abspath(os.path.dirname(sys.argv[0]))+'/logs/'+logdict[l]["file"], 'a', LOGLEN, 5)
      logdict[l]["handler"].setLevel(logging.DEBUG)
      logdict[l]["handler"].setFormatter(formatter)

147
   logging.basicConfig(format=LOGFORMAT)
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163

   log = logging.getLogger( 'DaemonStarter' )
   log.addHandler(logdict["corelog"]["handler"])
   log.setLevel( logging.INFO )

   curdir = os.path.abspath(os.path.dirname(sys.argv[0]))

   daemoncfg = configFile(curdir+'/conf/penguidomd.conf')
   daemoncfg.readConfig()
   
   for l in logdict.keys():
      for n in logdict[l]["name"]:
         lh = logging.getLogger(n[0])
         lh.setLevel( loglevels[daemoncfg.get(n[1], 'loglevel')] )
         lh.addHandler( logdict[l]["handler"] )

164
   logging.basicConfig(format=LOGFORMAT)
165 166 167 168 169 170 171

   # staring the application
   if len(sys.argv) > 1:
      log.debug("Starting daemon with option "+sys.argv[1]) 
      penguidomDaemon().process_command_line(sys.argv)
   else:
      print 'Please specify start, stop or debug option'