Esempio n. 1
0
    def run(self):
        # load the configuration
        abspath = path.abspath(path.join(path.dirname(__file__), path.pardir))
        configfile = abspath + '/conf/smsgw.conf'
        gammucfg = abspath + '/conf/gammu.conf'
        cfg = SmsConfig(configfile)

        pidglobals.pidid = cfg.getvalue('pidid', 'pid-dummy', 'pid')
        smsgwglobals.pidlogger.debug("PisID: " + pidglobals.pidid)

        # Gammu Debug on/off
        gammudebug = cfg.getvalue('gammudebug', 'Off', 'pid')
        if gammudebug == "On":
            pidglobals.gammudebug = True

            todir = cfg.getvalue('logdirectory', abspath + '/logs/', 'pid')
            tofile = cfg.getvalue('gammudebugfile', 'gammu.log', 'pid')
            gammudebugfile = todir + tofile
            pidglobals.gammudebugfile = gammudebugfile
            smsgwglobals.pidlogger.debug("Gammu Debug on! Will log to " +
                                         str(pidglobals.gammudebugfile))
        else:
            pidglobals.gammudebug = False

        # Wrapping Gammu or not
        wrapgammu = cfg.getvalue('wrapgammu', 'Off', 'pid')
        if wrapgammu == "On":
            pidglobals.wrapgammu = True

            gammucmd = cfg.getvalue('gammucmd', 'Blank', 'pid')
            smsgwglobals.pidlogger.debug("Gammucmd: " + str(gammucmd))

            if gammucmd == "Blank":
                option = "gammucmd - is not set!"
                cfg.errorandexit(option)

            if path.isfile(gammucmd) or path.islink(gammucmd):
                # file or link exists all fine
                pidglobals.gammucmd = gammucmd
            else:
                # exit PID here as not Modem connection will work!
                option = "gammucmd - Command given not found!"
                cfg.errorandexit(option)
        else:
            pidglobals.wrapgammu = False

        smsgwglobals.pidlogger.debug("WrapGammu: " +
                                     str(pidglobals.wrapgammu))

        testmode = cfg.getvalue('testmode', 'Off', 'pid')
        if testmode == "On":
            # set testmode - content "ERROR" "SUCCESS" and "LONGWAIT" is
            # handled in a special way now
            pidglobals.testmode = True
        else:
            pidglobals.testmode = False
        smsgwglobals.pidlogger.debug("TestMode: " +
                                     str(pidglobals.testmode))

        retrypisurl = cfg.getvalue('retrypisurl', '2', 'pid')
        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "RetryPisUrl: " + retrypisurl)

        retrywait = cfg.getvalue('retrywait', '5', 'pid')
        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "RetryWait: " + retrywait)

        modemcfg = cfg.getvalue('modemlist', '[{}]', 'pid')

        try:
            # convert json to list of dictionary entries
            modemlist = json.loads(modemcfg)
        except:
            cfg.errorandexit("modemlist - not a valid JSON structure!")

        # check if modemcfg is set
        if 'modemid' not in modemlist[0]:
            # if len(modemlist) == 0:
            cfg.errorandexit("modemlist - not set!!!")
        else:
            # validate modem settings
            for modem in modemlist:
                try:
                    re.compile(modem['regex'])
                except:
                    cfg.errorandexit("modemlist - at " + modem['modemid'] +
                                     " - invalid regex!")

        # connect to USBModems and persist in pidglobals
        Modem.connectmodems(modemlist, gammucfg)

        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "ModemList: " +
                                     str(pidglobals.modemlist))
        if len(pidglobals.modemlist) == 0:
            errortext = "at any configured modem."
            cfg.errorandexit(errortext, 2)

        pisurlcfg = cfg.getvalue('pisurllist',
                                 '[{"url": "ws://127.0.0.1:7788"}]',
                                 'pid')
        # convert json to list of dictionary entries
        pisurllist = json.loads(pisurlcfg)
        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "PisUrlList: " +
                                     str(pisurllist))

        # endless try to connect to configured PIS
        # error: wait for some secs, then 1 retry, then next PID  in list
        curpis = 0
        tries = 1
        while True:
            try:
                if pidglobals.closingcode:
                    raise

                baseurl = pisurllist[curpis]['url']
                pisurl = baseurl + "/ws"
                smsgwglobals.pidlogger.info(pidglobals.pidid + ": " +
                                            "Try " + str(tries) + ": " +
                                            "Connecting to: " +
                                            pisurl)
                # init websocket client with heartbeat, 30 is fixed in all
                # modules wis/pis/pid
                ws = PidWsClient(pisurl,
                                 protocols=['http-only', 'chat'],
                                 heartbeat_freq=30)
                ws.connect()
                # set values for primary check in Websocket connection!
                # trim ws out of ws:/.. and add http:/
                pidglobals.curpisurl = "http" + baseurl[2:]
                pidglobals.primpisurl = "http" + pisurllist[0]['url'][2:]
                ws.run_forever()
            except KeyboardInterrupt:
                ws.close()
                # leave while loop
                break
            except Exception as e:
                # do retry except there is no more modem to communicate
                if (pidglobals.closingcode is None or
                   pidglobals.closingcode < 4000):

                    # try to reconnect
                    smsgwglobals.pidlogger.info(pidglobals.pidid + ": " +
                                                "Got a problem will reconnect "
                                                "in " + retrywait + " seconds.")
                    smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                                 "Problem is: " + str(e))
                    try:
                        time.sleep(int(retrywait))
                    except:
                        break

                    if tries < int(retrypisurl):
                        tries = tries + 1
                    else:
                        tries = 1
                        curpis = curpis + 1
                        if curpis == len(pisurllist):
                            curpis = 0
                    pidglobals.closingcode = None

                elif pidglobals.closingcode == 4001:
                    # go back to inital PID
                    # reset while parameter for pis and retries
                    smsgwglobals.pidlogger.info(pidglobals.pidid + ": " +
                                                "Going back to Prim PID")
                    curpis = 0
                    tries = 1
                    pidglobals.closingcode = None

                elif pidglobals.closingcode == 4000:
                    # leave while loop
                    # no connection to modem found!
                    break
Esempio n. 2
0
class SmsLogger(object):
    """Base class for Log handling. Creates a log-handler for each section
    in config file.

    Attributes:
        configfile -- absolut path to configuration file
                      to read relevant optionsi out of all sections..

                      loglevel = CRITICAL | ERROR | WARNING | INFO | DEBUG
                      logdirectory = absolut path to log directory
                                     fallback is local \logs directory
                      logfile = smsgw.log
    """
    __smsconfig = None
    __abspath = path.abspath(path.join(path.dirname(__file__), path.pardir))

    # Constructor
    def __init__(self, configfile=__abspath + '/conf/smsgw.conf'):
        # read SmsConfigs
        self.__smsconfig = SmsConfig(configfile)
        sections = self.__smsconfig.getsections()
        # print (type(sections))
        # print (sections)

        # prepare inital logger for each section in config file
        for section in sections:
            # print (section)
            # configer logger per section
            # handler values are -> 'console'
            #                    -> 'file'
            self.addHandler(section, 'console')
            self.addHandler(section, 'file')

    def addHandler(self, section, forhandler='console'):
        # set logger per section
        smslogger = logging.getLogger(section)

        # prepare format
        logFormatter = logging.Formatter("%(asctime)s [%(name)s:%(levelname)-5.5s]  %(message)s")

        # choose the right handler
        if forhandler == 'file':
            todir = self.__smsconfig.getvalue('logdirectory', self.__abspath + '/logs/', section)
            fbacktofile = section + '.log'
            tofile = self.__smsconfig.getvalue('logfile', fbacktofile, section)
            logfile = todir + tofile
            daysback = int(self.__smsconfig.getvalue('logfiledaysback', 7, section))
            handler = logging.handlers.TimedRotatingFileHandler(logfile,
                                                                when='midnight',
                                                                backupCount=daysback,
                                                                encoding='utf-8',
                                                                utc=True)
            # handler = logging.FileHandler(logfile, 'a', 'utf-8')
        # double ensure that default handler is StreamHandler
        else:
            handler = logging.StreamHandler()

        # set the format to the Handler
        handler.setFormatter(logFormatter)

        # add handler
        smslogger.addHandler(handler)

        # set log level
        loglevel = self.__smsconfig.getvalue('loglevel', 'WARNING', section)
        try:
            nummeric_level = getattr(logging, loglevel)
            smslogger.setLevel(nummeric_level)
            smslogger.debug('addHandler for (%s) handler (%s) done!', section, forhandler)
        except Exception:
            self.__smsconfig.errorandexit('loglevel')
Esempio n. 3
0
    def run(self):

        # load the configuration
        abspath = path.abspath(path.join(path.dirname(__file__), path.pardir))
        pid_env_config_id = os.getenv("PID_ID")
        configfile = abspath + '/conf/smsgw_' + str(pid_env_config_id) + '.conf' if pid_env_config_id else '/conf/smsgw.conf'
        cfg = SmsConfig(configfile)
        smsgwglobals.pidlogger.debug("PID Env ID: " + str(pid_env_config_id))
        smsgwglobals.pidlogger.debug("PID Config file: " + configfile)

        pidglobals.pidid = cfg.getvalue('pidid', 'pid-dummy', 'pid')
        smsgwglobals.pidlogger.debug("PidID: " + pidglobals.pidid)

        # Gammu Debug on/off
        gammudebug = cfg.getvalue('gammudebug', 'Off', 'pid')
        if gammudebug == "On":
            pidglobals.gammudebug = True

            todir = cfg.getvalue('logdirectory', abspath + '/logs/', 'pid')
            tofile = cfg.getvalue('gammudebugfile', 'gammu.log', 'pid')
            gammudebugfile = todir + tofile
            pidglobals.gammudebugfile = gammudebugfile
            smsgwglobals.pidlogger.debug("Gammu Debug on! Will log to " +
                                         str(pidglobals.gammudebugfile))
        else:
            pidglobals.gammudebug = False

        # Wrapping Gammu or not
        wrapgammu = cfg.getvalue('wrapgammu', 'Off', 'pid')
        if wrapgammu == "On":
            pidglobals.wrapgammu = True

            gammucmd = cfg.getvalue('gammucmd', 'Blank', 'pid')
            smsgwglobals.pidlogger.debug("Gammucmd: " + str(gammucmd))

            if gammucmd == "Blank":
                option = "gammucmd - is not set!"
                cfg.errorandexit(option)

            if path.isfile(gammucmd) or path.islink(gammucmd):
                # file or link exists all fine
                pidglobals.gammucmd = gammucmd
            else:
                # exit PID here as not Modem connection will work!
                option = "gammucmd - Command given not found!"
                cfg.errorandexit(option)
        else:
            pidglobals.wrapgammu = False

        smsgwglobals.pidlogger.debug("WrapGammu: " +
                                     str(pidglobals.wrapgammu))

        testmode = cfg.getvalue('testmode', 'Off', 'pid')
        if testmode == "On":
            # set testmode - content "ERROR" "SUCCESS" and "LONGWAIT" is
            # handled in a special way now
            pidglobals.testmode = True
        else:
            pidglobals.testmode = False
        smsgwglobals.pidlogger.debug("TestMode: " +
                                     str(pidglobals.testmode))

        retrypisurl = cfg.getvalue('retrypisurl', '2', 'pid')
        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "RetryPisUrl: " + retrypisurl)

        retrywait = cfg.getvalue('retrywait', '5', 'pid')
        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "RetryWait: " + retrywait)

        modemcfg = cfg.getvalue('modemlist', '[{}]', 'pid')

        try:
            # convert json to list of dictionary entries
            modemlist = json.loads(modemcfg)
        except:
            cfg.errorandexit("modemlist - not a valid JSON structure!")

        #Get carriers config
        carriercfg = cfg.getvalue('carrierscfg', '{}', 'pid')
        try:
            # convert json to list of dictionary entries
            pidglobals.carriersconfig = json.loads(carriercfg)
        except:
            cfg.errorandexit("carrierscfg - not a valid JSON structure!")

        # check if modemcfg is set
        if 'modemid' not in modemlist[0]:
            # if len(modemlist) == 0:
            cfg.errorandexit("modemlist - not set!!!")
        else:
            # validate modem settings
            for modem in modemlist:
                try:
                    re.compile(modem['regex'])
                except:
                    cfg.errorandexit("modemlist - at " + modem['modemid'] +
                                     " - invalid regex!")

        # connect to USBModems and persist in pidglobals
        Modem.connectmodems(modemlist)

        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "ModemList: " +
                                     str(pidglobals.modemlist))
        if len(pidglobals.modemlist) == 0:
            errortext = "at any configured modem."
            cfg.errorandexit(errortext, 2)

        pisurlcfg = cfg.getvalue('pisurllist',
                                 '[{"url": "ws://127.0.0.1:7788"}]',
                                 'pid')
        # convert json to list of dictionary entries
        pisurllist = json.loads(pisurlcfg)
        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "PisUrlList: " +
                                     str(pisurllist))

        # endless try to connect to configured PIS
        # error: wait for some secs, then 1 retry, then next PID  in list
        curpis = 0
        tries = 1
        while True:
            try:
                if pidglobals.closingcode:
                    raise

                baseurl = pisurllist[curpis]['url']
                pisurl = baseurl + "/ws"
                smsgwglobals.pidlogger.info(pidglobals.pidid + ": " +
                                            "Try " + str(tries) + ": " +
                                            "Connecting to: " +
                                            pisurl)
                # init websocket client with heartbeat, 30 is fixed in all
                # modules wis/pis/pid
                ws = PidWsClient(pisurl,
                                 protocols=['http-only', 'chat'],
                                 heartbeat_freq=30)
                ws.connect()
                # set values for primary check in Websocket connection!
                # trim ws out of ws:/.. and add http:/
                pidglobals.curpisurl = "http" + baseurl[2:]
                pidglobals.primpisurl = "http" + pisurllist[0]['url'][2:]
                ws.run_forever()
            except KeyboardInterrupt:
                ws.close()
                # leave while loop
                break
            except Exception as e:
                # do retry except there is no more modem to communicate
                if (pidglobals.closingcode is None or
                   pidglobals.closingcode < 4000):

                    # try to reconnect
                    smsgwglobals.pidlogger.info(pidglobals.pidid + ": " +
                                                "Got a problem will reconnect "
                                                "in " + retrywait + " seconds.")
                    smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                                 "Problem is: " + str(e))
                    try:
                        time.sleep(int(retrywait))
                    except:
                        break

                    if tries < int(retrypisurl):
                        tries = tries + 1
                    else:
                        tries = 1
                        curpis = curpis + 1
                        if curpis == len(pisurllist):
                            curpis = 0
                    pidglobals.closingcode = None

                elif pidglobals.closingcode == 4001:
                    # go back to inital PID
                    # reset while parameter for pis and retries
                    smsgwglobals.pidlogger.info(pidglobals.pidid + ": " +
                                                "Going back to Prim PID")
                    curpis = 0
                    tries = 1
                    pidglobals.closingcode = None

                elif pidglobals.closingcode == 4000:
                    # leave while loop
                    # no connection to modem found!
                    smsgwglobals.pidlogger.debug(pidglobals.pidid + ": Sleep 45 seconds before shutdown..." )
                    sleep(45)
                    break
                elif pidglobals.closingcode == 4005:
                    # leave while loop
                    # pid restart requested
                    break
                elif pidglobals.closingcode == 4010:
                    # leave while loop
                    # pid lost connection to the modem. Probably sim card ejected
                    # Or HEARTBEAT failed
                    break
Esempio n. 4
0
    def run(self):
        # load the configuration
        abspath = path.abspath(path.join(path.dirname(__file__), path.pardir))
        configfile = abspath + '/conf/smsgw.conf'
        gammucfg = abspath + '/conf/gammu.conf'
        print(configfile)
        cfg = SmsConfig(configfile)

        pidglobals.pidid = cfg.getvalue('pidid', 'pid-dummy', 'pid')
        smsgwglobals.pidlogger.debug("PisID: " + pidglobals.pidid)

        testmode = cfg.getvalue('testmode', 'Off', 'pid')
        if testmode == "On":
            # set testmode - content "ERROR" "SUCCESS" and "LONGWAIT" is
            # handled in a special way now
            pidglobals.testmode = True
        else:
            pidglobals.testmode = False
        smsgwglobals.pidlogger.debug("TestMode: " +
                                     str(pidglobals.testmode))

        retrypisurl = cfg.getvalue('retrypisurl', '2', 'pid')
        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "RetryPisUrl: " + retrypisurl)

        retrywait = cfg.getvalue('retrywait', '5', 'pid')
        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "RetryWait: " + retrywait)

        modemcfg = cfg.getvalue('modemlist', '[{}]', 'pid')


        # convert json to list of dictionary entries
        modemlist = json.loads(modemcfg)
        # check if modemcfg is set
        if not 'modemid' in modemlist[0]:
        #if len(modemlist) == 0:
            cfg.errorandexit("modemlist - not set!!!")

        # connect to USBModems and persist in pidglobals
        Modem.connectmodems(modemlist, gammucfg)

        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "ModemList: " +
                                     str(pidglobals.modemlist))

        pisurlcfg = cfg.getvalue('pisurllist',
                                 '[{"url": "ws://127.0.0.1:7788"}]',
                                 'pid')
        # convert json to list of dictionary entries
        pisurllist = json.loads(pisurlcfg)
        smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                     "PisUrlList: " +
                                     str(pisurllist))

        # endless try to connect to configured PIS
        # error: wait for some secs, then 1 retry, then next PID  in list
        curpis = 0
        tries = 1
        while True:
            try:
                if pidglobals.closingcode:
                    raise

                baseurl = pisurllist[curpis]['url']
                pisurl = baseurl + "/ws"
                smsgwglobals.pidlogger.info(pidglobals.pidid + ": " +
                                            "Try " + str(tries) + ": " +
                                            "Connecting to: " +
                                            pisurl)
                # init websocket client with heartbeat, 30 is fixed in all
                # modules wis/pis/pid
                ws = PidWsClient(pisurl,
                                 protocols=['http-only', 'chat'],
                                 heartbeat_freq=30)
                ws.connect()
                # set values for primary check in Websocket connection!
                # trim ws out of ws:/.. and add http:/
                pidglobals.curpisurl = "http" + baseurl[2:]
                pidglobals.primpisurl = "http" + pisurllist[0]['url'][2:]
                ws.run_forever()
            except KeyboardInterrupt:
                ws.close()
                # leave while loop
                break
            except Exception as e:
                # do retry except there is no more modem to communicate
                if (pidglobals.closingcode is None or
                   pidglobals.closingcode < 4000):

                    # try to reconnect
                    smsgwglobals.pidlogger.info(pidglobals.pidid + ": " +
                                                "Got a problem will reconnect "
                                                "in " + retrywait + " seconds.")
                    smsgwglobals.pidlogger.debug(pidglobals.pidid + ": " +
                                                 "Problem is: " + str(e))
                    try:
                        time.sleep(int(retrywait))
                    except:
                        break

                    if tries < int(retrypisurl):
                        tries = tries + 1
                    else:
                        tries = 1
                        curpis = curpis + 1
                        if curpis == len(pisurllist):
                            curpis = 0
                    pidglobals.closingcode = None

                elif pidglobals.closingcode == 4001:
                    # go back to inital PID
                    # reset while parameter for pis and retries
                    smsgwglobals.pidlogger.info(pidglobals.pidid + ": " +
                                                "Going back to Prim PID")
                    curpis = 0
                    tries = 1
                    pidglobals.closingcode = None

                elif pidglobals.closingcode == 4000:
                    # leave while loop
                    # no connection to modem found!
                    break