Example #1
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()
Example #2
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}
Example #3
0
def updateifacestatus():

    import resource.pyiface.iface as pyiface
    from cupid.pilib import sqlitemultquery, setsinglevalue, systemdatadatabase, readonedbrow, gettimestring
    import subprocess

    netconfigdata = readonedbrow(systemdatadatabase, 'netconfig')[0]
    netstatus = readonedbrow(systemdatadatabase, 'netstatus')[0]
    # Networking check

    querylist = []
    table = 'netifaces'
    querylist.append('drop table if exists ' + table)
    querylist.append(
        "create table " + table + " (name text, hwaddr text, address text, ifaceindex integer, bcast text, mask text, flags text)")

    pilib.writedatedlogmsg(pilib.networklog, 'Reading ifaces with pyiface. ', 4, pilib.networkloglevel)

    allIfaces = pyiface.getIfaces()
    pilib.writedatedlogmsg(pilib.networklog, 'Got ifaces data. ', 5, pilib.networkloglevel)
    runquery=False
    for iface in allIfaces:
        runquery=True
        querylist.append(
            "insert into " + table + " values ( \'" + iface.name + "\' , \'" + iface.hwaddr + "\' , \'" + iface._Interface__sockaddrToStr(
                iface.addr) + "\' , \'" + str(iface.index) + "\' , \'" + iface._Interface__sockaddrToStr(
                iface.broadaddr) + "\' , \'" + iface._Interface__sockaddrToStr(
                iface.netmask) + "\' , \'" + pyiface.flagsToStr(iface.flags) + "\')")
    if runquery:
        pilib.writedatedlogmsg(pilib.networklog, 'Sending ifaces query. ', 5, pilib.networkloglevel)
        sqlitemultquery(systemdatadatabase, querylist)
    else:
        pilib.writedatedlogmsg(pilib.networklog, 'Empty ifaces query. ', 5, pilib.networkloglevel)


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


    # Interfaces check
    # WAN check
    pilib.writedatedlogmsg(pilib.networklog, 'Checking pingtimes. ', 4, pilib.networkloglevel)
    okping = float(netconfigdata['pingthreshold'])

    from netfun import runping
    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
        else:
            wanaccess = 0
        latency = pingresult
    querylist.append(pilib.makesinglevaluequery('netstatus', 'latency', str(latency)))

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


    # Check supplicant status, set on/offtime if necessary.
    wpastatusdict = netconfig.getwpaclientstatus()
    try:
        if wpastatusdict['wpa_state'] == 'COMPLETED':
            wpaconnected = 1
            if netstatus['connected'] == 0 or netstatus['onlinetime'] == '':
                pilib.writedatedlogmsg(pilib.networklog, 'setting online time', 2, pilib.networkloglevel)
                querylist.append(pilib.makesinglevaluequery('netstatus', 'onlinetime', gettimestring()))
                querylist.append(pilib.makesinglevaluequery('netstatus', 'offlinetime', ''))
        else:
            wpaconnected = 0
    except KeyError:
        wpaconnected = 0

    if wpaconnected == 0:
        if netstatus['connected'] == 1 or netstatus['offlinetime'] == '':
            if netconfigdata['mode'] == "station":
                pilib.writedatedlogmsg(pilib.networklog, 'setting offline time', 2, pilib.networkloglevel)
                querylist.append(pilib.makesinglevaluequery('netstatus', 'offlinetime', gettimestring()))
                querylist.append(pilib.makesinglevaluequery('netstatus', 'onlinetime', ''))
            else:
                pilib.writedatedlogmsg(pilib.networklog, 'setting online time', 2, pilib.networkloglevel)
                querylist.append(pilib.makesinglevaluequery('netstatus', 'offlinetime', ''))

    # Check dhcp server status
    pilib.writedatedlogmsg(pilib.networklog, 'Checking dhcp server status ', 4, pilib.networkloglevel)
    try:
        result = subprocess.Popen(['service', 'isc-dhcp-server', 'status'], stdout=subprocess.PIPE)
    except:
        dhcpstatus = 0
        pilib.writedatedlogmsg(pilib.networklog, 'Error in reading dhcp server status.', 1, pilib.networkloglevel)
    else:
        for line in result.stdout:
            if line.find('not running') > 0:
                dhcpstatus = 0
            elif line.find('is running') > 0:
                dhcpstatus = 1
            else:
                dhcpstatus = '\?'
    pilib.writedatedlogmsg(pilib.networklog, 'Done checking dhcp server status. ', 4, pilib.networkloglevel)

    pilib.writedatedlogmsg(pilib.networklog, 'Updating netstatus. ', 4, pilib.networkloglevel)

    wpastatusdict['connected'] = wpaconnected
    try:
        wpastatusdict['dhcpstatus'] = dhcpstatus
    except:
        wpastatusdict['dhcpstatus'] = 0
        dhcpstatus = 0
    try:
        mode = wpastatusdict['mode']
    except KeyError:
        mode = 'none'
    try:
        ssid = wpastatusdict['ssid']
    except KeyError:
        ssid = 'none'
    try:
        address = wpastatusdict['ip_address']
    except KeyError:
        address = 'none'

    # print('myaddress is ' + address)
    querylist.append(pilib.makesinglevaluequery('netstatus', 'dhcpstatus', dhcpstatus))
    querylist.append(pilib.makesinglevaluequery('netstatus', 'connected', str(wpaconnected)))
    if netconfigdata['mode'] in ['ap','tempap']:
        pilib.writedatedlogmsg(pilib.networklog, 'Updating netstatus to AP mode', 1, pilib.networkloglevel)
        querylist.append(pilib.makesinglevaluequery('netstatus', 'mode', netconfigdata['mode']))
        querylist.append(pilib.makesinglevaluequery('netstatus', 'SSID', 'cupidwifi'))
    else:
        pilib.writedatedlogmsg(pilib.networklog, 'Updating netstatus to station mode', 1, pilib.networkloglevel)
        querylist.append(pilib.makesinglevaluequery('netstatus', 'mode', str(mode)))
        querylist.append(pilib.makesinglevaluequery('netstatus', 'SSID', str(ssid)))
    querylist.append(pilib.makesinglevaluequery('netstatus', 'WANaccess', str(wanaccess)))
    querylist.append(pilib.makesinglevaluequery('netstatus', 'address', str(address)))

    pilib.writedatedlogmsg(pilib.networklog, 'Running netstatus query. ', 4, pilib.networkloglevel)
    pilib.sqlitemultquery(pilib.systemdatadatabase, querylist)
    pilib.writedatedlogmsg(pilib.networklog, 'Completed netstatus query. ', 4, pilib.networkloglevel)

    pilib.writedatedlogmsg(pilib.networklog, 'Completed netstatus update. ', 4, pilib.networkloglevel)

    return wpastatusdict
Example #4
0
def updateifacestatus():

    import resource.pyiface.iface as pyiface
    from cupid.pilib import sqlitemultquery, setsinglevalue, systemdatadatabase, readonedbrow, gettimestring
    import subprocess

    netconfigdata = readonedbrow(systemdatadatabase, 'netconfig')[0]
    netstatus = readonedbrow(systemdatadatabase, 'netstatus')[0]
    # Networking check

    querylist = []
    table = 'netifaces'
    querylist.append('drop table if exists ' + table)
    querylist.append(
        "create table " + table +
        " (name text, hwaddr text, address text, ifaceindex integer, bcast text, mask text, flags text)"
    )

    pilib.writedatedlogmsg(pilib.networklog, 'Reading ifaces with pyiface. ',
                           4, pilib.networkloglevel)

    allIfaces = pyiface.getIfaces()
    pilib.writedatedlogmsg(pilib.networklog, 'Got ifaces data. ', 5,
                           pilib.networkloglevel)
    runquery = False
    for iface in allIfaces:
        runquery = True
        querylist.append("insert into " + table + " values ( \'" + iface.name +
                         "\' , \'" + iface.hwaddr + "\' , \'" +
                         iface._Interface__sockaddrToStr(iface.addr) +
                         "\' , \'" + str(iface.index) + "\' , \'" +
                         iface._Interface__sockaddrToStr(iface.broadaddr) +
                         "\' , \'" +
                         iface._Interface__sockaddrToStr(iface.netmask) +
                         "\' , \'" + pyiface.flagsToStr(iface.flags) + "\')")
    if runquery:
        pilib.writedatedlogmsg(pilib.networklog, 'Sending ifaces query. ', 5,
                               pilib.networkloglevel)
        sqlitemultquery(systemdatadatabase, querylist)
    else:
        pilib.writedatedlogmsg(pilib.networklog, 'Empty ifaces query. ', 5,
                               pilib.networkloglevel)

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

    # Interfaces check
    # WAN check
    pilib.writedatedlogmsg(pilib.networklog, 'Checking pingtimes. ', 4,
                           pilib.networkloglevel)
    okping = float(netconfigdata['pingthreshold'])

    from netfun import runping
    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
        else:
            wanaccess = 0
        latency = pingresult
    querylist.append(
        pilib.makesinglevaluequery('netstatus', 'latency', str(latency)))

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

    # Check supplicant status, set on/offtime if necessary.
    wpastatusdict = netconfig.getwpaclientstatus()
    try:
        if wpastatusdict['wpa_state'] == 'COMPLETED':
            wpaconnected = 1
            if netstatus['connected'] == 0 or netstatus['onlinetime'] == '':
                pilib.writedatedlogmsg(pilib.networklog, 'setting online time',
                                       2, pilib.networkloglevel)
                querylist.append(
                    pilib.makesinglevaluequery('netstatus', 'onlinetime',
                                               gettimestring()))
                querylist.append(
                    pilib.makesinglevaluequery('netstatus', 'offlinetime', ''))
        else:
            wpaconnected = 0
    except KeyError:
        wpaconnected = 0

    if wpaconnected == 0:
        if netstatus['connected'] == 1 or netstatus['offlinetime'] == '':
            if netconfigdata['mode'] == "station":
                pilib.writedatedlogmsg(pilib.networklog,
                                       'setting offline time', 2,
                                       pilib.networkloglevel)
                querylist.append(
                    pilib.makesinglevaluequery('netstatus', 'offlinetime',
                                               gettimestring()))
                querylist.append(
                    pilib.makesinglevaluequery('netstatus', 'onlinetime', ''))
            else:
                pilib.writedatedlogmsg(pilib.networklog, 'setting online time',
                                       2, pilib.networkloglevel)
                querylist.append(
                    pilib.makesinglevaluequery('netstatus', 'offlinetime', ''))

    # Check dhcp server status
    pilib.writedatedlogmsg(pilib.networklog, 'Checking dhcp server status ', 4,
                           pilib.networkloglevel)
    try:
        result = subprocess.Popen(['service', 'isc-dhcp-server', 'status'],
                                  stdout=subprocess.PIPE)
    except:
        dhcpstatus = 0
        pilib.writedatedlogmsg(pilib.networklog,
                               'Error in reading dhcp server status.', 1,
                               pilib.networkloglevel)
    else:
        for line in result.stdout:
            if line.find('not running') > 0:
                dhcpstatus = 0
            elif line.find('is running') > 0:
                dhcpstatus = 1
            else:
                dhcpstatus = '\?'
    pilib.writedatedlogmsg(pilib.networklog,
                           'Done checking dhcp server status. ', 4,
                           pilib.networkloglevel)

    pilib.writedatedlogmsg(pilib.networklog, 'Updating netstatus. ', 4,
                           pilib.networkloglevel)

    wpastatusdict['connected'] = wpaconnected
    try:
        wpastatusdict['dhcpstatus'] = dhcpstatus
    except:
        wpastatusdict['dhcpstatus'] = 0
        dhcpstatus = 0
    try:
        mode = wpastatusdict['mode']
    except KeyError:
        mode = 'none'
    try:
        ssid = wpastatusdict['ssid']
    except KeyError:
        ssid = 'none'
    try:
        address = wpastatusdict['ip_address']
    except KeyError:
        address = 'none'

    # print('myaddress is ' + address)
    querylist.append(
        pilib.makesinglevaluequery('netstatus', 'dhcpstatus', dhcpstatus))
    querylist.append(
        pilib.makesinglevaluequery('netstatus', 'connected',
                                   str(wpaconnected)))
    if netconfigdata['mode'] in ['ap', 'tempap']:
        pilib.writedatedlogmsg(pilib.networklog,
                               'Updating netstatus to AP mode', 1,
                               pilib.networkloglevel)
        querylist.append(
            pilib.makesinglevaluequery('netstatus', 'mode',
                                       netconfigdata['mode']))
        querylist.append(
            pilib.makesinglevaluequery('netstatus', 'SSID', 'cupidwifi'))
    else:
        pilib.writedatedlogmsg(pilib.networklog,
                               'Updating netstatus to station mode', 1,
                               pilib.networkloglevel)
        querylist.append(
            pilib.makesinglevaluequery('netstatus', 'mode', str(mode)))
        querylist.append(
            pilib.makesinglevaluequery('netstatus', 'SSID', str(ssid)))
    querylist.append(
        pilib.makesinglevaluequery('netstatus', 'WANaccess', str(wanaccess)))
    querylist.append(
        pilib.makesinglevaluequery('netstatus', 'address', str(address)))

    pilib.writedatedlogmsg(pilib.networklog, 'Running netstatus query. ', 4,
                           pilib.networkloglevel)
    pilib.sqlitemultquery(pilib.systemdatadatabase, querylist)
    pilib.writedatedlogmsg(pilib.networklog, 'Completed netstatus query. ', 4,
                           pilib.networkloglevel)

    pilib.writedatedlogmsg(pilib.networklog, 'Completed netstatus update. ', 4,
                           pilib.networkloglevel)

    return wpastatusdict