Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make the client more resilient #25

Merged
merged 2 commits into from
Jan 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 28 additions & 10 deletions unifi_respondd/respondd_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,17 @@ class SoftwareInfo:

firmware: FirmwareInfo


@dataclasses.dataclass
class InterfacesInfo:
other: List[str]


@dataclasses.dataclass
class IntInfo:
interfaces: InterfacesInfo


@dataclasses.dataclass
class NetworkInfo:
"""This class contains the network information of an AP.
Expand All @@ -79,10 +82,12 @@ class NetworkInfo:
mac: str
mesh: Dict[str, IntInfo]


@dataclasses.dataclass
class SystemInfo:
domain_code: str


@dataclass_json
@dataclasses.dataclass
class NodeInfo:
Expand Down Expand Up @@ -185,21 +190,25 @@ class StatisticsInfo:
gateway6: str
gateway_nexthop: str


@dataclasses.dataclass
class NeighbourDetails:
tq: int
lastseen: float


@dataclasses.dataclass
class Neighbours:
neighbours: Dict[str, NeighbourDetails]


@dataclass_json
@dataclasses.dataclass
class NeighboursInfo:
node_id: str
batadv: Dict[str, Neighbours]


class ResponddClient:
"""This class receives a request from the respondd server and returns the response."""

Expand Down Expand Up @@ -248,8 +257,13 @@ def getNodeInfos(self):
location=LocationInfo(latitude=ap.latitude, longitude=ap.longitude),
hardware=HardwareInfo(model=ap.model),
owner=OwnerInfo(contact=ap.contact),
network=NetworkInfo(mac=ap.mac,mesh={"bat0": IntInfo(interfaces=InterfacesInfo(other=[ap.mac]))}),
system=SystemInfo(domain_code=ap.domain_code)
network=NetworkInfo(
mac=ap.mac,
mesh={
"bat0": IntInfo(interfaces=InterfacesInfo(other=[ap.mac]))
},
),
system=SystemInfo(domain_code=ap.domain_code),
)
)
return nodes
Expand Down Expand Up @@ -295,12 +309,15 @@ def getNeighbours(self):
neighbours.append(
NeighboursInfo(
node_id=ap.mac.replace(":", ""),
batadv={ap.mac: Neighbours(
neighbours={ap.neighbour_mac: NeighbourDetails(
tq=255,
lastseen=0.45
)}
)}
batadv={
ap.mac: Neighbours(
neighbours={
ap.neighbour_mac: NeighbourDetails(
tq=255, lastseen=0.45
)
}
)
},
)
)
return neighbours
Expand All @@ -315,7 +332,6 @@ def listenMulticast(self):
def sendUnicast(self):
logger.info("Using unicast method")


timeSleep = int(60 - (self._timeStop - self._timeStart) % 60)
if self._config.verbose:
logger.debug("will now sleep " + str(timeSleep) + " seconds")
Expand Down Expand Up @@ -346,6 +362,8 @@ def start(self):
self.sendUnicast()
self._timeStart = time.time()
self._aps = unifi_client.get_infos()
if self._aps is None:
continue
if msgSplit[0] == "GET": # multi_request
for request in msgSplit[1:]:
responseStruct[request] = self.buildStruct(request)
Expand Down Expand Up @@ -375,7 +393,7 @@ def buildStruct(self, responseType):
responseClass = self._statistics
elif responseType == "nodeinfo":
responseClass = self._nodeinfos
elif responseType == 'neighbours':
elif responseType == "neighbours":
responseClass = self._neighbours
else:
logger.warning("unknown command: " + responseType)
Expand Down
46 changes: 32 additions & 14 deletions unifi_respondd/unifi_client.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
#!/usr/bin/env python3

from json import load
from geopy.point import Point
from pyunifi.controller import Controller
from typing import List
from geopy.geocoders import Nominatim
from unifi_respondd import config
from requests import get as rget
from unifi_respondd import logger
import time
import dataclasses
import re


ffnodes = None


@dataclasses.dataclass
class Accesspoint:
"""This class contains the information of an AP.
Expand Down Expand Up @@ -96,25 +98,31 @@ def get_location_by_address(address, app):
except:
return get_location_by_address(address)


def scrape(url):
"""returns remote json"""
try:
return rget(url).json()
except Exception as ex:
print('Error: %s' %(ex))
logger.error("Error: %s" % (ex))


def get_infos():
"""This function gathers all the information and returns a list of Accesspoint objects."""
cfg = config.Config.from_dict(config.load_config())
ffnodes = scrape(cfg.nodelist)
c = Controller(
host=cfg.controller_url,
username=cfg.username,
password=cfg.password,
port=cfg.controller_port,
version=cfg.version,
ssl_verify=cfg.ssl_verify,
)
try:
c = Controller(
host=cfg.controller_url,
username=cfg.username,
password=cfg.password,
port=cfg.controller_port,
version=cfg.version,
ssl_verify=cfg.ssl_verify,
)
except Exception as ex:
logger.error("Error: %s" % (ex))
return
geolookup = Nominatim(user_agent="ffmuc_respondd")
aps = Accesspoints(accesspoints=[])
for site in c.get_sites():
Expand Down Expand Up @@ -164,16 +172,24 @@ def get_infos():
pass
try:
neighbour_mac = cfg.offloader_mac.get(site["desc"], None)
offloader_id = cfg.offloader_mac.get(site["desc"], "").replace(':', '')
offloader = list(filter(lambda x:x["mac"]==cfg.offloader_mac.get(site["desc"], ""),ffnodes["nodes"]))[0]
offloader_id = cfg.offloader_mac.get(site["desc"], "").replace(
":", ""
)
offloader = list(
filter(
lambda x: x["mac"]
== cfg.offloader_mac.get(site["desc"], ""),
ffnodes["nodes"],
)
)[0]
except:
neighbour_mac = None
offloader_id = None
offloader = {}
pass
uplink = ap.get("uplink", None)
if uplink is not None and uplink.get("ap_mac", None) is not None:
neighbour_mac = uplink.get("ap_mac")
neighbour_mac = uplink.get("ap_mac")
aps.accesspoints.append(
Accesspoint(
name=ap.get("name", None),
Expand All @@ -200,7 +216,9 @@ def get_infos():
gateway6=offloader.get("gateway6", None),
gateway_nexthop=offloader_id,
neighbour_mac=neighbour_mac,
domain_code=offloader.get("domain", "ffmuc_unifi_respondd_fallback"),
domain_code=offloader.get(
"domain", "ffmuc_unifi_respondd_fallback"
),
)
)
return aps
Expand Down