-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathffapi-update-nodes.py
More file actions
144 lines (117 loc) · 4.74 KB
/
Copy pathffapi-update-nodes.py
File metadata and controls
144 lines (117 loc) · 4.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/python3
# 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 json
from datetime import datetime, timezone
from urllib.request import urlopen
# Configuration - replace these variables with your settings
host = '127.0.0.1'
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 = ''
try:
url = f"http://{host}:{port}/topology"
response = urlopen(url, None, 10)
except BaseException as 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.')
exit()
topo = {}
if response != '':
topo = json.loads(response.read().decode('utf-8'))['topology']
else:
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?')
exit()
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:
ips.append(ip)
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 = services.read().splitlines()
services.closed
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.')
exit()
with open(apiFile, 'r') as ffapi:
apidict = json.load(ffapi)
ffapi.closed
return apidict
def updateApiNodes(apiDict, countNodes):
""" Updates an ffapi dictionary with number of nodes and timestamp """
try:
apiDict['state']['nodes'] = countNodes
except KeyError:
print('Could not update %(field)s in the ffapi dictionary.' % { "field": "['state']['nodes']" })
try:
apiDict['state']['lastchange'] = datetime.now(timezone.utc).isoformat()
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"):
apiDict['services'].remove(element)
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]
apiDict['services'].append(servicesDict)
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.')
exit()
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__":
main()