@@ -11,12 +11,16 @@ use std::io::{self, BufWriter};
1111use std:: net:: TcpStream ;
1212use std:: path:: { Path , PathBuf } ;
1313use std:: process:: { Command , Stdio } ;
14- use std:: time:: Duration ;
14+ use std:: time:: { Duration , Instant } ;
1515use std:: { env, thread} ;
1616
1717const REMOTE_ADDR_ENV : & str = "TEST_DEVICE_ADDR" ;
1818const DEFAULT_ADDR : & str = "127.0.0.1:12345" ;
1919
20+ const CONNECT_TIMEOUT_ENV : & str = "TEST_DEVICE_CONNECT_TIMEOUT_SECONDS" ;
21+ /// The default timeout is high to not break slow CI or slow device starts.
22+ const DEFAULT_CONNECT_TIMEOUT : Duration = Duration :: from_mins ( 30 ) ;
23+
2024macro_rules! t {
2125 ( $e: expr) => {
2226 match $e {
@@ -56,6 +60,17 @@ fn main() {
5660 }
5761}
5862
63+ fn connect_timeout ( ) -> Duration {
64+ match env:: var ( CONNECT_TIMEOUT_ENV ) . ok ( ) {
65+ Some ( timeout) => timeout. parse ( ) . map ( Duration :: from_secs) . unwrap_or_else ( |e| {
66+ panic ! (
67+ "error: parsing `{CONNECT_TIMEOUT_ENV}` value \" {timeout}\" as seconds failed: {e}"
68+ )
69+ } ) ,
70+ None => DEFAULT_CONNECT_TIMEOUT ,
71+ }
72+ }
73+
5974fn spawn_emulator ( target : & str , server : & Path , tmpdir : & Path , rootfs : Option < PathBuf > ) {
6075 let device_address = env:: var ( REMOTE_ADDR_ENV ) . unwrap_or ( DEFAULT_ADDR . to_string ( ) ) ;
6176
@@ -69,20 +84,28 @@ fn spawn_emulator(target: &str, server: &Path, tmpdir: &Path, rootfs: Option<Pat
6984 }
7085
7186 // Wait for the emulator to come online
72- loop {
87+ let timeout = connect_timeout ( ) ;
88+ let mut successful_read = false ;
89+ let start_time = Instant :: now ( ) ;
90+ while start_time. elapsed ( ) < timeout {
7391 let dur = Duration :: from_millis ( 2000 ) ;
7492 if let Ok ( mut client) = TcpStream :: connect ( & device_address) {
7593 t ! ( client. set_read_timeout( Some ( dur) ) ) ;
7694 t ! ( client. set_write_timeout( Some ( dur) ) ) ;
7795 if client. write_all ( b"ping" ) . is_ok ( ) {
7896 let mut b = [ 0 ; 4 ] ;
7997 if client. read_exact ( & mut b) . is_ok ( ) {
98+ successful_read = true ;
8099 break ;
81100 }
82101 }
83102 }
84103 thread:: sleep ( dur) ;
85104 }
105+
106+ if !successful_read {
107+ panic ! ( "Gave up trying to connect to test device at {device_address} after {timeout:?}" ) ;
108+ }
86109}
87110
88111fn start_android_emulator ( server : & Path ) {
0 commit comments