Exemplo n.º 1
0
def runconfig(onboot=False):
    import subprocess
    try:
        netconfigdata = pilib.readonedbrow(pilib.systemdatadatabase, 'netconfig')[0]
        # print(netconfigdata)
    except:
        pilib.log(pilib.networklog, 'Error reading netconfig data. ', 0, pilib.networkloglevel)
    else:
        pilib.log(pilib.networklog, 'Successfully read netconfig data', 3, pilib.networkloglevel)

        pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'mode', netconfigdata['mode'])

        pilib.log(pilib.networklog, 'Netconfig is enabled', 3, pilib.networkloglevel)

        # This will grab the specified SSID and the credentials and update
        # the wpa_supplicant file
        updatewpasupplicant()

        # Copy the correct interfaces file
        if netconfigdata['mode'] == 'station':
            setstationmode(netconfigdata)
        elif netconfigdata['mode'] in ['ap', 'tempap', 'eth0wlan0bridge']:
            pilib.log(pilib.networklog, 'Setting eth0wlan0 bridge (or bare ap mode). ', 0, pilib.networkloglevel)
            subprocess.call(['/bin/cp', '/usr/lib/iicontrollibs/misc/interfaces/interfaces.ap', '/etc/network/interfaces'])
            killapservices()
            resetwlan()
            startapservices('wlan0')

        # All of these require ipv4 being enabled in /etc/sysctl.conf
        # First interface is DHCP, second is CuPIDwifi
        elif netconfigdata['mode'] == 'wlan0wlan1bridge':
            pilib.log(pilib.networklog, 'Setting wlan0wlan1 bridge', 0, pilib.networkloglevel)
            subprocess.call(['/bin/cp', '/usr/lib/iicontrollibs/misc/interfaces/interfaces.wlan0dhcp.wlan1cupidwifi', '/etc/network/interfaces'])
            killapservices()
            resetwlan('wlan0')
            resetwlan('wlan1')
            startapservices('wlan1')

        elif netconfigdata['mode'] == 'wlan1wlan0bridge':
            pilib.log(pilib.networklog, 'Setting wlan1wlan0 bridge', 0, pilib.networkloglevel)
            subprocess.call(['/bin/cp', '/usr/lib/iicontrollibs/misc/interfaces/interfaces.wlan1dhcp.wlan0cupidwifi', '/etc/network/interfaces'])
            killapservices()
            resetwlan('wlan0')
            resetwlan('wlan1')
            startapservices('wlan0')

        runIPTables(netconfigdata['mode'])
Exemplo n.º 2
0
def processapoverride(pin):
    pilib.log(pilib.networklog, "Reading GPIO override on pin " + str(pin) + '. ', 3, pilib.networkloglevel)
    pilib.log(pilib.syslog, "Reading GPIO override on pin " + str(pin) + '. ', 2, pilib.sysloglevel)

    import RPi.GPIO as GPIO
    import pilib

    try:
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    except:
        pilib.log(pilib.networklog, "Error reading GPIO", 3, pilib.networkloglevel)
    else:
        # jumper in place = input off, --> AP mode
        if not GPIO.input(pin):
            pilib.log(pilib.networklog, "GPIO On. Setting AP Mode.", 3, pilib.networkloglevel)
            pilib.setsinglevalue(pilib.systemdatadatabase, 'netconfig', 'mode', 'ap')
Exemplo n.º 3
0
def processsystemflags(systemflags=None):
    import pilib
    from pilib import log, syslog, sysloglevel

    if not systemflags:
        systemflags = pilib.readalldbrows(pilib.systemdatadatabase, 'systemflags')

    flagnames = []
    flagvalues = []
    for flag in systemflags:
        flagnames.append(flag['name'])
        flagvalues.append(flag['value'])

    stop = False
    if 'reboot' in flagnames:
        if flagvalues[flagnames.index('reboot')]:
            stop = True
            pilib.setsinglevalue(pilib.systemdatadatabase, 'systemflags', 'value', 0, "name='reboot'")
            import subprocess

            log(syslog, 'Rebooting for system flag', 0, sysloglevel)
            subprocess.call(['/sbin/reboot'])
    if 'netconfig' in flagnames:
        if flagvalues[flagnames.index('netconfig')]:
            stop = True
            pilib.setsinglevalue(pilib.systemdatadatabase, 'systemflags', 'value', 0, "name='netconfig'")
            from netconfig import runconfig

            log(syslog, 'Restarting network configuration', 0, sysloglevel)
            runconfig()
    if 'updateiicontrollibs' in flagnames and not stop:
        if flagvalues[flagnames.index('updateiicontrollibs')]:
            stop = True
            pilib.setsinglevalue(pilib.systemdatadatabase, 'systemflags', 'value', 0, 'name=\'updateiicontrollibs\'')
            from misc.gitupdatelib import updateiicontrollibs

            log(syslog, 'Updating iicontrollibs', 0, sysloglevel)
            updateiicontrollibs(True)
    if 'updatecupidweblib' in flagnames and not stop:
        if flagvalues[flagnames.index('updatecupidweblib')]:
            stop = True
            pilib.setsinglevalue(pilib.systemdatadatabase, 'systemflags', 'value', 0, 'name=\'updatecupidweblib\'')
            from misc.gitupdatelib import updatecupidweblib

            log(syslog, 'Updating cupidweblib', 0, sysloglevel)
            updatecupidweblib(True)
Exemplo n.º 4
0
def watchdoghamachi(pingip):
    from netfun import runping, restarthamachi, killhamachi
    import pilib
    try:
        # Turns out this is not going to work, as when it hangs, it hangs hard
        # hamachistatusdata = gethamachistatusdata()

        # So instead, we are going to test with a ping to another member on the network that
        # should always be online. This of course means that we have to make sure that it is, in fact, always
        # online

        pingtimes = runping(pingip, numpings=5)
        pingmax = max(pingtimes)
        pingmin = min(pingtimes)
        pingave = sum(pingtimes)/len(pingtimes)

        # if hamachistatusdata['status'] not in ['logged in']:
        if pingave == 0 or pingave > 3000:
            pilib.log(pilib.networklog, 'Pingtime unacceptable: ' + str(pingave) + '. ', 1, pilib.networkloglevel)
            pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'hamachistatus', 0)
            pilib.log(pilib.networklog, 'Restarting Hamachi. ', 1, pilib.networkloglevel)

            killhamachi()
            restarthamachi()
        else:
            if pingmax > 3000 or pingmin <= 0:
                pilib.log(pilib.syslog, 'Hamachi lives, with issues: ' + str(pingtimes), 3, pilib.sysloglevel)
            else:
                pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'hamachistatus', 1)
                pilib.log(pilib.networklog, 'Hamachi appears fine. ', 3, pilib.networkloglevel)

    except Exception as e:
        pilib.log(pilib.networklog, 'Error checking Hamachi with message:  ' + e.message, 1, pilib.networkloglevel)

        killhamachi()
        restarthamachi()
Exemplo n.º 5
0
    def onact(self):
        if self.actiontype == 'email':
            # process email action
            self.statusmsg += 'Processing email alert. '
            email = self.actiondetail
            message = 'Alert is active for ' + self.name + '. Criterion ' + self.variablename + ' in ' + self.tablename + ' has value ' + str(self.variablevalue) + ' with a criterion of ' + str(self.criterion) + ' with an operator of ' + self.operator + '. This alarm status has been on since ' + self.ontime + '.'
            subject = 'CuPID Alert : Alarm On - ' + self.name
            actionmail = pilib.gmail(message=message, subject=subject, recipient=email)
            actionmail.send()

        elif self.actiontype == 'indicator':
            # process indicator action
            self.statusmsg += 'Processing indicator on action. '
            indicatorname = self.actiondetail
            pilib.sqlitequery(pilib.controldatabase, 'update indicators set status=1 where name = \'' + indicatorname + '\'')

        elif self.actiontype == 'output':
            self.statusmsg += 'Processing output on action. '
            pilib.setsinglevalue(pilib.controldatabase, 'outputs', 'value', '1', condition='"id"=\'' + self.actiondetail +"'")

        # This should be the generic handler that we migrate to
        elif self.actiontype == 'setvalue':
            # to set a value, we need at minimum:
            #   dbname, tablename, valuename, setmethod and either:
            #   setmethod = increment, incrementvalue=1
            #   setmethod = value
            dbvndict = parsedbvn(self.actiondetail)
            dbpath = pilib.dbnametopath(dbvndict['dbname'])
            # Special set formula?

            if 'setvalueformula' in self.actiondatadict:
                # Stuff that we don't know yet.
                pilib.setsinglevalue(dbpath, dbvndict['tablename'], dbvndict['valuename'], 'formulastuff here', dbvndict['condition'])
            else:

                """ TODO: Fix this hack. We cannot currently single quote in the database entry because it breaks the reinsert.
                So for now, we have to add quotes on either side of the string literal before executing the sqlite query. """
                if dbvndict['condition']:
                    querycondition = dbvndict['condition'].split('=')[0] + "='" + dbvndict['condition'].split('=')[1] + "'"
                    # print('FIXED CONDITION')
                    # print(querycondition)
                else:
                    querycondition = None
                pilib.setsinglevalue(dbpath, dbvndict['tablename'], dbvndict['valuename'], '1', querycondition)
Exemplo n.º 6
0
def rundaemon(startall=False):
    from subprocess import Popen, PIPE
    from time import sleep
    from pilib import log, daemonlog, daemonloglevel

    # Set up list of enabled statuses (whether to restart if
    # we find that the process is not currently running

    picontrolenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select picontrolenabled from systemstatus')
    updateioenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select updateioenabled from systemstatus')
    systemstatusenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select systemstatusenabled from systemstatus')
    sessioncontrolenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select sessioncontrolenabled from systemstatus')
    serialhandlerenabled = pilib.sqlitedatumquery(pilib.controldatabase, 'select serialhandlerenabled from systemstatus')


    enableditemlist = [(int(updateioenabled)), (int(picontrolenabled)), int(systemstatusenabled), int(sessioncontrolenabled), int(serialhandlerenabled)]

    itemstatuses = findprocstatuses(pilib.daemonprocs)

    # Set system message
    systemstatusmsg = ''
    for name, enabled, status in zip(pilib.daemonprocs, enableditemlist, itemstatuses):
        systemstatusmsg += name + ' - Enabled: ' + str(enabled) + ' Status: ' + str(status) + '. '
        if pilib.daemonloglevel > 0:
            pilib.log(pilib.daemonlog, name + ' - Enabled: ' + str(enabled) + ' Status: ' + str(status) + '. ')

    pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'systemmessage', systemstatusmsg)

    # Set up list of itemnames in the systemstatus table that
    # we assign the values to when we detect if the process
    # is running or not

    statustableitemnames = ['updateiostatus', 'picontrolstatus', 'systemstatusstatus', 'sessioncontrolstatus', 'serialhandlerstatus']

    for index, item in enumerate(pilib.daemonprocs):
        # set status
        if itemstatuses[index]:
            pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 1')
            if pilib.daemonloglevel > 0:
                pilib.log(pilib.daemonlog, 'Process is running: ' + pilib.baselibdir + pilib.daemonprocs[index])
        else:
            pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 0')
            if pilib.daemonloglevel > 0:
                pilib.log(pilib.daemonlog, 'Process is not running: ' + pilib.baselibdir + pilib.daemonprocs[index])

            # run if set to enable
            if enableditemlist[index]:
                # print(pilib.baselibdir + pilib.daemonprocs[index])
                if pilib.daemonloglevel > 0:
                    pilib.log(pilib.daemonlog, 'Starting ' + pilib.baselibdir + pilib.daemonprocs[index])
                procresult = Popen([pilib.baselibdir + pilib.daemonprocs[index]], stdout=PIPE, stderr=PIPE)
                # if pilib.daemonloglevel > 0:
                #     pilib.writedatedlogmsg(pilib.daemonproclog, procresult.stdout.read())

    sleep(1)

    # Refresh after set
    itemstatuses = findprocstatuses(pilib.daemonprocs)
    for item in pilib.daemonprocs:
        index = pilib.daemonprocs.index(item)
        # set status
        if itemstatuses[index]:
            pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 1')
        else:
            pilib.sqlitequery(pilib.controldatabase, 'update systemstatus set ' + statustableitemnames[index] + ' = 0')

    # Set system message
    systemstatusmsg = ''
    for name, enabled, status in zip(pilib.daemonprocs, enableditemlist, itemstatuses):
        systemstatusmsg += name + ' - Enabled: ' + str(bool(enabled)) + ' Status: ' + str(status) + '. '
    pilib.setsinglevalue(pilib.controldatabase, 'systemstatus','systemmessage', systemstatusmsg)

    # Rotate all logs
    pilib.rotatelogs(pilib.networklog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.syslog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.iolog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.controllog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.daemonlog, pilib.numlogs, pilib.maxlogsize)
Exemplo n.º 7
0
import pilib
import updateio
from time import sleep

readtime = 10  # default, seconds

# Read from systemstatus to make sure we should be running
updateioenabled = pilib.getsinglevalue(pilib.controldatabase, 'systemstatus', 'updateioenabled')

while updateioenabled:

    pilib.log(pilib.iolog, 'Running periodicupdateio', 3, pilib.iologlevel)
    pilib.log(pilib.syslog, 'Running periodicupdateio', 3, pilib.sysloglevel)

    # Set last run time
    pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'lastinputpoll', pilib.gettimestring())
    pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'updateiostatus', '1')

    # Read and record everything as specified in controldatabase
    # Update database of inputs with read data

    # DEBUG
    runupdate = True
    if runupdate:
        reply = updateio.updateiodata(pilib.controldatabase)
    else:
        pilib.log(pilib.iolog,'DEBUG: Update IO disabled', 1, pilib.iologlevel)
        pilib.log(pilib.syslog,'DEBUG: Update IO disabled', 1, pilib.sysloglevel)


    result = pilib.readonedbrow(pilib.controldatabase, 'systemstatus', 0)
Exemplo n.º 8
0
def updateiodata(database, **kwargs):
    # This recreates all input and output tables based on the interfaces table.
    # Thus way we don't keep around stale data values. We could at some point incorporate
    # a retention feature that keeps them around in case they disappear temporarily.
    # It also reads the elements if they are enabled and it's time to read them

    import pilib
    import traceback

    if 'piobject' in kwargs:
        pi = kwargs['piobject']
    else:
        import pigpio
        pi = pigpio.pi()

    allowedGPIOaddresses = [18, 23, 24, 25, 4, 17, 27, 22, 5, 6, 13, 19, 26, 16, 20, 21]

    logconfig = pilib.getlogconfig()

    tables = pilib.gettablenames(pilib.controldatabase)
    if 'interfaces' in tables:
        interfaces = pilib.readalldbrows(pilib.controldatabase, 'interfaces')
    else:
        pilib.log(pilib.iolog, 'interfaces table not found. Exiting', 1,
                               logconfig['iologlevel'])
        return
    if 'inputs' in tables:
        previnputs = pilib.readalldbrows(pilib.controldatabase, 'inputs')

        # Make list of IDs for easy indexing
        previnputids = []
        for input in previnputs:
            previnputids.append(input['id'])
    else:
        previnputs = []
        previnputids = []

    if 'outputs' in tables:
        prevoutputs = pilib.readalldbrows(pilib.controldatabase, 'outputs')

        # Make list of IDs for easy indexing
        prevoutputids = []
        prevoutputvalues = []
        for output in prevoutputs:
            prevoutputids.append(output['id'])
            prevoutputvalues.append(output['value'])
    else:
        prevoutputs = {}
        prevoutputids = []

    if 'defaults' in tables:
        defaults = pilib.readalldbrows(pilib.controldatabase, 'defaults')[0]
        defaultinputpollfreq = defaults['inputpollfreq']
        defaultoutputpollfreq = defaults['outputpollfreq']
    else:
        defaults = []
        defaultinputpollfreq = 60
        defaultoutputpollfreq = 60

    if 'indicators' in tables:
        indicatornames = []
        previndicators = pilib.readalldbrows(pilib.controldatabase, 'indicators')
        for indicator in previndicators:
            indicatornames.append(indicator['name'])
    else:
        previndicators = []
        indicatornames = []

    # We drop all inputs and outputs and recreate
    # Add all into one query so there is no time when the IO don't exist.

    querylist = []
    querylist.append('delete from inputs')
    querylist.append('delete from outputs')

    # This is temporary. Clearing the table here and adding entries below can result in a gap in time
    # where there are no database indicator entries. This is not too much of a problem with indicators, as we
    # update the hardware explicitly after we add the entries. If the interface queries the table during
    # this period, however, we could end up with an apparently empty table.
    # TODO: FIX update on indicators in updateio

    # We drop this table, so that if SP1 has been disabled, the entries do not appear as valid indicators
    pilib.sqlitequery(pilib.controldatabase, 'delete from indicators')

    owfsupdate = False
    for interface in interfaces:
        if interface['interface'] == 'I2C':
            pilib.log(pilib.iolog, 'Processing I2C interface ' + interface['name'], 3,
                                   logconfig['iologlevel'])
            if interface['enabled']:
                pilib.log(pilib.iolog, 'I2C Interface ' + interface['name'] + ' enabled', 3,
                                       logconfig['iologlevel'])
                if interface['type'] == 'DS2483':
                    pilib.log(pilib.iolog, 'Interface type is DS2483', 3,
                                           logconfig['iologlevel'])
                    owfsupdate = True
            else:
                 pilib.log(pilib.iolog, 'I2C Interface ' + interface['name'] + ' disabled', 3,
                                       logconfig['iologlevel'])
        elif interface['interface'] == 'USB':
            pilib.log(pilib.iolog, 'Processing USB interface ' + interface['name'], 3,
                                   logconfig['iologlevel'])
            if interface['enabled']:
                pilib.log(pilib.iolog, 'USB Interface ' + interface['name'] + ' enabled', 3,
                                       logconfig['iologlevel'])
                if interface['type'] == 'DS9490':
                    pilib.log(pilib.iolog, 'Interface type is DS9490', 3,
                                           logconfig['iologlevel'])
                    owfsupdate = True
            else:
                 pilib.log(pilib.iolog, 'USB Interface ' + interface['name'] + ' disabled', 3,
                                       logconfig['iologlevel'])
        elif interface['interface'] == 'MOTE':

            #determine and then update id based on fields
            entryid = interface['interface'] + '_' + interface['type'] + '_' + interface['address']
            condition = '"interface"=\'' + interface['interface'] + '\' and "type"=\'' + interface['type'] + '\' and "address"=\'' + interface['address'] + '\''

            print(condition)
            pilib.setsinglevalue(pilib.controldatabase, 'interfaces', 'id', entryid, condition)

            pilib.log(pilib.iolog, 'Processing Mote interface' + interface['name'] + ', id:' + entryid, 3,
                                   logconfig['iologlevel'])
            if interface['enabled']:
                pilib.log(pilib.iolog, 'Mote Interface ' + interface['name'] + ', id:' + entryid + ' enabled', 3,
                                       logconfig['iologlevel'])

                # Grab mote entries from remotes table
                # nodeid and keyvalue are keyed into address in remotes table
                # keyvalues are :
                #   channel: channel number
                #   iovalue: ionumber
                #   owdev: ROM

                # This would look like, for example
                # 1:1 for a nodeid:channel scenario for a controller
                split = interface['address'].split(':')
                nodeid = split[0]
                keyvalue = split[1]

                # so we used to enable an interface and then take all entries from a node
                # Now, we have to explicitly add an interface for each device, unless the keychar * is used as the
                # keyvalue. This will allow us to insert all automatically, for example for owdevs or iovals from a
                # node.

                # This pulls out all mote entries that have nodeid and keyvalue that match the interface address
                # We should just find one, ideally
                if keyvalue == '*':
                    pass
                else:
                    condition = "\"nodeid\"='" + nodeid + "' and \"keyvalue\"='" + keyvalue + "'"
                    nodeentries = pilib.dynamicsqliteread(pilib.controldatabase, 'remotes', condition=condition)

                print("WE FOUND MOTE")
                print(condition)
                print(len(nodeentries))

                if interface['type'] == 'channel':
                    print('channel')
                    if len(nodeentries) == 1:
                        print('one entry found')

                        nodeentry = nodeentries[0]
                        nodedata = pilib.parseoptions(nodeentry['data'])

                        # Find existing channel so we can get existing data, settings, etc., and retain channel ordering
                        newchanneldata = {'name':interface['name'], 'controlvalue':nodedata['pv'], 'setpointvalue':nodedata['sv'],'controlvaluetime':pilib.gettimestring(), 'data':nodeentry['data'], 'type':'remote'}
                        newchannel = {}
                        existingchannels = pilib.readalldbrows(pilib.controldatabase, 'channels')
                        for channel in existingchannels:
                            if channel['name'] == interface['name']:
                                print('updating')
                                print(channel)
                                newchannel.update(channel)
                                print(newchannel)
                        newchannel.update(newchanneldata)
                        print(newchannel)

                        keys = []
                        values = []
                        for key, value in newchannel.iteritems():
                            keys.append(key)
                            values.append(value)


                        query = pilib.makesqliteinsert('channels',values, keys)
                        # print(query)
                        pilib.sqlitequery(pilib.controldatabase,query)
                    else:
                        print('multiple entries found for channel. not appropriate')
                else:
                    pass
                    # Create queries for table insertion
                    # TODO: process mote pollfreq, ontime, offtime
                    moteentries = []
                    for nodeentry in nodeentries:

                        # THis breaks out all of the strictly json-encoded data.
                        datadict = pilib.parseoptions(nodeentry['data'])
                        try:
                            entrytype = nodeentry['msgtype']

                            # now treat each mote type entry specially
                            # if entrytype == 'channel':

                            entryid = 'MOTE' + str(nodeentry['nodeid']) + '_' + nodeentry['keyvaluename'] + '_' + nodeentry['keyvalue']

                            entrymetareturn = pilib.dynamicsqliteread(pilib.controldatabase, 'ioinfo', condition="\"id\"='" + entryid + "'")
                            try:
                                entrymeta = entrymetareturn[0]
                            except:
                                entrymeta = []

                            # print(entrymeta)

                            entryoptions={}
                            if entrymeta:
                                entryname = entrymeta['name']
                                if entrymeta['options']:
                                    entryoptions = pilib.parseoptions(entrymeta['options'])
                            else:
                                entryname = '[MOTE' + str(nodeentry['nodeid']) + '] ' + nodeentry['keyvaluename'] + ':' + nodeentry['keyvalue']
                        except KeyError:
                            print('OOPS KEY ERROR')
                        else:
                            if entrytype == 'iovalue':
                                if 'scale' in entryoptions:
                                    entryvalue = str(float(entryoptions['scale']) * float(datadict['ioval']))
                                elif 'formula' in entryoptions:
                                    x = float(datadict['ioval'])
                                    try:
                                        entryvalue = eval(entryoptions['formula'])
                                    except:
                                        entryvalue = float(datadict['ioval'])
                                else:
                                    entryvalue = float(datadict['ioval'])
                            elif entrytype == 'owdev':
                                if 'owtmpasc' in datadict:
                                    if 'scale' in entryoptions:
                                        entryvalue = str(float(entryoptions['scale']) * float(datadict['owtmpasc']))
                                    elif 'formula' in entryoptions:
                                        x = float(datadict['owtmpasc'])
                                        try:
                                            entryvalue = eval(entryoptions['formula'])
                                        except:
                                            entryvalue = float(datadict['owtmpasc'])
                                    else:
                                        entryvalue = datadict['owtmpasc']
                                else:
                                    entryvalue = -1
                            else:
                                entryvalue = -1


                            moteentries.append('insert into inputs values (\'' + entryid + '\',\'' + interface['interface'] + '\',\'' +
                                interface['type'] + '\',\'' + str(address) + '\',\'' + entryname + '\',\'' + str(entryvalue) + "','','" +
                                 nodeentry['time'] + '\',\'' + str(15) + "','" + '' + "','" + '' + "')")
                    # print('querylist')
                    # print(moteentries)
                    querylist.extend(moteentries)

            else:
                pilib.log(pilib.iolog, 'Mote Interface ' + interface['name'] + ' disnabled', 3,
                                       logconfig['iologlevel'])
        elif interface['interface'] == 'LAN':
            pilib.log(pilib.iolog, 'Processing LAN interface' + interface['name'], 3,
                                   logconfig['iologlevel'])
            if interface['enabled']:
                pilib.log(pilib.iolog, 'LAN Interface ' + interface['name'] + ' enabled', 3,
                                       logconfig['iologlevel'])
                if interface['type'] == 'MBTCP':
                    pilib.log(pilib.iolog, 'Interface ' + interface['name'] + ' type is MBTCP',
                                           3, logconfig['iologlevel'])

                    try:
                        mbentries = processMBinterface(interface, prevoutputs, prevoutputids, previnputs, previnputids, defaults, logconfig)
                    except:
                        pilib.log(pilib.iolog,
                                               'Error processing MBTCP interface ' + interface['name'], 0,
                                               logconfig['iologlevel'])
                        errorstring = traceback.format_exc()
                        pilib.log(pilib.iolog,
                                               'Error of kind: ' + errorstring, 0,
                                               logconfig['iologlevel'])
                    else:
                        pilib.log(pilib.iolog,
                                               'Done processing MBTCP interface ' + interface['name'], 3,
                                               logconfig['iologlevel'])
                        querylist.extend(mbentries)
            else:
                pilib.log(pilib.iolog, 'LAN Interface ' + interface['name'] + ' disabled', 3,
                                       logconfig['iologlevel'])
        elif interface['interface'] == 'GPIO':
            try:
                address = int(interface['address'])
            except KeyError:
                pilib.log(pilib.iolog, 'GPIO address key not found for ' + interface['name'], 1,
                                       logconfig['iologlevel'])
                continue
            if interface['enabled']:

                pilib.log(pilib.iolog, 'Processing GPIO interface ' + str(interface['address']), 3,
                                       logconfig['iologlevel'])

                if address in allowedGPIOaddresses:
                    pilib.log(pilib.iolog, 'GPIO address' + str(address) + ' allowed. Processing.', 4,
                                           logconfig['iologlevel'])
                    GPIOentries = processGPIOinterface(interface, prevoutputs, prevoutputvalues, prevoutputids,
                                                               previnputs, previnputids, defaults, logconfig, piobject=pi)
                    if GPIOentries:
                                querylist.extend(GPIOentries)
                else:
                    pilib.log(pilib.iolog,
                                           'GPIO address' + str(address) + ' not allowed. Bad things can happen. ', 4,
                                           logconfig['iologlevel'])

            else:
                pilib.log(pilib.iolog, 'GPIO address' + str(address) + ' disabled. Doing nothing.', 4,
                                               logconfig['iologlevel'])
        elif interface['interface'] == 'SPI0':
            pilib.log(pilib.iolog, 'Processing SPI0', 1, logconfig['iologlevel'])
            if interface['enabled']:
                pilib.log(pilib.iolog, 'SPI0 enabled', 1, logconfig['iologlevel'])
                if interface['type'] == 'SPITC':
                    pilib.log(pilib.iolog, 'Processing SPITC on SPI0', 3, logconfig['iologlevel'])
                    import readspi

                    tcdict = readspi.getpigpioMAX31855temp(0,0)

                    # Convert to F for now
                    spitcentries = readspi.recordspidata(database, {'SPITC1' :tcdict['tctemp']*1.8+32})
                    querylist.extend(spitcentries)

                if interface['type'] == 'CuPIDlights':
                    import spilights

                    spilightsentries, setlist = spilights.getCuPIDlightsentries('indicators', 0, previndicators)
                    querylist.extend(spilightsentries)
                    spilights.updatelightsfromdb(pilib.controldatabase, 'indicators', 0)
                    spilights.setspilights(setlist, 0)
            else:
                pilib.log(pilib.iolog, 'SPI0 not enabled', 1, logconfig['iologlevel'])

        elif interface['interface'] == 'SPI1':
            pilib.log(pilib.iolog, 'Processing SPI1', 1, logconfig['iologlevel'])
            if interface['enabled']:
                pilib.log(pilib.iolog, 'SPI1 enabled', 1, logconfig['iologlevel'])
                if interface['type'] == 'CuPIDlights':
                    pilib.log(pilib.iolog, 'Processing CuPID Lights on SPI1', 1, logconfig['iologlevel'])
                    import spilights

                    spilightsentries, setlist = spilights.getCuPIDlightsentries('indicators', 1, previndicators)
                    querylist.extend(spilightsentries)
                    spilights.setspilights(setlist, 1)
            else:
                pilib.log(pilib.iolog, 'SPI1 disaabled', 1, logconfig['iologlevel'])

    # Set tables
    querylist.append(pilib.makesinglevaluequery('systemstatus', 'lastiopoll', pilib.gettimestring()))

    if owfsupdate:
        from owfslib import runowfsupdate
        pilib.log(pilib.iolog, 'Running owfsupdate', 1, logconfig['iologlevel'])
        devices, owfsentries = runowfsupdate(execute=False)
        querylist.extend(owfsentries)
    else:
        pilib.log(pilib.iolog, 'owfsupdate disabled', 3, logconfig['iologlevel'])

    pilib.log(pilib.iolog, 'Executing query:  ' + str(querylist), 5, logconfig['iologlevel'])
    try:
        # print(querylist)
        pilib.sqlitemultquery(pilib.controldatabase, querylist)
    except:
        errorstring = traceback.format_exc()
        pilib.log(pilib.iolog, 'Error executing query, message:  ' + errorstring, 0, logconfig['iologlevel'])
        pilib.log(pilib.errorlog, 'Error executing updateio query, message:  ' + errorstring)
        pilib.log(pilib.errorlog, 'Query:  ' + str(querylist))
Exemplo n.º 9
0
def runsystemstatus(runonce=False):
    import pilib
    import time
    import netconfig

    from misc.gitupdatelib import updategitversions

    # This doesn't update git libraries. It checks current versions and updates the database

    try:
        pilib.log(pilib.syslog, 'Checking git versions', 3, pilib.sysloglevel)
        updategitversions()
    except:
        pilib.log(pilib.syslog, 'Error in git version check', 0, pilib.sysloglevel)
    else:
        pilib.log(pilib.syslog, 'Git version check complete', 3, pilib.sysloglevel)

    systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0]

    ## Read wireless config via iwconfig
    # this is breaking systemstatus for some reason
    # updateiwstatus()

    ## Read current netstatus
    lastnetstatus={}
    try:
        lastnetstatus = pilib.readonedbrow(pilib.systemdatadatabase, 'netstatus')[0]
    except:
        pilib.log(pilib.networklog, 'Error reading network status. ', 1, pilib.networkloglevel)
    else:
        pilib.log(pilib.syslog, 'Completed network status. ', 3, pilib.networkloglevel)

    # Poll netstatus and return data
    allnetstatus = updatenetstatus(lastnetstatus)
    # wpastatusdict = allnetstatus['wpastatusdict']

    # Keep reading system status?
    while systemstatus['systemstatusenabled']:

        currenttime = pilib.gettimestring()
        pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'lastsystemstatuspoll', pilib.gettimestring())

        starttime = time.time()
        pilib.log(pilib.syslog, 'System status routine is starting. ', 3,
                               pilib.sysloglevel)

        """
        Check all network statuses. The goal here is to totally decouple status read and reconfigure
        When we need to check all status data, we'll have it either in a dict or dict array, or in a database table
        """

        if systemstatus['netstatusenabled']:
            pilib.log(pilib.syslog, 'Beginning network routines. ', 3, pilib.sysloglevel)

            # Update network interfaces statuses for all interfaces, in database tables as well
            # Check on wpa supplicant status as well. Function returns wpastatusdict
            try:
                pilib.log(pilib.syslog, 'Running updateifacestatus. ', 4, pilib.sysloglevel)
                pilib.log(pilib.networklog, 'Running updateifacestatus', 4, pilib.networkloglevel)
                allnetstatus = updatenetstatus(lastnetstatus)
            except:
                pilib.log(pilib.networklog, 'Exception in updateifacestatus. ')
            else:
                pilib.log(pilib.networklog, 'Updateifacestatus completed. ')

            pilib.log(pilib.syslog, 'Completed net status update. ', 4, pilib.sysloglevel)
        else:
            allnetstatus={'netstatusdict': {}, 'ifacesdictarray': {}}


        """
        End network configuration status
        """

        """
        Do we want to autoconfig the network? If so, we analyze our netstatus data against what should be going on,
        and translate this into a network status
        """
        if systemstatus['netconfigenabled'] and systemstatus['netstatusenabled']:

            # No need to get this fresh. We have it stored.
            netconfigdata = allnetstatus['netconfigdata']

            # We are going to hack in a jumper that sets AP configuration. This isn't the worst thing ever.
            if netconfigdata['apoverride']:
                result = processapoverride(21)

            ''' Now we check network status depending on the configuration we have selected '''
            ''' Now we check network status depending on the configuration we have selected '''
            pilib.log(pilib.syslog, 'Running interface configuration watchdog. ', 4,
                                   pilib.sysloglevel)
            pilib.log(pilib.networklog, 'Running interface configuration. Mode: ' + netconfigdata['mode'], 4,
                                   pilib.networkloglevel)

            result = watchdognetstatus()

        else:
            pilib.log(pilib.syslog, 'Netconfig disabled. ', 1, pilib.sysloglevel)
            pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'mode', 'manual')
            pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'statusmsg', 'netconfig is disabled')


        if systemstatus['checkhamachistatus']:
            pilib.log(pilib.syslog, 'Hamachi watchdog is enabled', 3, pilib.sysloglevel)
            pilib.log(pilib.networklog, 'Hamachi watchdog is enabled. ', 3, pilib.networkloglevel)

            # Only watchdog haamchi if we are connected to the network.
            netstatus = pilib.readonedbrow(pilib.systemdatadatabase, 'netstatus')[0]
            if netstatus['WANaccess']:
                pilib.log(pilib.syslog, 'We appear to be online. Checking Hamachi Status. ', 3, pilib.sysloglevel)
                pilib.log(pilib.networklog, 'We appear to be online. Checking Hamachi Status. ', 3, pilib.networkloglevel)
                watchdoghamachi(pingip='25.37.18.7')
            else:
                pilib.log(pilib.syslog, 'We appear to be offline. Not checking Hamachi Status. ', 3, pilib.sysloglevel)
                pilib.log(pilib.networklog, 'We appear to be offline. Not checking Hamachi Status. ', 3, pilib.networkloglevel)

        else:
            pilib.log(pilib.syslog, 'Hamachi watchdog is disnabled', 3, pilib.sysloglevel)

        pilib.log(pilib.syslog, 'Finished interface configuration. ', 4,
                               pilib.sysloglevel)
        # pilib.writedatedlogmsg(pilib.networklog, statusmsg)

        pilib.log(pilib.syslog, 'Running updateifacestatus. ', 4, pilib.sysloglevel)
        updatenetstatus()
        pilib.log(pilib.syslog, 'Completed updateifacestatus. ', 4, pilib.sysloglevel)

        pilib.log(pilib.syslog, 'Network routines complete. ', 3, pilib.sysloglevel)

        pilib.log(pilib.syslog, 'Checking system flags. ', 3, pilib.sysloglevel)
        processsystemflags()
        pilib.log(pilib.syslog, 'System flags complete. ', 3, pilib.sysloglevel)

        # Get system status again
        systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0]

        elapsedtime = int(time.time() - starttime)

        pilib.log(pilib.syslog, 'Status routines complete. Elapsed time: ' + str(elapsedtime), 3,
                               pilib.sysloglevel)

        pilib.log(pilib.syslog,
                               'System status is sleeping for ' + str(systemstatus['systemstatusfreq']) + '. ', 3,
                               pilib.sysloglevel)

        if runonce:
            break

        time.sleep(systemstatus['systemstatusfreq'])


    else:
        pilib.log(pilib.syslog, 'System status is disabled. Exiting. ', 0,
                               pilib.sysloglevel)
Exemplo n.º 10
0
def updatenetstatus(lastnetstatus=None):
    import pilib
    import time
    import subprocess
    from netfun import getifacestatus, getwpaclientstatus, getifconfigstatus

    netconfigdata = pilib.readonedbrow(pilib.systemdatadatabase, 'netconfig')[0]

    """ We get last netstatus so that we can save last online times, previous online status, etc. """

    if not lastnetstatus:
        try:
            lastnetstatus = pilib.readonedbrow(pilib.systemdatadatabase, 'netstatus')[0]
        except:
            pilib.log(pilib.syslog, 'Error reading netstatus. Attempting to recreate netstatus table with default values. ', 1, pilib.networkloglevel)
            try:
                pilib.emptyandsetdefaults(pilib.systemdatadatabase, 'netstatus')
                lastnetstatus = pilib.readonedbrow(pilib.systemdatadatabase, 'netstatus')[0]
            except:
                pilib.log(pilib.syslog, 'Error recreating netstatus. ', 1, pilib.networkloglevel)

    """ Pyiface is one way to read some iface data, but it doesn't always appear to show all interfaces(?!)
        So we wrote our own instead. A work in progress but quite functional at the moment. """

    pilib.log(pilib.networklog, 'Reading ifaces with ifconfig status. ', 4, pilib.networkloglevel)
    ifacesdictarray = getifconfigstatus()
    # ifacesdictarray = getifacestatus()

    """ We supplement with wpa status on the wlan interfaces """

    updateddictarray = []
    for interface in ifacesdictarray:
        if interface['name'].find('wlan') >= 0:
            interface['wpastate'] = pilib.dicttojson(getwpaclientstatus(interface['name']))
        else:
            interface['wpastate'] = ''
        updateddictarray.append(interface)
    ifacesdictarray = updateddictarray

    """ Then write it to the table """

    if ifacesdictarray:
        pilib.log(pilib.networklog, 'Sending ifaces query. ', 5, pilib.networkloglevel)
        # print(ifacesdictarray)
        pilib.insertstringdicttablelist(pilib.systemdatadatabase, 'netifaces', ifacesdictarray)
    else:
        pilib.log(pilib.networklog, 'Empty ifaces query. ', 2, pilib.networkloglevel)

    pilib.log(pilib.networklog, 'Completed pyiface ifaces. ', 4, pilib.networkloglevel)

    """ Now we check to see if we can connect to WAN """

    pilib.log(pilib.networklog, 'Checking pingtimes. ', 4, pilib.networkloglevel)
    okping = float(netconfigdata['pingthreshold'])

    from netfun import runping

    netstatusdict = {}

    querylist=[]
    pingresults = runping('8.8.8.8')

    # pingresults = [20, 20, 20]
    pingresult = sum(pingresults) / float(len(pingresults))

    if pingresult == 0:
        wanaccess = 0
        latency = 0
    else:
        if pingresult < okping:
            wanaccess = 1
            pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'WANaccess', 1)
            if lastnetstatus['WANaccess'] == 0 or not lastnetstatus['onlinetime']:
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'onlinetime', pilib.gettimestring())

        else:
            wanaccess = 0
            pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'WANaccess', 0)
            if lastnetstatus['WANaccess'] == 1 or not lastnetstatus['offlinetime']:
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'offlinetime', pilib.gettimestring())

        latency = pingresult

    # we set all the values here, so when we retreive it we get changed and also whatever else happens to be there.
    pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'latency', latency)
    updatetime = pilib.gettimestring()
    pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'updatetime', updatetime)
    pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'WANaccess', wanaccess)

    pilib.log(pilib.networklog, 'Done checking pings. ', 4, pilib.networkloglevel)

    if netconfigdata['netstatslogenabled']:
        # print('going to log stuff')
        pilib.logtimevaluedata(pilib.logdatabase, 'system_WANping', time.time(), pingresult, 1000,
                               netconfigdata['netstatslogfreq'])

    #This is kinda ugly. Should be fixed.
    # netstatusdict = {'WANaccess':wanaccess, 'latency': latency, 'updatetime': updatetime}
    netstatusdict = pilib.readonedbrow(pilib.systemdatadatabase, 'netstatus')[0]

    return {'netstatusdict': netstatusdict, 'ifacesdictarray': ifacesdictarray, 'netconfigdata':netconfigdata}
Exemplo n.º 11
0
def watchdognetstatus(allnetstatus=None):
    import pilib
    import netconfig
    import subprocess
    from cupiddaemon import pgrepstatus

    """
    And now comes the checking of configuration specific statuses and restarting them if enabled
    and necessary

    NOW
    Set number configuration types:
    eth0 is always dhcp

    if interface is not specified, it is assumed that the specified configuration applies to wlan0
    ap : access point on wlan0.
        Currently, address is hard-coded as 192.168.0.1 as set in hostapd (to have dhcp all on same subnet)
    station : station mode on wlan0
        IP address mode set in 'addtype' field. If DHCP, set as DHCP. If static, set as address field
    eth0wlan0bridge :
        wlan0 set as AP mode with bridge to eth0
    wlan0wlan1bridge :
        wlan0 set as station mode, wlan1 as ap mode with bridge
    wlan1wlan0bridge
        wlan1 set as station mode, wlan0 as ap mode with bridge

    IN THE FUTURE
    netconfigdata will have a row for each interface that needs to be configured.
    Each interface can be either static, dhcp, or ap.
    Each interface can also bridge, but this will be limited at first, due to the number of combinations.
    If bridge is selected, the mode will be checked, and the appropriate IPTables will be set based on which one is AP

    """

    if not allnetstatus:
        allnetstatus = updatenetstatus()

    netconfigdata = allnetstatus['netconfigdata']
    netstatus = allnetstatus['netstatusdict']

    # Refactor ifaces array. We could probably do this earlier and pass it around like this
    ifacedict = {}
    for iface in allnetstatus['ifacesdictarray']:
        # print(iface['name'])
        # print(iface)
        ifacedict[iface['name']] = iface

    # print(ifacedict)

    statusmsg = ''
    currenttime = pilib.gettimestring()

    runconfig = False
    if netconfigdata['mode'] in ['ap', 'tempap']:
        pilib.log(pilib.networklog, 'AP Mode is set. ', 1, pilib.networkloglevel)

        """

        THIS NEEDS TO BE REWRITTEN ( or absorbed into eth0wlan0bridge )

        """

        if netconfigdata['mode'] == 'tempap':
            timesincelastretry = pilib.timestringtoseconds(currenttime) - pilib.timestringtoseconds(netconfigdata['laststationretry'])
            pilib.log(pilib.networklog, 'TempAP mode: Time since last retry:  ' + str(timesincelastretry) + '. Station retry time: '
                                   + str(netconfigdata['stationretrytime']), 1, pilib.networkloglevel)

            if timesincelastretry > netconfigdata['stationretrytime']:
                # We go back to station mode
                statusmsg += 'Time to go back to station mode. '
                pilib.log(pilib.networklog, 'Time to go back to station mode. ', 1, pilib.networkloglevel)
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netconfig', 'mode', 'station')
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netconfig', 'laststationretry', '')
                netconfig.runconfig()
        else:
            # If we have ap up, do nothing

            if netstatus['dhcpstatus']:
                statusmsg += 'AP checked and ok. '
                pilib.log(pilib.networklog, 'AP checked and ok. ', 1, pilib.networkloglevel)
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'mode', 'ap')
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'SSID', 'cupidwifi')
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'offlinetime', '')

            # If we don't have dhcp up, restart ap mode
            # this will currently cause reboot if we don't set onboot=True
            # We set status message in case we change our minds and reboot here.
            else:
                statusmsg += 'Restarting AP. '
                pilib.log(pilib.networklog, 'Restarting AP mode. ', 1, pilib.networkloglevel)
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'statusmsg', statusmsg)
                netconfig.runconfig()

    #    Station Mode. Again, like above, this should be modular.

    elif netconfigdata['mode'] == 'station':

        pilib.log(pilib.networklog, 'Station mode is set. ', 3, pilib.networkloglevel)

        # Check station address (not yet implemented) and wpa status (implemented)
        stationinterface = 'wlan0'
        try:
            stationifacedata = ifacedict[stationinterface]
        except KeyError:
            pilib.log(pilib.networklog, 'No stationiface data(' + stationinterface + ') present for mode ' + netconfigdata['mode'], 1, pilib.networkloglevel)
            statusmsg += 'No stationiface data(' + stationinterface + ') present for mode ' + netconfigdata['mode']
            runconfig = True
        else:
            wpadata = pilib.parseoptions(stationifacedata['wpastate'])
            if wpadata['wpa_state'] == 'COMPLETED' and stationifacedata['address']:
                pilib.log(pilib.networklog, 'station interface ' + stationinterface + ' wpastatus appears ok with address ' + str(stationifacedata['address']), 3, pilib.networkloglevel)
            else:
                pilib.log(pilib.networklog, 'station interface for ' + stationinterface + ' does not appear ok judged by wpa_state: wpastate = ' + wpadata['wpa_state'] + ' address= ' + stationifacedata['address'], 1, pilib.networkloglevel)
                statusmsg += 'station interface does not appear ok judged by wpa_state. '
                runconfig = True

        # Should do special handling in here to verify address for static mode.

        # # If we have wpa up, do nothing
        # if int(netstatus['connected']):
        #     statusmsg += 'Station wpamode appears ok. '
        #     pilib.log(pilib.networklog, 'wpamode appears ok. ', 1, pilib.networkloglevel)
        #
        # # If wpa is not connected
        # else:
        #     statusmsg += 'Station wpamode appears disconnected. '
        #     pilib.log(pilib.networklog, 'wpamode appears disconnected. ', 1, pilib.networkloglevel)
        #
        #     if netstatus['offlinetime'] == '':
        #         pilib.log(pilib.networklog, 'Setting offline time for empty value. ', 4,
        #                                pilib.networkloglevel)
        #         pilib.setsinglevalue('netstatus', 'offlinetime', pilib.gettimestring())
        #         offlinetime = 0
        #     else:
        #         pilib.log(pilib.networklog, 'Calculating offline time. ', 4, pilib.networkloglevel)
        #         offlinetime = pilib.timestringtoseconds(currenttime) - pilib.timestringtoseconds(
        #             netstatus['offlinetime'])
        #
        #     pilib.log(pilib.networklog, 'wpa has been offline for ' + str(offlinetime) + '. ', 3,
        #                            pilib.networkloglevel)
        #     statusmsg += 'We have been offline for ' + str(offlinetime) + '. '
        #
        #     # If aprevert is aprevert or temprevert and we've been offline long enough, flip over to ap
        #     # then set offline time to now (otherwise this keeps happening)
        #     if netconfigdata['aprevert'] in ['temprevert', 'aprevert'] and offlinetime > netconfigdata[
        #         'apreverttime']:
        #
        #         # set laststationretry to currenttime. This marks when we flipped over to ap
        #         statusmsg += 'Setting last station retry time. '
        #         pilib.log(pilib.networklog, 'Reverting to AP mode', 3, pilib.networkloglevel)
        #         pilib.log(pilib.networklog,
        #                                'Setting last station retry time to ' + str(currenttime), 0,
        #                                pilib.networkloglevel)
        #         pilib.setsinglevalue(pilib.systemdatadatabase, 'netconfig', 'laststationretry', currenttime)
        #         pilib.setsinglevalue('netstatus', 'offlinetime', currenttime)
        #
        #         if netconfigdata['aprevert'] == 'aprevert':
        #             # set mode to ap
        #             statusmsg += 'Setting mode to ap. '
        #             pilib.log(pilib.networklog, 'Setting mode to ap ' + str(currenttime), 3,
        #                                    pilib.networkloglevel)
        #             pilib.setsinglevalue(pilib.systemdatadatabase, 'netconfig', 'mode', 'ap')
        #         elif netconfigdata['aprevert'] == 'temprevert':
        #             # set mode to tempap
        #             statusmsg += 'Setting mode to tempap. '
        #             pilib.log(pilib.networklog, 'Setting mode to tempap ' + str(currenttime), 3,
        #                                    pilib.networkloglevel)
        #             pilib.setsinglevalue(pilib.systemdatadatabase, 'netconfig', 'mode', 'tempap')
        #
        #         # Unfortunately, to revert to ap mode successfully, we currently have to reboot
        #         # this is built into the netconfig script - any time you set ap mode except at boot, it reboots
        #         pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'statusmsg', statusmsg)
        #         pilib.log(pilib.syslog, 'Running netconfig . ', 4,
        #                                pilib.sysloglevel)
        #         netconfig.runconfig()
        #     elif offlinetime > 15:
        #         pilib.log(pilib.syslog, 'Restarting netconfig on bad wpastatus', 1,
        #                                pilib.sysloglevel)
        #         runconfig = True
        #
        #     # Here, we need to check the ifaces address. Netstatus address is ambiguous
        #     if netstatus['ip_address'] != netconfigdata['address']:
        #         pilib.log(pilib.networklog, 'IP address mismatch ( Configured for ' + netconfigdata['address'] + '. Reporting' + netstatus['ip_address'] + ' ). Running config.', 1, pilib.networkloglevel)
        #         runconfig = True
        #     else:
        #         pilib.log(pilib.networklog, 'IP address match for ' + netconfigdata['address'] + '. ', 3, pilib.networkloglevel)

    elif netconfigdata['mode'] == 'eth0wlan0bridge':

        # We don't actually check eth0. This is because we shouldn't have to. Also, if we don't check on eth0, we can
        # use the same mode for wlan0 AP and eth0wlan0 bridge. Hot plug, works fine.

        # Check wlan0 dhcp and hostapd status
        try:
            wlan0ifacedata =ifacedict['wlan0']
        except KeyError:
            pilib.log(pilib.networklog, 'No wlan0 data present in configuration of eth0wlan0bridge. ', 1, pilib.networkloglevel)
            statusmsg += 'wlan0 data is not present. '
            runconfig = True
        else:
            pilib.log(pilib.networklog, 'Checking dhcp server status on wlan0. ', 4, pilib.networkloglevel)
            try:
                result = subprocess.check_output(['/usr/sbin/service', 'isc-dhcp-server', 'status'], stderr=subprocess.PIPE)
            except Exception, e:
                # If not running, the subprocess call will throw an error
                pilib.log(pilib.networklog, 'Error in reading dhcp server status. Assumed down. ', 1, pilib.networkloglevel)
                statusmsg += 'dhcp server appears down. '
                runconfig = True
            else:
                pilib.log(pilib.networklog, 'DHCP server appears to be up. ', 1,  pilib.networkloglevel)

            """ Check ifconfig ipaddress for wlan0
                This should be programmable. """

            if wlan0ifacedata['address'] == '192.168.0.1':
                pilib.log(pilib.networklog, 'wlan0 address is appears to be set properly:  ' + str(wlan0ifacedata['address']), 3, pilib.networkloglevel)
            else:
                pilib.log(pilib.networklog, 'wlan0 address is not set properly:  ' + str(wlan0ifacedata['address']), 1, pilib.networkloglevel)
                statusmsg += 'wlan0 address does not appear ok. '
                runconfig = True

            if pgrepstatus('hostapd.*wlan0')['count'] == 1:
                pilib.log(pilib.networklog, 'hostapd on wlan0 appears to be ok. ', 3, pilib.networkloglevel)
            else:
                pilib.log(pilib.networklog, 'hostapd on wlan0 does NOT appear to be ok. ', 1, pilib.networkloglevel)
                statusmsg += 'wlan0 hostpad does not appear ok. '
                runconfig=True
Exemplo n.º 12
0
                print('netstatus ERROR')
                pilib.log(pilib.networklog, 'Error gettng offlinetime. ', 2, pilib.networkloglevel)

            offlineperiod = pilib.timestringtoseconds(pilib.gettimestring()) - pilib.timestringtoseconds(offlinetime)
            pilib.log(pilib.networklog, 'We have been offline for ' + str(offlineperiod))
            if offlineperiod > int(netconfigdata['WANretrytime']):
                pilib.log(pilib.networklog, 'Offline period of ' + str(offlineperiod) + ' has exceeded retry time of ' + str(int(netconfigdata['WANretrytime'])))
                # Note that although we obey this period once, after we start this process we don't reset the offlinetime,
                # so it will just continue to run. This is good in a way, as it will continually set the netstateok to bad,
                # which will eventually cause us to reboot

                # We do reset the WAN offline time in the reboot sequence, hwoever.

                restarts = int(pilib.getsinglevalue(pilib.systemdatadatabase, 'netstatus','WANaccessrestarts'))
                restarts += 1
                pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'WANaccessrestarts', restarts)

                pilib.log(pilib.networklog, 'Going to run netconfig to correct WAN access.')
            else:
                pilib.log(pilib.networklog, 'Not yet time to run netconfig to correct WAN access. Retry time set at ' + str(netconfigdata['WANretrytime']))
                runconfig = True
        else:
            pilib.log(pilib.networklog, 'WANAccess is fine. ')

    if runconfig:
        # Set bad status in netstatus
        pilib.setsinglevalue(pilib.systemdatadatabase, 'netstatus', 'netstate', 0)

        # Set ok time to '' to trigger rewrite next time status is ok
        lastoktime = pilib.getsinglevalue(pilib.systemdatadatabase, 'netstatus', 'netstateoktime')
        if not lastoktime:
Exemplo n.º 13
0
def rundaemon(startall=False):
    from subprocess import Popen, PIPE
    from time import sleep
    from pilib import writedatedlogmsg, daemonlog, daemonloglevel

    # Set up list of enabled statuses (whether to restart if
    # we find that the process is not currently running

    picontrolenabled = pilib.sqlitedatumquery(
        pilib.controldatabase, 'select picontrolenabled from systemstatus')
    updateioenabled = pilib.sqlitedatumquery(
        pilib.controldatabase, 'select updateioenabled from systemstatus')
    systemstatusenabled = pilib.sqlitedatumquery(
        pilib.controldatabase, 'select systemstatusenabled from systemstatus')
    sessioncontrolenabled = pilib.sqlitedatumquery(
        pilib.controldatabase,
        'select sessioncontrolenabled from systemstatus')
    serialhandlerenabled = pilib.sqlitedatumquery(
        pilib.controldatabase, 'select serialhandlerenabled from systemstatus')

    enableditemlist = [(int(updateioenabled)), (int(picontrolenabled)),
                       int(systemstatusenabled),
                       int(sessioncontrolenabled),
                       int(serialhandlerenabled)]

    itemstatuses = findprocstatuses(pilib.daemonprocs)

    # Set system message
    systemstatusmsg = ''
    for name, enabled, status in zip(pilib.daemonprocs, enableditemlist,
                                     itemstatuses):
        systemstatusmsg += name + ' - Enabled: ' + str(
            enabled) + ' Status: ' + str(status) + '. '
        if pilib.daemonloglevel > 0:
            pilib.writedatedlogmsg(
                pilib.daemonlog, name + ' - Enabled: ' + str(enabled) +
                ' Status: ' + str(status) + '. ')

    pilib.setsinglevalue(pilib.controldatabase, 'systemstatus',
                         'systemmessage', systemstatusmsg)

    # Set up list of itemnames in the systemstatus table that
    # we assign the values to when we detect if the process
    # is running or not

    statustableitemnames = [
        'updateiostatus', 'picontrolstatus', 'systemstatusstatus',
        'sessioncontrolstatus', 'serialhandlerstatus'
    ]

    for index, item in enumerate(pilib.daemonprocs):
        # set status
        if itemstatuses[index]:
            pilib.sqlitequery(
                pilib.controldatabase, 'update systemstatus set ' +
                statustableitemnames[index] + ' = 1')
            if pilib.daemonloglevel > 0:
                pilib.writedatedlogmsg(
                    pilib.daemonlog, 'Process is running: ' +
                    pilib.baselibdir + pilib.daemonprocs[index])
        else:
            pilib.sqlitequery(
                pilib.controldatabase, 'update systemstatus set ' +
                statustableitemnames[index] + ' = 0')
            if pilib.daemonloglevel > 0:
                pilib.writedatedlogmsg(
                    pilib.daemonlog, 'Process is not running: ' +
                    pilib.baselibdir + pilib.daemonprocs[index])

            # run if set to enable
            if enableditemlist[index]:
                print(pilib.baselibdir + pilib.daemonprocs[index])
                if pilib.daemonloglevel > 0:
                    pilib.writedatedlogmsg(
                        pilib.daemonlog, 'Starting ' + pilib.baselibdir +
                        pilib.daemonprocs[index])
                procresult = Popen(
                    [pilib.baselibdir + pilib.daemonprocs[index]], stdout=PIPE)
                # if pilib.daemonloglevel > 0:
                #     pilib.writedatedlogmsg(pilib.daemonproclog, procresult.stdout.read())

    sleep(1)

    # Refresh after set
    itemstatuses = findprocstatuses(pilib.daemonprocs)
    for item in pilib.daemonprocs:
        index = pilib.daemonprocs.index(item)
        # set status
        if itemstatuses[index]:
            pilib.sqlitequery(
                pilib.controldatabase, 'update systemstatus set ' +
                statustableitemnames[index] + ' = 1')
        else:
            pilib.sqlitequery(
                pilib.controldatabase, 'update systemstatus set ' +
                statustableitemnames[index] + ' = 0')

    # Set system message
    systemstatusmsg = ''
    for name, enabled, status in zip(pilib.daemonprocs, enableditemlist,
                                     itemstatuses):
        systemstatusmsg += name + ' - Enabled: ' + str(
            bool(enabled)) + ' Status: ' + str(status) + '. '
    pilib.setsinglevalue(pilib.controldatabase, 'systemstatus',
                         'systemmessage', systemstatusmsg)

    # Rotate all logs
    pilib.rotatelogs(pilib.networklog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.systemstatuslog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.iolog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.controllog, pilib.numlogs, pilib.maxlogsize)
    pilib.rotatelogs(pilib.daemonlog, pilib.numlogs, pilib.maxlogsize)
Exemplo n.º 14
0
    else:
        pilib.writedatedlogmsg(pilib.systemstatuslog, 'Git version check complete', 3, pilib.systemstatusloglevel)


    systemstatus = pilib.readalldbrows(pilib.controldatabase, 'systemstatus')[0]

    # Keep reading system status?
    while systemstatus['systemstatusenabled']:

        starttime = time.time()
        pilib.writedatedlogmsg(pilib.systemstatuslog, 'System status routine is starting. ', 3, pilib.systemstatusloglevel)

        pilib.writedatedlogmsg(pilib.systemstatuslog, 'Beginning network routines. ', 3, pilib.systemstatusloglevel)

        currenttime = pilib.gettimestring()
        pilib.setsinglevalue(pilib.controldatabase, 'systemstatus', 'lastsystemstatuspoll', pilib.gettimestring())

        pilib.writedatedlogmsg(pilib.systemstatuslog, 'Running updateifacestatus. ', 4, pilib.systemstatusloglevel)

        # Update network interfaces statuses for all interfaces, in database tables as well
        # Check on wpa supplicant status as well. Function returns wpastatusdict
        try:
            pilib.writedatedlogmsg(pilib.networklog, 'Running updateifacestatus', 4, pilib.networkloglevel)
            wpastatusdict = updateifacestatus()
        except:
            pilib.writedatedlogmsg(pilib.networklog, 'Exception in updateifacestatus. ')
        else:
            pilib.writedatedlogmsg(pilib.networklog, 'Updateifacestatus completed. ')

        pilib.writedatedlogmsg(pilib.systemstatuslog, 'Completed updateifacestatus. ', 4, pilib.systemstatusloglevel)
Exemplo n.º 15
0
                                       'systemstatus')[0]

    # Keep reading system status?
    while systemstatus['systemstatusenabled']:

        starttime = time.time()
        pilib.writedatedlogmsg(pilib.systemstatuslog,
                               'System status routine is starting. ', 3,
                               pilib.systemstatusloglevel)

        pilib.writedatedlogmsg(pilib.systemstatuslog,
                               'Beginning network routines. ', 3,
                               pilib.systemstatusloglevel)

        currenttime = pilib.gettimestring()
        pilib.setsinglevalue(pilib.controldatabase, 'systemstatus',
                             'lastsystemstatuspoll', pilib.gettimestring())

        pilib.writedatedlogmsg(pilib.systemstatuslog,
                               'Running updateifacestatus. ', 4,
                               pilib.systemstatusloglevel)

        # Update network interfaces statuses for all interfaces, in database tables as well
        # Check on wpa supplicant status as well. Function returns wpastatusdict
        try:
            pilib.writedatedlogmsg(pilib.networklog,
                                   'Running updateifacestatus', 4,
                                   pilib.networkloglevel)
            wpastatusdict = updateifacestatus()
        except:
            pilib.writedatedlogmsg(pilib.networklog,
                                   'Exception in updateifacestatus. ')