Skip to content

Commit 1719f90

Browse files
alexandruantochimarcelstoer
authored andcommitted
Add Lua module for Gossip protocol (#3013)
1 parent 56a86c2 commit 1719f90

File tree

6 files changed

+819
-0
lines changed

6 files changed

+819
-0
lines changed

docs/lua-modules/gossip.md

Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
# ESPGossip
2+
3+
| Since | Origin / Contributor | Maintainer | Source |
4+
| :----- | :-------------------- | :---------- | :------ |
5+
| 2020-01-20 | [alexandruantochi](https://github.com/alexandruantochi) | [alexandruantochi](https://github.com/alexandruantochi) | [gossip.lua](../../lua_modules/gossip/gossip.lua) |
6+
7+
8+
This module is based on the gossip protocol and it can be used to disseminate information through the network to other nodes. The time it takes for the information to reach all nodes is logN. For every round number n, 2^n nodes will receive the information.
9+
10+
### Require
11+
```lua
12+
gossip = require('gossip')
13+
```
14+
15+
### Release
16+
```lua
17+
gossip.inboundSocket:close()
18+
gossip = nil
19+
```
20+
21+
## Usage
22+
```lua
23+
config = {
24+
seedList = { '192.168.0.1', '192.168.0.15' },
25+
debug = true,
26+
debugOutput = print
27+
}
28+
gossip = require ("gossip")
29+
gossip.setConfig(config)
30+
gossip.start()
31+
```
32+
33+
## Strategy
34+
35+
Each controller will randomly pick an IP from it's seed list. It will send a `SYN` request to that IP and set receiving node's `state` to an intermediary state between `Up` and `Suspect`. The node that receives the `SYN` request will compute a diff on the received networkState vs own networkState. It will then send that diff as an `ACK` request. If there is no data to send, it will only send an `ACK`. When the `ACK` is received, the sender's state will revert to `Up` and the receiving node will update it's own networkState using the diff (based on the `ACK` reply).
36+
37+
Gossip will establish if the information received from another node has fresher data by first comparing the `revision`, then the `heartbeat` and lastly the `state`. States that are closer to `DOWN` have priority as an offline node does not update it's heartbeat.
38+
39+
Any other parameter can be sent along with the mandatory `revision`, `heartbeat` and `state` thus allowing the user to spread information around the network. Every time a node receives 'fresh' data, the `gossip.updateCallback` will be called with that data as the first parameter.
40+
41+
Currently there is no implemented deletion for nodes that are down except for the fact that their status is signaled as `REMOVE`.
42+
43+
## Example use-case
44+
45+
There are multiple modules on the network that measure temperature. We want to know the maximum and minimum temperature at a given time and have every node display it.
46+
47+
The brute force solution would be to query each node from a single point and save the `min` and `max` values, then go back to each node and present them with the computed `min` and `max`. This requires n*2 rounds, where n is the number of nodes. It also opens the algorithm to a single point of failure (the node that is in charge of gathering the data).
48+
49+
Using gossip, one can have the node send it's latest value through `SYN` or `pushGossip()` and use the `callbackUpdate` function to compare the values from other nodes to it's own. Based on that, the node will display the values it knows about by gossiping with others. The data will be transmitted in ~log(n) rounds, where n is the number of nodes.
50+
51+
## Terms
52+
53+
`revision` : generation of the node; if a node restarts, the revision will be increased by one. The revision data is stored as a file to provide persistency
54+
55+
`heartBeat` : the node uptime in seconds (`tmr.time()`). This is used to help the other nodes figure out if the information about that particular node is newer.
56+
57+
`networkState` : the list with the state of the network composed of the `ip` as a key and `revision`, `heartBeat` and `state` as values packed in a table.
58+
59+
`state` : all nodes start with a state set to `UP` and when a node sends a `SYN` request, it will mark the destination node in an intermediary state until it receives an `ACK` or a `SYN` from it. If a node receives any message, it will mark that senders IP as `UP` as this provides proof that the node is online.
60+
61+
62+
## setConfig()
63+
64+
#### Syntax
65+
```lua
66+
gossip.setConfig(config)
67+
```
68+
69+
Sets the configuration for gossip. The available options are:
70+
71+
`seedList` : the list of seeds gossip will start with; this will be updated as new nodes are discovered. Note that it's enough for all nodes to start with the same IP in the seedList, as once they have one seed in common, the data will propagate
72+
73+
`roundInterval`: interval in milliseconds at which gossip will pick a random node from the seed list and send a `SYN` request
74+
75+
`comPort` : port for the listening UDP socket
76+
77+
`debug` : flag that will provide debugging messages
78+
79+
`debugOutput` : if debug is set to `true`, then this method will be used as a callback with the debug message as the first parameter
80+
81+
```lua
82+
config = {
83+
seedList = {'192.168.0.54','192.168.0.55'},
84+
roundInterval = 10000,
85+
comPort = 5000,
86+
debug = true,
87+
debugOutput = function(message) print('Gossip says: '..message); end
88+
}
89+
```
90+
91+
If any of them is not provided, the values will default:
92+
93+
`seedList` : nil
94+
95+
`roundInterval`: 10000 (10 seconds)
96+
97+
`comPort` : 5000
98+
99+
`debug` : false
100+
101+
`debugOutput` : print
102+
103+
## start()
104+
105+
#### Syntax
106+
```lua
107+
gossip.start()
108+
```
109+
110+
Starts gossip, sets the `started` flag to true and initiates the `revision`. The revision (generation) main purpose is like a persistent heartbeat, as the heartbeat (measured by uptime in seconds) will obviously revert to 0.
111+
112+
## callbackFunction
113+
114+
#### Syntax
115+
```lua
116+
gossip.callbackFunction = function(data)
117+
processData(data)
118+
end
119+
120+
-- stop the callback
121+
gossip.callbackFunction = nil
122+
```
123+
124+
If declared, this function will get called every time there is a `SYN` with new data.
125+
126+
## pushGossip()
127+
128+
#### Syntax
129+
130+
```lua
131+
gossip.pushGossip(data, [ip])
132+
133+
-- remove data
134+
gossip.pushGossip(nil, [ip])
135+
```
136+
137+
Send a `SYN` request outside of the normal gossip round. The IP is optional and if none given, it will pick a random node.
138+
139+
```
140+
!!! note
141+
. By calling `pushGossip(nil)` you effectively remove the `data` table from the node's network state and notify other nodes of this.
142+
```
143+
## setRevManually()
144+
145+
#### Syntax
146+
147+
```lua
148+
gossip.setRevFileValue(number)
149+
```
150+
151+
The only scenario when rev should be set manually is when a new node is added to the network and has the same IP. Having a smaller revision than the previous node with the same IP would make gossip think the data it received is old, thus ignoring it.
152+
153+
```
154+
!!! note
155+
156+
The revision file value will only be read when gossip starts and it will be incremented by one.
157+
```
158+
159+
## getNetworkState()
160+
161+
#### Syntax
162+
163+
```lua
164+
networkState = gossip.getNetworkState()
165+
print(networkState)
166+
```
167+
168+
The network state can be directly accessed as a Lua table : `gossip.networkState` or it can be received as a JSON with this method.
169+
170+
#### Returns
171+
172+
JSON formatted string regarding the network state.
173+
174+
Example:
175+
176+
```JSON
177+
{
178+
"192.168.0.53": {
179+
"state": 3,
180+
"revision": 25,
181+
"heartbeat": 2500,
182+
"extra" : "this is some extra info from node 53"
183+
},
184+
"192.168.0.75": {
185+
"state": 0,
186+
"revision": 4,
187+
"heartbeat": 6500
188+
}
189+
}
190+
```
191+

lua_examples/gossip_example.lua

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
-- need a wifi connection
2+
-- enter your wifi credentials
3+
local credentials = {SSID = "SSID", PASS = "PASS"};
4+
5+
-- push a message onto the network
6+
-- this can also be done by changing gossip.networkState[gossip.ip].data = {temperature = 78};
7+
local function sendAlarmingData()
8+
Gossip.pushGossip({temperature = 78});
9+
print('Pushed alarming data');
10+
end
11+
12+
local function removeAlarmingData()
13+
Gossip.pushGossip(nil);
14+
print('Removed alarming data from the network.');
15+
end
16+
17+
-- callback function for when gossip receives an update
18+
local function treatAlarmingData(updateData)
19+
for k in pairs(updateData) do
20+
if updateData[k].data then
21+
if updateData[k].data.temperature and updateData[k].data.temperature > 30 then
22+
print('Warning, the temp is above 30 degrees at ' .. k);
23+
end
24+
end
25+
end
26+
end
27+
28+
local function Startup()
29+
-- initialize all nodes with the seed except for the seed itself
30+
-- eventually they will all know about each other
31+
32+
-- enter at least one ip that will be a start seed
33+
local startingSeed = '192.168.0.73';
34+
35+
-- luacheck: push allow defined
36+
Gossip = require('gossip');
37+
-- luacheck: pop
38+
local config = {debug = true, seedList = {}};
39+
40+
if wifi.sta.getip() ~= startingSeed then
41+
table.insert(config.seedList, startingSeed);
42+
end
43+
44+
Gossip.setConfig(config);
45+
46+
-- add the update callback
47+
Gossip.updateCallback = treatAlarmingData;
48+
49+
-- start gossiping
50+
Gossip.start();
51+
52+
-- send some alarming data timer
53+
if wifi.sta.getip() == startingSeed then
54+
tmr.create():alarm(50000, tmr.ALARM_SINGLE, sendAlarmingData);
55+
tmr.create():alarm(50000*3, tmr.ALARM_SINGLE, removeAlarmingData);
56+
end
57+
end
58+
59+
local function startExample()
60+
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED,
61+
function() print('Diconnected') end);
62+
print("Connecting to WiFi access point...");
63+
64+
if wifi.sta.getip() == nil then
65+
wifi.setmode(wifi.STATION);
66+
wifi.sta.config({ssid = credentials.SSID, pwd = credentials.PASS});
67+
end
68+
print('Ip: ' .. wifi.sta.getip() .. '. Starting in 5s ..');
69+
tmr.create():alarm(5000, tmr.ALARM_SINGLE, Startup);
70+
end
71+
72+
startExample();
73+

lua_modules/gossip/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Gossip module
2+
3+
Documentation for this Lua module is available in the [gossip.md](../../docs/lua-modules/gossip.md) file and in the [Official NodeMCU Documentation](https://nodemcu.readthedocs.io/) in `Lua Modules` section.

0 commit comments

Comments
 (0)