Skip to content
Cannot retrieve contributors at this time
152 lines (124 sloc) 4.76 KB
# This script can be used to dynamically update your ffapi-json-file with
# the number of currently running nodes.
# The number of running nodes is received by parsing the output of the olsr
# jsoninfo plugin.
# Quickly hacked together by soma (freifunk at somakoma dot de) and released
# into the public domain.
# Version: 0.1
import os
import socket
import json
import datetime
import time
# Configuration - replace these variables with your settings
host = ''
port = 9090
olsrServices = "/var/run/services_olsr"
apiFile = "/var/www/ffapi/ffapi.json"
# End of configuration
def getTopo():
""" Get the topology information from jsoninfo and return a dictionary """
response = ''
s = socket.socket()
s.connect((host, port))
buffer = s.recv(4096)
while buffer:
response += buffer
buffer = s.recv(4096)
except socket.error, e:
print 'Error, could not connect to %(host)s:%(port)s' % {"host": host, "port": port}
print 'Make sure the host is reachable and jsoninfo is running there.'
topo = {}
if response != '':
topo = json.loads(response)['topology']
print 'Could not get any info from jsoninfo on %(host)s:%(port)s' % {"host": host, "port": port}
print 'Does it accept connections from this host?'
return topo
def uniqueIPs(topo):
""" Iterate over a topology dictionary and create an array of unique node ips """
ips = []
for t in topo:
ip = t['destinationIP']
if not ip in ips:
return ips
def getServices():
""" read services from olsrServices """
if not olsrServices or olsrServices == '':
return False
servicesText = []
if not os.access(olsrServices, os.R_OK):
print 'Error: Could not read %(file)s.' % { "file": olsrServices }
print 'Make sure the path is correct and your user has read and write permissions.'
return False
with open(olsrServices, 'r') as services:
servicesText =
return servicesText
def loadApiFile():
""" Load an api file into a dictionary """
if not os.access(apiFile, os.R_OK):
print 'Error: Could not read %(file)s.' % { "file": apiFile }
print 'Make sure the path is correct and your user has read and write permissions.'
with open(apiFile, 'r') as ffapi:
apidict = json.load(ffapi)
return apidict
def updateApiNodes(apiDict, countNodes):
""" Updates an ffapi dictionary with number of nodes and timestamp """
apiDict['state']['nodes'] = countNodes
except KeyError:
print 'Could not update %(field)s in the ffapi dictionary.' % { "field": "['state']['nodes']" }
apiDict['state']['lastchange'] =
except KeyError:
print 'Could not update %(field)s in the ffapi dictionary.' % { "field": "['state']['lastchange']" }
return apiDict
def updateApiServices(apiDict, services):
""" Updates the services section """
if not 'services' in apiDict:
apiDict['services'] = []
for element in reversed(apiDict['services']):
if (element['serviceDescription'] == "auto generated by olsr nameservice plugin"):
for line in services:
if (line == '' or line[1] == '#' or line.split("|").__len__() < 2 ): continue
servicesDict = dict()
serviceList = line.split("|")
servicesDict['serviceName'] = serviceList[2].split("\t")[0]
servicesDict['serviceDescription'] = "auto generated by olsr nameservice plugin"
servicesDict['internalUri'] = serviceList[0]
return apiDict
def writeApiFile(content):
""" writes the dictionary to the ffapi json file """
if not os.access(apiFile, os.W_OK):
print 'Error: Could not write %(file)s.' % { "file": apiFile }
print 'Make sure the path is correct and your user has write permissions for it.'
with open(apiFile, 'w') as ffapi:
ffapi.write(json.dumps(content, indent=4))
return True
def main():
countNodes = len(uniqueIPs(getTopo()))
apiDict = loadApiFile()
apiDictUpdated = updateApiNodes(apiDict, countNodes)
services = getServices()
if services:
apiDictUpdated = updateApiServices(apiDictUpdated, services)
if writeApiFile(apiDictUpdated):
print('Update of %s successful.' % apiFile)
print('We now have %d Nodes' % countNodes)
if services:
print('and %d services' % len(apiDictUpdated['services']))
if __name__ == "__main__":