Browse Source

style rework

Marcus Scharf 6 years ago
parent
commit
7743853c06
6 changed files with 90 additions and 78 deletions
  1. 2 2
      ext-respondd.py
  2. 28 24
      lib/neighbours.py
  3. 11 6
      lib/nodeinfo.py
  4. 15 15
      lib/respondd.py
  5. 20 22
      lib/respondd_client.py
  6. 14 9
      lib/statistics.py

+ 2 - 2
ext-respondd.py

@@ -18,8 +18,8 @@ options = vars(args)
 
 config = {}
 try:
-  with open("config.json", 'r') as cfg_handle:
-    config = json.load(cfg_handle)
+  with open("config.json", 'r') as fh:
+    config = json.load(fh)
 except IOError:
   raise
 

+ 28 - 24
lib/neighbours.py

@@ -11,11 +11,11 @@ class Neighbours(Respondd):
   def __init__(self, config):
     Respondd.__init__(self, config)
 
-  def getStationDump(self, dev_list):
+  def getStationDump(self, devList):
     j = {}
-    for dev in dev_list:
+
+    for dev in devList:
       try:
-        # iw dev ibss3 station dump
         output = subprocess.check_output(["iw", "dev", dev, "station", "dump"])
         output_utf8 = output.decode("utf-8")
         lines = output_utf8.splitlines()
@@ -30,32 +30,35 @@ class Neighbours(Respondd):
           else:
             ml = re.match(r"^[\t ]+([^:]+):[\t ]+([^ ]+)", line, re.I)
             if ml:
-              j[mac][ml.group(1)] = ml.group(2)
+              j[mac][ ml.group(1) ] = ml.group(2)
       except:
           pass
     return j
 
-  def getMesh_Interfaces(self):
+  def getMeshInterfaces(self, batmanDev):
     j = {}
-    output = subprocess.check_output(["batctl", "-m", self._config['batman'], "if"])
+
+    output = subprocess.check_output(["batctl", "-m", batmanDev, "if"])
     output_utf8 = output.decode("utf-8")
     lines = output_utf8.splitlines()
 
     for line in lines:
-      dev_re = re.match(r"^([^:]*)", line)
-      dev = dev_re.group(1)
+      ml = re.match(r"^([^:]*)", line)
+      dev = ml.group(1)
       j[dev] = lib.helper.getDevice_MAC(dev)
 
     return j
 
   def _get(self):
     j = {"batadv": {}}
+
     stationDump = None
+
     if 'mesh-wlan' in self._config:
       j["wifi"] = {}
       stationDump = self.getStationDump(self._config["mesh-wlan"])
 
-    mesh_ifs = self.getMesh_Interfaces()
+    meshInterfaces = self.getMeshInterfaces(self._config['batman'])
 
     output = subprocess.check_output(["batctl", "-m", self._config['batman'], "o", "-n"])
     output_utf8 = output.decode("utf-8")
@@ -67,32 +70,33 @@ class Neighbours(Respondd):
 
       if ml:
         dev = ml.group(5)
-        mac_origin = ml.group(1)
-        mac_nhop = ml.group(4)
+        macOrigin = ml.group(1)
+        macNexthop = ml.group(4)
         tq = ml.group(3)
         lastseen = ml.group(2)
 
-        if mac_origin == mac_nhop:
+        if macOrigin == macNexthop:
           if 'mesh-wlan' in self._config and dev in self._config["mesh-wlan"] and not stationDump is None:
-            if not mesh_ifs[dev] in j["wifi"]:
-              j["wifi"][mesh_ifs[dev]] = {}
-              j["wifi"][mesh_ifs[dev]]["neighbours"] = {}
+            if not meshInterfaces[dev] in j["wifi"]:
+              j["wifi"][ meshInterfaces[dev] ] = {}
+              j["wifi"][ meshInterfaces[dev] ]["neighbours"] = {}
 
-            if mac_origin in stationDump:
-              j["wifi"][mesh_ifs[dev]]["neighbours"][mac_origin] = {
-                "signal": stationDump[mac_origin]["signal"],
+            if macOrigin in stationDump:
+              j["wifi"][ meshInterfaces[dev] ]["neighbours"][macOrigin] = {
+                "signal": stationDump[macOrigin]["signal"],
                 "noise": 0, # TODO: fehlt noch
-                "inactive": stationDump[mac_origin]["inactive time"]
+                "inactive": stationDump[macOrigin]["inactive time"]
               }
 
-          if dev in mesh_ifs:
-            if not mesh_ifs[dev] in j["batadv"]:
-              j["batadv"][mesh_ifs[dev]] = {}
-              j["batadv"][mesh_ifs[dev]]["neighbours"] = {}
+          if dev in meshInterfaces:
+            if not meshInterfaces[dev] in j["batadv"]:
+              j["batadv"][ meshInterfaces[dev] ] = {}
+              j["batadv"][ meshInterfaces[dev] ]["neighbours"] = {}
 
-            j["batadv"][mesh_ifs[dev]]["neighbours"][mac_origin] = {
+            j["batadv"][ meshInterfaces[dev] ]["neighbours"][macOrigin] = {
               "tq": int(tq),
               "lastseen": float(lastseen)
             }
+
     return j
 

+ 11 - 6
lib/nodeinfo.py

@@ -13,8 +13,9 @@ class Nodeinfo(Respondd):
   def __init__(self, config):
     Respondd.__init__(self, config)
 
-  def getDevice_Addresses(self, dev):
+  def getDeviceAddresses(self, dev):
     l = []
+
     try:
       for ip6 in netif.ifaddresses(dev)[netif.AF_INET6]:
         raw6 = ip6['addr'].split('%')
@@ -28,9 +29,10 @@ class Nodeinfo(Respondd):
 
     return l
 
-  def getBat0_Interfaces(self):
+  def getBatmanInterfaces(self, dev):
     j = {}
-    output = subprocess.check_output(["batctl", "-m", self._config['batman'], "if"])
+
+    output = subprocess.check_output(["batctl", "-m", dev, "if"])
     output_utf8 = output.decode("utf-8")
     lines = output_utf8.splitlines()
 
@@ -65,22 +67,24 @@ class Nodeinfo(Respondd):
 
   def getCPUInfo(self):
     j = {}
+
     with open("/proc/cpuinfo", 'r') as fh:
       for line in fh:
         ml = re.match(r"^(.+?)[\t ]+:[\t ]+(.*)$", line, re.I)
 
         if ml:
           j[ml.group(1)] = ml.group(2)
+
     return j
 
   def _get(self):
     j = {
       "hostname": socket.gethostname(),
       "network": {
-        "addresses": self.getDevice_Addresses(self._config['bridge']),
+        "addresses": self.getDeviceAddresses(self._config['bridge']),
         "mesh": {
           "bat0": {
-            "interfaces": self.getBat0_Interfaces()
+            "interfaces": self.getBatmanInterfaces(self._config['batman'])
           }
         },
         "mac": lib.helper.getDevice_MAC(self._config["batman"])
@@ -118,6 +122,7 @@ class Nodeinfo(Respondd):
         }
       except:
         pass
-    return lib.helper.merge(j, self._aliases["nodeinfo"])
+
+    return lib.helper.merge(j, self._aliasOverlay["nodeinfo"])
 
 

+ 15 - 15
lib/respondd.py

@@ -8,40 +8,40 @@ import lib.helper
 class Respondd:
   def __init__(self, config):
     self._config = config
-    self._aliases = {}
+    self._aliasOverlay = {}
     try:
-      with open("alias.json", 'r') as cfg_handle:
-        self._aliases = json.load(cfg_handle)
+      with open("alias.json", 'r') as fh:
+        self._aliasOverlay = json.load(fh)
     except IOError:
       raise
       pass
 
   def getNode_ID(self):
-    if 'node_id' in self._aliases["nodeinfo"]:
-      return self._aliases["nodeinfo"]["node_id"]
+    if 'node_id' in self._aliasOverlay["nodeinfo"]:
+      return self._aliasOverlay["nodeinfo"]["node_id"]
     else:
       return lib.helper.getDevice_MAC(self._config["batman"]).replace(':', '')
 
-  def getStruct(self, root=None):
+  def getStruct(self, rootName=None):
     j = self._get()
     j['node_id'] = self.getNode_ID()
-    if not root is None:
+    if not rootName is None:
       j_tmp = j
       j = {}
-      j[root] = j_tmp
+      j[rootName] = j_tmp
     return j
 
-  def getJSON(self, root=None):
-    return bytes(json.dumps(self.getStruct(root), separators=(',', ':')), 'UTF-8')
+  def getJSON(self, rootName=None):
+    return bytes(json.dumps(self.getStruct(rootName), separators=(',', ':')), 'UTF-8')
 
-  def getJSONCompressed(self, root=None):
-    return self.compress(self.getJSON(root))
+  def getJSONCompressed(self, rootName=None):
+    return self.compress(self.getJSON(rootName))
 
   def compress(self, data):
     encoder = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) # The data may be decompressed using zlib and many zlib bindings using -15 as the window size parameter.
-    gzip_data = encoder.compress(data)
-    gzip_data = gzip_data + encoder.flush()
-    return gzip_data
+    dataGzip = encoder.compress(data)
+    dataGzip+= encoder.flush()
+    return dataGzip
 
   def _get(self):
     return {}

+ 20 - 22
lib/respondd_client.py

@@ -45,41 +45,39 @@ class ResponddClient:
   def start(self):
     while True:
       if select.select([self._sock], [], [], 1)[0]:
-        msg, sender = self._sock.recvfrom(2048)
-#        if options["verbose"]:
-#          print(msg)
+        msg, sourceAddress = self._sock.recvfrom(2048)
 
-        msg_spl = str(msg, 'UTF-8').split(" ")
+        msgSplit = str(msg, 'UTF-8').split(" ")
 
-        if msg_spl[0] == 'GET': # multi_request
-          for req in msg_spl[1:]:
-            self.sendResponse(sender, req, True)
+        if msgSplit[0] == 'GET': # multi_request
+          for request in msgSplit[1:]:
+            self.sendResponse(sourceAddress, request, True)
         else: # single_request
-          self.sendResponse(sender, msg_spl[0], False)
+          self.sendResponse(sourceAddress, msgSplit[0], False)
 
-  def sendResponse(self, sender, request, compress):
+  def sendResponse(self, destAddress, responseType, withCompression):
     if not self.__RateLimit is None and not self.__RateLimit.limit():
       print("rate limit reached!")
       return
 
-    response = None
-    if request == 'statistics':
-      response = self._statistics
-    elif request == 'nodeinfo':
-      response = self._nodeinfo
-    elif request == 'neighbours':
-      response = self._neighbours
+    responseClass = None
+    if responseType == 'statistics':
+      responseClass = self._statistics
+    elif responseType == 'nodeinfo':
+      responseClass = self._nodeinfo
+    elif responseType == 'neighbours':
+      responseClass = self._neighbours
     else:
-      print("unknown command: " + request)
+      print("unknown command: " + responseType)
       return
 
     if not self._config["dry_run"]:
-      if compress:
-        self._sock.sendto(response.getJSONCompressed(request), sender)
+      if withCompression:
+        self._sock.sendto(responseClass.getJSONCompressed(responseType), destAddress)
       else:
-        self._sock.sendto(response.getJSON(request), sender)
+        self._sock.sendto(responseClass.getJSON(responseType), destAddress)
 
     if self._config["verbose"] or self._config["dry_run"]:
-      print("%35s %5d %13s: " % (sender[0], sender[1], request), end='')
-      print(json.dumps(response.getStruct(request), sort_keys=True, indent=4))
+      print("%35s %5d %13s: " % (destAddress[0], destAddress[1], responseType), end='')
+      print(json.dumps(responseClass.getStruct(responseType), sort_keys=True, indent=4))
 

+ 14 - 9
lib/statistics.py

@@ -14,12 +14,13 @@ class Statistics(Respondd):
     Respondd.__init__(self, config)
 
   def getClients(self):
+    j = {"total": 0, "wifi": 0}
+
+    batmanMAC = lib.helper.getDevice_MAC(self._config['batman'])
+
     output = subprocess.check_output(["batctl", "-m", self._config['batman'], "tl", "-n"])
     output_utf8 = output.decode("utf-8")
     lines = output_utf8.splitlines()
-    batadv_mac = lib.helper.getDevice_MAC(self._config['batman'])
-
-    j = {"total": 0, "wifi": 0}
 
     for line in lines:
       # batman-adv -> translation-table.c -> batadv_tt_local_seq_print_text
@@ -33,7 +34,7 @@ class Statistics(Respondd):
       # * c0:11:73:b2:8f:dd   -1 [.P..W.]   1.710   (0xe680a836)
       ml = re.match(r"^\s\*\s([0-9a-f:]+)\s+-\d\s\[([RPNXWI\.]+)\]", line, re.I)
       if ml:
-        if not batadv_mac == ml.group(1): # Filter bat0
+        if not batmanMAC == ml.group(1): # Filter bat0
           if not ml.group(1).startswith('33:33:') and not ml.group(1).startswith('01:00:5e:'): # Filter Multicast
             j["total"] += 1
             if ml.group(2)[4] == 'W':
@@ -65,7 +66,8 @@ class Statistics(Respondd):
     )
 
   def getFastd(self):
-    fastd_data = b""
+    dataFastd = b""
+
     try:
       sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
       sock.connect(config["fastd_socket"])
@@ -77,13 +79,14 @@ class Statistics(Respondd):
       data = sock.recv(1024)
       if not data:
         break
-      fastd_data += data
+      dataFastd += data
 
     sock.close()
-    return json.loads(fastd_data.decode("utf-8"))
+    return json.loads(dataFastd.decode("utf-8"))
 
   def getMeshVPNPeers(self):
     j = {}
+
     if "fastd_socket" in self._config:
       fastd = self.getFastd()
       for peer in fastd["peers"].values():
@@ -99,10 +102,11 @@ class Statistics(Respondd):
       return None
 
   def getGateway(self):
+    j = None
+
     output = subprocess.check_output(["batctl", "-m", self._config['batman'], "gwl", "-n"])
     output_utf8 = output.decode("utf-8")
     lines = output_utf8.splitlines()
-    j = None
 
     for line in lines:
       gw_line = re.match(r"^(\*|=>) +([0-9a-f:]+) \([\d ]+\) ([0-9a-f:]+)", line)
@@ -133,6 +137,7 @@ class Statistics(Respondd):
 
     gateway = self.getGateway()
     if gateway != None:
-        j = lib.helper.merge(j, gateway)
+      j = lib.helper.merge(j, gateway)
+
     return j