network.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. use std::collections::HashMap;
  2. use std::sync::mpsc::{channel, Receiver, Sender, TryRecvError};
  3. use std::sync::{
  4. atomic::{AtomicBool, Ordering},
  5. Arc, Mutex,
  6. };
  7. use std::time::{Duration, Instant};
  8. use rand::{thread_rng, Rng};
  9. use crate::{
  10. Client, ClientIdentifier, Result, RpcOnWire, Server, ServerIdentifier,
  11. };
  12. pub struct Network {
  13. // Settings.
  14. reliable: bool,
  15. long_delays: bool,
  16. long_reordering: bool,
  17. // Clients
  18. clients: HashMap<ClientIdentifier, (bool, ServerIdentifier)>,
  19. servers: HashMap<ServerIdentifier, Arc<Server>>,
  20. // Network bus
  21. request_bus: Sender<RpcOnWire>,
  22. request_pipe: Option<Receiver<RpcOnWire>>,
  23. // Closing signal.
  24. keep_running: bool,
  25. // Whether the network is active or not.
  26. stopped: AtomicBool,
  27. // RPC Counter, using Cell for interior mutability.
  28. rpc_count: std::cell::Cell<usize>,
  29. }
  30. impl Network {
  31. pub fn set_reliable(&mut self, yes: bool) {
  32. self.reliable = yes
  33. }
  34. pub fn set_long_reordering(&mut self, yes: bool) {
  35. self.long_reordering = yes
  36. }
  37. pub fn set_long_delays(&mut self, yes: bool) {
  38. self.long_delays = yes
  39. }
  40. pub fn stop(&mut self) {
  41. self.keep_running = false;
  42. }
  43. pub fn stopped(&self) -> bool {
  44. self.stopped.load(Ordering::Acquire)
  45. }
  46. pub fn make_client<C: Into<ClientIdentifier>, S: Into<ServerIdentifier>>(
  47. &mut self,
  48. client: C,
  49. server: S,
  50. ) -> Client {
  51. let (client, server) = (client.into(), server.into());
  52. self.clients.insert(client.clone(), (true, server.clone()));
  53. Client {
  54. client,
  55. server,
  56. request_bus: self.request_bus.clone(),
  57. }
  58. }
  59. pub fn set_enable_client<C: AsRef<str>>(&mut self, client: C, yes: bool) {
  60. if let Some(pair) = self.clients.get_mut(client.as_ref()) {
  61. pair.0 = yes;
  62. }
  63. }
  64. pub fn add_server<S: Into<ServerIdentifier>>(
  65. &mut self,
  66. server_name: S,
  67. server: Server,
  68. ) {
  69. self.servers.insert(server_name.into(), Arc::new(server));
  70. }
  71. pub fn remove_server<S: AsRef<str>>(&mut self, server_name: &S) {
  72. self.servers.remove(server_name.as_ref());
  73. }
  74. pub fn get_rpc_count<S: AsRef<str>>(
  75. &self,
  76. server_name: S,
  77. ) -> Option<usize> {
  78. self.servers
  79. .get(server_name.as_ref())
  80. .map(|s| s.rpc_count())
  81. }
  82. #[allow(clippy::ptr_arg)]
  83. fn dispatch(&self, client: &ClientIdentifier) -> Result<Arc<Server>> {
  84. let (enabled, server_name) =
  85. self.clients.get(client).ok_or_else(|| {
  86. std::io::Error::new(
  87. std::io::ErrorKind::PermissionDenied,
  88. format!("Client {} is not connected.", client),
  89. )
  90. })?;
  91. if !enabled {
  92. return Err(std::io::Error::new(
  93. std::io::ErrorKind::BrokenPipe,
  94. format!("Client {} is disabled.", client),
  95. ));
  96. }
  97. let server = self.servers.get(server_name).ok_or_else(|| {
  98. std::io::Error::new(
  99. std::io::ErrorKind::NotFound,
  100. format!(
  101. "Cannot connect {} to server {}: server not found.",
  102. client, server_name,
  103. ),
  104. )
  105. })?;
  106. Ok(server.clone())
  107. }
  108. pub fn get_total_rpc_count(&self) -> usize {
  109. self.rpc_count.get()
  110. }
  111. }
  112. impl Network {
  113. const MAX_MINOR_DELAY_MILLIS: u64 = 27;
  114. const MAX_SHORT_DELAY_MILLIS: u64 = 100;
  115. const MAX_LONG_DELAY_MILLIS: u64 = 7000;
  116. const DROP_RATE: (u32, u32) = (100, 1000);
  117. const LONG_REORDERING_RATE: (u32, u32) = (600u32, 900u32);
  118. const LONG_REORDERING_BASE_DELAY_MILLIS: u64 = 200;
  119. const LONG_REORDERING_RANDOM_DELAY_BOUND_MILLIS: u64 = 2000;
  120. const SHUTDOWN_DELAY: Duration = Duration::from_micros(20);
  121. async fn delay_for_millis(milli_seconds: u64) {
  122. tokio::time::delay_for(Duration::from_millis(milli_seconds)).await;
  123. }
  124. async fn serve_rpc(network: Arc<Mutex<Self>>, rpc: RpcOnWire) {
  125. let (server_result, reliable, long_reordering, long_delays) = {
  126. let network = network
  127. .lock()
  128. .expect("Network mutex should not be poisoned");
  129. network.increase_rpc_count();
  130. (
  131. network.dispatch(&rpc.client),
  132. network.reliable,
  133. network.long_reordering,
  134. network.long_delays,
  135. )
  136. };
  137. // Random delay before sending requests to server.
  138. if !reliable {
  139. let minor_delay =
  140. thread_rng().gen_range(0, Self::MAX_MINOR_DELAY_MILLIS);
  141. Self::delay_for_millis(minor_delay).await;
  142. // Random drop of a DROP_RATE / DROP_BASE chance.
  143. if thread_rng().gen_ratio(Self::DROP_RATE.0, Self::DROP_RATE.1) {
  144. // Note this is different from the original Go version.
  145. // Here we don't reply to client until timeout actually passes.
  146. Self::delay_for_millis(Self::MAX_MINOR_DELAY_MILLIS).await;
  147. let _ = rpc.reply_channel.send(Err(std::io::Error::new(
  148. std::io::ErrorKind::TimedOut,
  149. "Remote server did not respond in time.",
  150. )));
  151. return;
  152. }
  153. }
  154. let reply = match server_result {
  155. // Call the server.
  156. Ok(server) => {
  157. // Simulates the copy from network to server.
  158. let data = rpc.request.clone();
  159. server.dispatch(rpc.service_method, data).await
  160. }
  161. // If the server does not exist, return error after a random delay.
  162. Err(e) => {
  163. let long_delay = rand::thread_rng().gen_range(
  164. 0,
  165. if long_delays {
  166. Self::MAX_LONG_DELAY_MILLIS
  167. } else {
  168. Self::MAX_SHORT_DELAY_MILLIS
  169. },
  170. );
  171. Self::delay_for_millis(long_delay).await;
  172. Err(e)
  173. }
  174. };
  175. if reply.is_ok() {
  176. // Random drop again.
  177. if !reliable
  178. && thread_rng().gen_ratio(Self::DROP_RATE.0, Self::DROP_RATE.1)
  179. {
  180. let _ = rpc.reply_channel.send(Err(std::io::Error::new(
  181. std::io::ErrorKind::TimedOut,
  182. "The network did not send respond in time.",
  183. )));
  184. return;
  185. } else if long_reordering {
  186. let should_reorder = thread_rng().gen_ratio(
  187. Self::LONG_REORDERING_RATE.0,
  188. Self::LONG_REORDERING_RATE.1,
  189. );
  190. if should_reorder {
  191. let long_delay_bound = thread_rng().gen_range(
  192. 0,
  193. Self::LONG_REORDERING_RANDOM_DELAY_BOUND_MILLIS,
  194. );
  195. let long_delay = Self::LONG_REORDERING_BASE_DELAY_MILLIS
  196. + thread_rng().gen_range(0, 1 + long_delay_bound);
  197. Self::delay_for_millis(long_delay).await;
  198. // Falling through to send the result.
  199. }
  200. }
  201. }
  202. if let Err(_e) = rpc.reply_channel.send(reply) {
  203. // TODO(ditsing): log and do nothing.
  204. }
  205. }
  206. pub fn run_daemon() -> Arc<Mutex<Network>> {
  207. let mut network = Network::new();
  208. let rx = network
  209. .request_pipe
  210. .take()
  211. .expect("Newly created network should have a rx");
  212. // Using Mutex instead of RWLock, because most of the access are reads.
  213. let network = Arc::new(Mutex::new(network));
  214. // Using tokio instead of futures-rs, because we need timer futures.
  215. let thread_pool = tokio::runtime::Builder::new()
  216. .threaded_scheduler()
  217. .core_threads(10)
  218. .max_threads(20)
  219. .thread_name("network")
  220. .enable_time()
  221. .build()
  222. .expect("Creating network thread pool should not fail");
  223. let other = network.clone();
  224. std::thread::spawn(move || {
  225. let network = other;
  226. let mut stop_timer = Instant::now();
  227. loop {
  228. // If the lock of network is unfair, we could starve threads
  229. // trying to add / remove RPC servers, or change settings.
  230. // Having a shutdown delay helps minimise lock holding.
  231. if stop_timer.elapsed() >= Self::SHUTDOWN_DELAY {
  232. let locked_network = network
  233. .lock()
  234. .expect("Network mutex should not be poisoned");
  235. if !locked_network.keep_running {
  236. break;
  237. }
  238. stop_timer = Instant::now();
  239. }
  240. match rx.try_recv() {
  241. Ok(rpc) => {
  242. thread_pool
  243. .spawn(Self::serve_rpc(network.clone(), rpc));
  244. }
  245. // All senders have disconnected. This should never happen,
  246. // since the network instance itself holds a sender.
  247. Err(TryRecvError::Disconnected) => break,
  248. Err(TryRecvError::Empty) => {
  249. std::thread::sleep(Self::SHUTDOWN_DELAY)
  250. }
  251. }
  252. }
  253. // Shutdown might leak outstanding tasks if timed-out.
  254. thread_pool.shutdown_timeout(Self::SHUTDOWN_DELAY);
  255. // rx is dropped here, all clients should get disconnected error
  256. // and stop sending messages.
  257. drop(rx);
  258. network
  259. .lock()
  260. .expect("Network mutex should not be poisoned")
  261. .stopped
  262. .store(true, Ordering::Release);
  263. });
  264. network
  265. }
  266. }
  267. impl Network {
  268. fn increase_rpc_count(&self) {
  269. self.rpc_count.set(self.rpc_count.get() + 1);
  270. }
  271. fn new() -> Self {
  272. // The channel has infinite buffer, could OOM the server if there are
  273. // too many pending RPCs to be served.
  274. let (tx, rx) = channel();
  275. Network {
  276. reliable: true,
  277. long_delays: false,
  278. long_reordering: false,
  279. clients: Default::default(),
  280. servers: Default::default(),
  281. request_bus: tx,
  282. request_pipe: Some(rx),
  283. keep_running: true,
  284. stopped: Default::default(),
  285. rpc_count: std::cell::Cell::new(0),
  286. }
  287. }
  288. }
  289. #[cfg(test)]
  290. mod tests {
  291. use std::sync::{Barrier, MutexGuard};
  292. use crate::test_utils::{
  293. junk_server::{
  294. make_test_server, JunkRpcs, NON_CLIENT, NON_SERVER, TEST_CLIENT,
  295. TEST_SERVER,
  296. },
  297. make_aborting_rpc, make_echo_rpc,
  298. };
  299. use crate::{ReplyMessage, RequestMessage, Result};
  300. use super::*;
  301. fn make_network() -> Network {
  302. Network::new()
  303. }
  304. #[test]
  305. fn test_rpc_count_works() {
  306. let network = make_network();
  307. assert_eq!(0, network.get_total_rpc_count());
  308. network.increase_rpc_count();
  309. assert_eq!(1, network.get_total_rpc_count());
  310. }
  311. fn unlock<T>(network: &Arc<Mutex<T>>) -> MutexGuard<T> {
  312. network
  313. .lock()
  314. .expect("Network mutex should not be poisoned")
  315. }
  316. #[test]
  317. fn test_network_shutdown() {
  318. let network = Network::run_daemon();
  319. let sender = {
  320. let mut network = unlock(&network);
  321. network.keep_running = false;
  322. network.request_bus.clone()
  323. };
  324. while !unlock(&network).stopped() {
  325. std::thread::sleep(Network::SHUTDOWN_DELAY)
  326. }
  327. let (rpc, _) = make_echo_rpc("client", "server", &[]);
  328. let result = sender.send(rpc);
  329. assert!(
  330. result.is_err(),
  331. "Network is shutdown, requests should not be processed."
  332. );
  333. }
  334. fn send_rpc<C: Into<String>, S: Into<String>>(
  335. rpc: RpcOnWire,
  336. rx: futures::channel::oneshot::Receiver<Result<ReplyMessage>>,
  337. client: C,
  338. server: S,
  339. enabled: bool,
  340. ) -> Result<ReplyMessage> {
  341. let network = Network::run_daemon();
  342. let sender = {
  343. let mut network = unlock(&network);
  344. network
  345. .clients
  346. .insert(client.into(), (enabled, server.into()));
  347. network
  348. .servers
  349. .insert(TEST_SERVER.into(), Arc::new(make_test_server()));
  350. network.request_bus.clone()
  351. };
  352. let result = sender.send(rpc);
  353. assert!(
  354. result.is_ok(),
  355. "Network is running, requests should be processed."
  356. );
  357. let reply = match futures::executor::block_on(rx) {
  358. Ok(reply) => reply,
  359. Err(e) => panic!("Future execution should not fail: {}", e),
  360. };
  361. reply
  362. }
  363. #[test]
  364. fn test_proxy_rpc() -> Result<()> {
  365. let (rpc, rx) =
  366. make_echo_rpc(TEST_CLIENT, TEST_SERVER, &[0x09u8, 0x00u8]);
  367. let reply = send_rpc(rpc, rx, TEST_CLIENT, TEST_SERVER, true);
  368. match reply {
  369. Ok(reply) => assert_eq!(reply.as_ref(), &[0x00u8, 0x09u8]),
  370. Err(e) => panic!("Expecting echo message, got {}", e),
  371. }
  372. Ok(())
  373. }
  374. #[test]
  375. fn test_proxy_rpc_server_error() -> Result<()> {
  376. let (rpc, rx) = make_aborting_rpc(TEST_CLIENT, TEST_SERVER);
  377. let reply = send_rpc(rpc, rx, TEST_CLIENT, TEST_SERVER, true);
  378. let err = reply.expect_err("Network should proxy server errors");
  379. assert_eq!(std::io::ErrorKind::ConnectionReset, err.kind());
  380. Ok(())
  381. }
  382. #[test]
  383. fn test_proxy_rpc_server_not_found() -> Result<()> {
  384. let (rpc, rx) = make_aborting_rpc(TEST_CLIENT, NON_SERVER);
  385. let reply = send_rpc(rpc, rx, TEST_CLIENT, NON_SERVER, true);
  386. let err = reply.expect_err("Network should check server in memory");
  387. assert_eq!(std::io::ErrorKind::NotFound, err.kind());
  388. Ok(())
  389. }
  390. #[test]
  391. fn test_proxy_rpc_client_disabled() -> Result<()> {
  392. let (rpc, rx) = make_aborting_rpc(TEST_CLIENT, TEST_SERVER);
  393. let reply = send_rpc(rpc, rx, TEST_CLIENT, TEST_SERVER, false);
  394. let err =
  395. reply.expect_err("Network should check if client is disabled");
  396. assert_eq!(std::io::ErrorKind::BrokenPipe, err.kind());
  397. Ok(())
  398. }
  399. #[test]
  400. fn test_proxy_rpc_no_such_client() -> Result<()> {
  401. let (rpc, rx) = make_aborting_rpc(NON_CLIENT, TEST_SERVER);
  402. let reply = send_rpc(rpc, rx, TEST_CLIENT, TEST_SERVER, true);
  403. let err = reply.expect_err("Network should check client names");
  404. assert_eq!(std::io::ErrorKind::PermissionDenied, err.kind());
  405. Ok(())
  406. }
  407. fn make_network_and_client() -> (Arc<Mutex<Network>>, Client) {
  408. let network = Network::run_daemon();
  409. let server = make_test_server();
  410. unlock(&network).add_server(TEST_SERVER, server);
  411. let client = unlock(&network).make_client(TEST_CLIENT, TEST_SERVER);
  412. (network, client)
  413. }
  414. #[test]
  415. fn test_basic_functions() -> Result<()> {
  416. // Initialize
  417. let (network, client) = make_network_and_client();
  418. assert_eq!(0, unlock(&network).get_total_rpc_count());
  419. let request = RequestMessage::from_static(&[0x17, 0x20]);
  420. let reply_data = &[0x20, 0x17];
  421. // Send first request.
  422. let reply = futures::executor::block_on(
  423. client
  424. .clone()
  425. .call_rpc(JunkRpcs::Echo.name(), request.clone()),
  426. )?;
  427. assert_eq!(reply_data, reply.as_ref());
  428. assert_eq!(1, unlock(&network).get_total_rpc_count());
  429. // Block the client.
  430. unlock(&network).set_enable_client(TEST_CLIENT, false);
  431. // Send second request.
  432. let reply = futures::executor::block_on(
  433. client
  434. .clone()
  435. .call_rpc(JunkRpcs::Echo.name(), request.clone()),
  436. );
  437. reply.expect_err("Client is blocked");
  438. assert_eq!(2, unlock(&network).get_total_rpc_count());
  439. assert_eq!(Some(1), unlock(&network).get_rpc_count(TEST_SERVER));
  440. assert_eq!(None, unlock(&network).get_rpc_count(NON_SERVER));
  441. // Unblock the client, then remove the server.
  442. unlock(&network).set_enable_client(TEST_CLIENT, true);
  443. unlock(&network).remove_server(&TEST_SERVER);
  444. // Send third request.
  445. let reply = futures::executor::block_on(
  446. client
  447. .clone()
  448. .call_rpc(JunkRpcs::Echo.name(), request.clone()),
  449. );
  450. reply.expect_err("Client is blocked");
  451. assert_eq!(3, unlock(&network).get_total_rpc_count());
  452. // Shutdown the network.
  453. unlock(&network).stop();
  454. while !unlock(&network).stopped() {
  455. std::thread::sleep(Duration::from_millis(10));
  456. }
  457. // Send forth request.
  458. let reply = futures::executor::block_on(
  459. client
  460. .clone()
  461. .call_rpc(JunkRpcs::Echo.name(), request.clone()),
  462. );
  463. reply.expect_err("Network is shutdown");
  464. assert_eq!(3, unlock(&network).get_total_rpc_count());
  465. // Done.
  466. Ok(())
  467. }
  468. #[test]
  469. #[ignore = "Large tests with many threads"]
  470. fn test_many_requests() {
  471. let now = Instant::now();
  472. let (network, _) = make_network_and_client();
  473. let barrier = Arc::new(Barrier::new(THREAD_COUNT + 1));
  474. const THREAD_COUNT: usize = 200;
  475. const RPC_COUNT: usize = 100;
  476. let mut handles = vec![];
  477. for i in 0..THREAD_COUNT {
  478. let network_ref = network.clone();
  479. let barrier_ref = barrier.clone();
  480. let handle = std::thread::spawn(move || {
  481. let client = unlock(&network_ref)
  482. .make_client(format!("{}-{}", TEST_CLIENT, i), TEST_SERVER);
  483. // We should all create the client first.
  484. barrier_ref.wait();
  485. let mut results = vec![];
  486. for _ in 0..RPC_COUNT {
  487. let reply = client.clone().call_rpc(
  488. JunkRpcs::Echo.name(),
  489. RequestMessage::from_static(&[0x20, 0x17]),
  490. );
  491. results.push(reply);
  492. }
  493. for result in results {
  494. futures::executor::block_on(result)
  495. .expect("All futures should succeed");
  496. }
  497. });
  498. handles.push(handle);
  499. }
  500. barrier.wait();
  501. for handle in handles {
  502. handle.join().expect("All threads should succeed");
  503. }
  504. eprintln!("Many requests test took {:?}", now.elapsed());
  505. }
  506. }