network.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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::delay_for(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. // Random drop again.
  176. if !reliable
  177. && thread_rng().gen_ratio(Self::DROP_RATE.0, Self::DROP_RATE.1)
  178. {
  179. let _ = rpc.reply_channel.send(Err(std::io::Error::new(
  180. std::io::ErrorKind::TimedOut,
  181. "The network did not send respond in time.",
  182. )));
  183. return;
  184. } else if long_reordering {
  185. let should_reorder = thread_rng().gen_ratio(
  186. Self::LONG_REORDERING_RATE.0,
  187. Self::LONG_REORDERING_RATE.1,
  188. );
  189. if should_reorder {
  190. let long_delay_bound = thread_rng().gen_range(
  191. 0,
  192. Self::LONG_REORDERING_RANDOM_DELAY_BOUND_MILLIS,
  193. );
  194. let long_delay = Self::LONG_REORDERING_BASE_DELAY_MILLIS
  195. + thread_rng().gen_range(0, 1 + long_delay_bound);
  196. Self::delay_for_millis(long_delay).await;
  197. // Falling through to send the result.
  198. }
  199. }
  200. }
  201. if let Err(_e) = rpc.reply_channel.send(reply) {
  202. // TODO(ditsing): log and do nothing.
  203. }
  204. }
  205. pub fn run_daemon() -> Arc<Mutex<Network>> {
  206. let mut network = Network::new();
  207. let rx = network
  208. .request_pipe
  209. .take()
  210. .expect("Newly created network should have a rx");
  211. // Using Mutex instead of RWLock, because most of the access are reads.
  212. let network = Arc::new(Mutex::new(network));
  213. // Using tokio instead of futures-rs, because we need timer futures.
  214. let thread_pool = tokio::runtime::Builder::new()
  215. .threaded_scheduler()
  216. .core_threads(10)
  217. .max_threads(20)
  218. .thread_name("network")
  219. .enable_time()
  220. .build()
  221. .expect("Creating network thread pool should not fail");
  222. let other = network.clone();
  223. std::thread::spawn(move || {
  224. let network = other;
  225. let mut stop_timer = Instant::now();
  226. loop {
  227. // If the lock of network is unfair, we could starve threads
  228. // trying to add / remove RPC servers, or change settings.
  229. // Having a shutdown delay helps minimise lock holding.
  230. if stop_timer.elapsed() >= Self::SHUTDOWN_DELAY {
  231. if !network.lock().keep_running {
  232. break;
  233. }
  234. stop_timer = Instant::now();
  235. }
  236. match rx.try_recv() {
  237. Ok(rpc) => {
  238. thread_pool
  239. .spawn(Self::serve_rpc(network.clone(), rpc));
  240. }
  241. // All senders have disconnected. This should never happen,
  242. // since the network instance itself holds a sender.
  243. Err(TryRecvError::Disconnected) => break,
  244. Err(TryRecvError::Empty) => {
  245. std::thread::sleep(Self::SHUTDOWN_DELAY)
  246. }
  247. }
  248. }
  249. // Shutdown might leak outstanding tasks if timed-out.
  250. thread_pool.shutdown_timeout(Self::SHUTDOWN_DELAY);
  251. // rx is dropped here, all clients should get disconnected error
  252. // and stop sending messages.
  253. drop(rx);
  254. network
  255. .lock()
  256. .stopped
  257. .store(true, Ordering::Release);
  258. });
  259. network
  260. }
  261. }
  262. impl Network {
  263. fn increase_rpc_count(&self) {
  264. self.rpc_count.set(self.rpc_count.get() + 1);
  265. }
  266. fn new() -> Self {
  267. // The channel has infinite buffer, could OOM the server if there are
  268. // too many pending RPCs to be served.
  269. let (tx, rx) = channel();
  270. Network {
  271. reliable: true,
  272. long_delays: false,
  273. long_reordering: false,
  274. clients: Default::default(),
  275. servers: Default::default(),
  276. request_bus: tx,
  277. request_pipe: Some(rx),
  278. keep_running: true,
  279. stopped: Default::default(),
  280. rpc_count: std::cell::Cell::new(0),
  281. }
  282. }
  283. }
  284. #[cfg(test)]
  285. mod tests {
  286. use std::sync::Barrier;
  287. use parking_lot::MutexGuard;
  288. use crate::test_utils::{
  289. junk_server::{
  290. make_test_server, JunkRpcs, NON_CLIENT, NON_SERVER, TEST_CLIENT,
  291. TEST_SERVER,
  292. },
  293. make_aborting_rpc, make_echo_rpc,
  294. };
  295. use crate::{ReplyMessage, RequestMessage, Result};
  296. use super::*;
  297. fn make_network() -> Network {
  298. Network::new()
  299. }
  300. #[test]
  301. fn test_rpc_count_works() {
  302. let network = make_network();
  303. assert_eq!(0, network.get_total_rpc_count());
  304. network.increase_rpc_count();
  305. assert_eq!(1, network.get_total_rpc_count());
  306. }
  307. fn unlock<T>(network: &Arc<Mutex<T>>) -> MutexGuard<T> {
  308. network.lock()
  309. }
  310. #[test]
  311. fn test_network_shutdown() {
  312. let network = Network::run_daemon();
  313. let sender = {
  314. let mut network = unlock(&network);
  315. network.keep_running = false;
  316. network.request_bus.clone()
  317. };
  318. while !unlock(&network).stopped() {
  319. std::thread::sleep(Network::SHUTDOWN_DELAY)
  320. }
  321. let (rpc, _) = make_echo_rpc("client", "server", &[]);
  322. let result = sender.send(rpc);
  323. assert!(
  324. result.is_err(),
  325. "Network is shutdown, requests should not be processed."
  326. );
  327. }
  328. fn send_rpc<C: Into<String>, S: Into<String>>(
  329. rpc: RpcOnWire,
  330. rx: futures::channel::oneshot::Receiver<Result<ReplyMessage>>,
  331. client: C,
  332. server: S,
  333. enabled: bool,
  334. ) -> Result<ReplyMessage> {
  335. let network = Network::run_daemon();
  336. let sender = {
  337. let mut network = unlock(&network);
  338. network
  339. .clients
  340. .insert(client.into(), (enabled, server.into()));
  341. network
  342. .servers
  343. .insert(TEST_SERVER.into(), Arc::new(make_test_server()));
  344. network.request_bus.clone()
  345. };
  346. let result = sender.send(rpc);
  347. assert!(
  348. result.is_ok(),
  349. "Network is running, requests should be processed."
  350. );
  351. let reply = match futures::executor::block_on(rx) {
  352. Ok(reply) => reply,
  353. Err(e) => panic!("Future execution should not fail: {}", e),
  354. };
  355. reply
  356. }
  357. #[test]
  358. fn test_proxy_rpc() -> Result<()> {
  359. let (rpc, rx) =
  360. make_echo_rpc(TEST_CLIENT, TEST_SERVER, &[0x09u8, 0x00u8]);
  361. let reply = send_rpc(rpc, rx, TEST_CLIENT, TEST_SERVER, true);
  362. match reply {
  363. Ok(reply) => assert_eq!(reply.as_ref(), &[0x00u8, 0x09u8]),
  364. Err(e) => panic!("Expecting echo message, got {}", e),
  365. }
  366. Ok(())
  367. }
  368. #[test]
  369. fn test_proxy_rpc_server_error() -> Result<()> {
  370. let (rpc, rx) = make_aborting_rpc(TEST_CLIENT, TEST_SERVER);
  371. let reply = send_rpc(rpc, rx, TEST_CLIENT, TEST_SERVER, true);
  372. let err = reply.expect_err("Network should proxy server errors");
  373. assert_eq!(std::io::ErrorKind::ConnectionReset, err.kind());
  374. Ok(())
  375. }
  376. #[test]
  377. fn test_proxy_rpc_server_not_found() -> Result<()> {
  378. let (rpc, rx) = make_aborting_rpc(TEST_CLIENT, NON_SERVER);
  379. let reply = send_rpc(rpc, rx, TEST_CLIENT, NON_SERVER, true);
  380. let err = reply.expect_err("Network should check server in memory");
  381. assert_eq!(std::io::ErrorKind::NotFound, err.kind());
  382. Ok(())
  383. }
  384. #[test]
  385. fn test_proxy_rpc_client_disabled() -> Result<()> {
  386. let (rpc, rx) = make_aborting_rpc(TEST_CLIENT, TEST_SERVER);
  387. let reply = send_rpc(rpc, rx, TEST_CLIENT, TEST_SERVER, false);
  388. let err =
  389. reply.expect_err("Network should check if client is disabled");
  390. assert_eq!(std::io::ErrorKind::BrokenPipe, err.kind());
  391. Ok(())
  392. }
  393. #[test]
  394. fn test_proxy_rpc_no_such_client() -> Result<()> {
  395. let (rpc, rx) = make_aborting_rpc(NON_CLIENT, TEST_SERVER);
  396. let reply = send_rpc(rpc, rx, TEST_CLIENT, TEST_SERVER, true);
  397. let err = reply.expect_err("Network should check client names");
  398. assert_eq!(std::io::ErrorKind::PermissionDenied, err.kind());
  399. Ok(())
  400. }
  401. fn make_network_and_client() -> (Arc<Mutex<Network>>, Client) {
  402. let network = Network::run_daemon();
  403. let server = make_test_server();
  404. unlock(&network).add_server(TEST_SERVER, server);
  405. let client = unlock(&network).make_client(TEST_CLIENT, TEST_SERVER);
  406. (network, client)
  407. }
  408. #[test]
  409. fn test_basic_functions() -> Result<()> {
  410. // Initialize
  411. let (network, client) = make_network_and_client();
  412. assert_eq!(0, unlock(&network).get_total_rpc_count());
  413. let request = RequestMessage::from_static(&[0x17, 0x20]);
  414. let reply_data = &[0x20, 0x17];
  415. // Send first request.
  416. let reply = futures::executor::block_on(
  417. client
  418. .clone()
  419. .call_rpc(JunkRpcs::Echo.name(), request.clone()),
  420. )?;
  421. assert_eq!(reply_data, reply.as_ref());
  422. assert_eq!(1, unlock(&network).get_total_rpc_count());
  423. // Block the client.
  424. unlock(&network).set_enable_client(TEST_CLIENT, false);
  425. // Send second request.
  426. let reply = futures::executor::block_on(
  427. client
  428. .clone()
  429. .call_rpc(JunkRpcs::Echo.name(), request.clone()),
  430. );
  431. reply.expect_err("Client is blocked");
  432. assert_eq!(2, unlock(&network).get_total_rpc_count());
  433. assert_eq!(Some(1), unlock(&network).get_rpc_count(TEST_SERVER));
  434. assert_eq!(None, unlock(&network).get_rpc_count(NON_SERVER));
  435. // Unblock the client, then remove the server.
  436. unlock(&network).set_enable_client(TEST_CLIENT, true);
  437. unlock(&network).remove_server(&TEST_SERVER);
  438. // Send third request.
  439. let reply = futures::executor::block_on(
  440. client
  441. .clone()
  442. .call_rpc(JunkRpcs::Echo.name(), request.clone()),
  443. );
  444. reply.expect_err("Client is blocked");
  445. assert_eq!(3, unlock(&network).get_total_rpc_count());
  446. // Shutdown the network.
  447. unlock(&network).stop();
  448. while !unlock(&network).stopped() {
  449. std::thread::sleep(Duration::from_millis(10));
  450. }
  451. // Send forth request.
  452. let reply = futures::executor::block_on(
  453. client
  454. .clone()
  455. .call_rpc(JunkRpcs::Echo.name(), request.clone()),
  456. );
  457. reply.expect_err("Network is shutdown");
  458. assert_eq!(3, unlock(&network).get_total_rpc_count());
  459. // Done.
  460. Ok(())
  461. }
  462. #[test]
  463. #[ignore = "Large tests with many threads"]
  464. fn test_many_requests() {
  465. let now = Instant::now();
  466. let (network, _) = make_network_and_client();
  467. let barrier = Arc::new(Barrier::new(THREAD_COUNT + 1));
  468. const THREAD_COUNT: usize = 200;
  469. const RPC_COUNT: usize = 100;
  470. let mut handles = vec![];
  471. for i in 0..THREAD_COUNT {
  472. let network_ref = network.clone();
  473. let barrier_ref = barrier.clone();
  474. let handle = std::thread::spawn(move || {
  475. let client = unlock(&network_ref)
  476. .make_client(format!("{}-{}", TEST_CLIENT, i), TEST_SERVER);
  477. // We should all create the client first.
  478. barrier_ref.wait();
  479. let mut results = vec![];
  480. for _ in 0..RPC_COUNT {
  481. let reply = client.clone().call_rpc(
  482. JunkRpcs::Echo.name(),
  483. RequestMessage::from_static(&[0x20, 0x17]),
  484. );
  485. results.push(reply);
  486. }
  487. for result in results {
  488. futures::executor::block_on(result)
  489. .expect("All futures should succeed");
  490. }
  491. });
  492. handles.push(handle);
  493. }
  494. barrier.wait();
  495. for handle in handles {
  496. handle.join().expect("All threads should succeed");
  497. }
  498. eprintln!("Many requests test took {:?}", now.elapsed());
  499. }
  500. }