network.rs 20 KB

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