aboutsummaryrefslogtreecommitdiff
path: root/src/membership.rs
blob: 8b0676863738fb8f7943708869a9b31b03d29d0b (plain) (blame)
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use std::sync::Arc;
use std::collections::HashMap;
use std::time::Duration;
use std::net::{IpAddr, SocketAddr};

use futures::future::join_all;
use hyper::client::Client;
use tokio::sync::RwLock;
use sha2::{Sha256, Digest};

use crate::Config;
use crate::error::Error;
use crate::data::*;
use crate::proto::*;
use crate::rpc::*;

const PING_INTERVAL: Duration = Duration::from_secs(10);
const PING_TIMEOUT: Duration = Duration::from_secs(2);
const MAX_FAILED_PINGS: usize = 3;

pub struct System {
	pub config: Config,
	pub id: UUID,

	pub rpc_client: Client<hyper::client::HttpConnector, hyper::Body>,

	pub members: RwLock<Members>,
}

pub struct Members {
	pub status: HashMap<UUID, NodeStatus>,
	pub status_hash: Hash,

	pub config: NetworkConfig,
}

impl Members {
	fn handle_ping(&mut self, ip: IpAddr, info: &PingMessage) -> bool {
		let addr = SocketAddr::new(ip, info.rpc_port);
		let old_status = self.status.insert(info.id.clone(),
			NodeStatus{
				addr: addr.clone(),
				remaining_ping_attempts: MAX_FAILED_PINGS,
			});
		match old_status {
			None => {
				eprintln!("Discovered new node (ping): {}", hex::encode(info.id));
				true
			}
			Some(x) => x.addr != addr,
		}
	}

	fn handle_advertise_node(&mut self, id: &UUID, addr: &SocketAddr) -> bool {
		if !self.status.contains_key(id) {
			eprintln!("Discovered new node (advertisment): {}", hex::encode(id));
			self.status.insert(id.clone(),
				NodeStatus{
					addr: addr.clone(),
					remaining_ping_attempts: MAX_FAILED_PINGS,
				});
			true
		} else {
			false
		}
	}

	fn recalculate_status_hash(&mut self) {
		let mut nodes = self.status.iter().collect::<Vec<_>>();
		nodes.sort_by_key(|(id, _status)| *id);

		let mut hasher = Sha256::new();
		for (id, status) in nodes {
			hasher.input(format!("{} {}\n", hex::encode(id), status.addr));
		}
		self.status_hash.copy_from_slice(&hasher.result()[..]);
	}
}

pub struct NodeStatus {
	pub addr: SocketAddr,
	pub remaining_ping_attempts: usize,
}


impl System {
	pub fn new(config: Config, id: UUID) -> Self {
		System{
			config,
			id,
			rpc_client: Client::new(),
			members: RwLock::new(Members{
				status: HashMap::new(),
				status_hash: [0u8; 32],
				config: NetworkConfig{
					members: HashMap::new(),
					version: 0,
				},
			}),
		}
	}

	pub async fn make_ping(&self) -> Message {
		let members = self.members.read().await;
		Message::Ping(PingMessage{
			id: self.id,
			rpc_port: self.config.rpc_port,
			status_hash: members.status_hash.clone(),
			config_version: members.config.version,
		})
	}

	pub async fn broadcast(self: Arc<Self>, msg: Message, timeout: Duration) {
		let members = self.members.read().await;
		let to = members.status.keys().filter(|x| **x != self.id).cloned().collect::<Vec<_>>();
		drop(members);
		rpc_call_many(self.clone(), &to[..], &msg, None, timeout).await;
	}

	pub async fn bootstrap(self: Arc<Self>) {
		let ping_msg = self.make_ping().await;
		let ping_resps = join_all(
			self.config.bootstrap_peers.iter().cloned()
			.map(|to| {
				let sys = self.clone();
				let ping_msg_ref = &ping_msg;
				async move {
					(to.clone(), rpc_call_addr(sys, &to, ping_msg_ref, PING_TIMEOUT).await)
				}
			})).await;
		
		let mut members = self.members.write().await;
		for (addr, ping_resp) in ping_resps {
			if let Ok(Message::Ping(info)) = ping_resp {
				members.handle_ping(addr.ip(), &info);
			}
		}
		members.recalculate_status_hash();
		drop(members);

		tokio::spawn(self.ping_loop());
	}

	pub async fn handle_ping(self: Arc<Self>,
							 from: &SocketAddr,
							 ping: &PingMessage)
		-> Result<Message, Error> 
	{
		let mut members = self.members.write().await;
		let is_new = members.handle_ping(from.ip(), ping);
		if is_new {
			members.recalculate_status_hash();
		}
		let status_hash = members.status_hash.clone();
		let config_version = members.config.version;
		drop(members);

		if is_new || status_hash != ping.status_hash {
			tokio::spawn(self.clone().pull_status(ping.id.clone()));
		}
		if is_new || config_version < ping.config_version {
			tokio::spawn(self.clone().pull_config(ping.id.clone()));
		}

		Ok(self.make_ping().await)
	}

	pub async fn handle_pull_status(&self) -> Result<Message, Error> {
		let members = self.members.read().await;
		let mut mem = vec![];
		for (node, status) in members.status.iter() {
			mem.push(AdvertisedNode{
				id: node.clone(),
				addr: status.addr.clone(),
			});
		}
		Ok(Message::AdvertiseNodesUp(mem))
	}

	pub async fn handle_pull_config(&self) -> Result<Message, Error> {
		let members = self.members.read().await;
		Ok(Message::AdvertiseConfig(members.config.clone()))
	}

	pub async fn handle_advertise_nodes_up(self: Arc<Self>,
									   adv: &[AdvertisedNode])
		 -> Result<Message, Error>
	{
		let mut propagate = vec![];

		let mut members = self.members.write().await;
		for node in adv.iter() {
			let is_new = members.handle_advertise_node(&node.id, &node.addr);
			if is_new {
				tokio::spawn(self.clone().pull_status(node.id.clone()));
				tokio::spawn(self.clone().pull_config(node.id.clone()));
				propagate.push(node.clone());
			}
		}
		drop(members);
		
		if propagate.len() > 0 {
			tokio::spawn(self.clone().broadcast(Message::AdvertiseNodesUp(propagate), PING_TIMEOUT));
		}

		Ok(Message::Ok)
	}

	pub async fn handle_advertise_config(self: Arc<Self>,
										 adv: &NetworkConfig)
		-> Result<Message, Error>
	{
		let mut members = self.members.write().await;
		if adv.version > members.config.version {
			members.config = adv.clone();
			tokio::spawn(self.clone().broadcast(Message::AdvertiseConfig(adv.clone()), PING_TIMEOUT));
		}

		Ok(Message::Ok)
	}

	pub async fn ping_loop(self: Arc<Self>) {
		loop {
			let restart_at = tokio::time::delay_for(PING_INTERVAL);
			
			let members = self.members.read().await;
			let ping_addrs = members.status.iter()
					.filter(|(id, _)| **id != self.id)
					.map(|(id, status)| (id.clone(), status.addr.clone()))
					.collect::<Vec<_>>();
			drop(members);

			let ping_msg = self.make_ping().await;
			let ping_resps = join_all(
					ping_addrs.iter()
						.map(|(id, addr)| {
							let sys = self.clone();
							let ping_msg_ref = &ping_msg;
							async move {
								(id, addr.clone(), rpc_call_addr(sys, &addr, ping_msg_ref, PING_TIMEOUT).await)
							}
					})).await;

			let mut members = self.members.write().await;
			for (id, addr, ping_resp) in ping_resps {
				if let Ok(Message::Ping(ping)) = ping_resp {
					let is_new = members.handle_ping(addr.ip(), &ping);
					if is_new || members.status_hash != ping.status_hash {
						tokio::spawn(self.clone().pull_status(ping.id.clone()));
					}
					if is_new || members.config.version < ping.config_version {
						tokio::spawn(self.clone().pull_config(ping.id.clone()));
					}
				} else {
					let remaining_attempts = members.status.get(id).map(|x| x.remaining_ping_attempts).unwrap_or(0);
					if remaining_attempts == 0 {
						eprintln!("Removing node {} after too many failed pings", hex::encode(id));
						members.status.remove(id);
					} else {
						if let Some(st) = members.status.get_mut(id) {
							st.remaining_ping_attempts = remaining_attempts - 1;
						}
					}
				}
			}
			drop(members);

			restart_at.await
		}
	}

	pub fn pull_status(self: Arc<Self>, peer: UUID) -> impl futures::future::Future<Output=()> + Send + 'static {
		async move {
			let resp = rpc_call(self.clone(),
						 &peer,
						 &Message::PullStatus,
						 PING_TIMEOUT).await;
			if let Ok(Message::AdvertiseNodesUp(nodes)) = resp {
				let _: Result<_, _> = self.handle_advertise_nodes_up(&nodes).await;
			}
		}
	}

	pub async fn pull_config(self: Arc<Self>, peer: UUID) {
		let resp = rpc_call(self.clone(),
					 &peer,
					 &Message::PullConfig,
					 PING_TIMEOUT).await;
		if let Ok(Message::AdvertiseConfig(config)) = resp {
			let _: Result<_, _> = self.handle_advertise_config(&config).await;
		}
	}
}