1+ // Copyright (C) Microsoft Corporation. All rights reserved.
2+
3+ use std:: io;
4+ use std:: path:: { Path , PathBuf } ;
5+ use std:: time:: Duration ;
6+
7+ use hyper_util:: rt:: TokioIo ;
8+ use socket2:: { Domain , SockAddr , Socket , Type } ;
9+ use tokio:: net:: TcpStream ;
10+ use tonic:: transport:: { Channel , Endpoint } ;
11+ use tower:: service_fn;
12+
13+ /// Connects a Tonic channel to the OpenVMM AF_UNIX listener.
14+ pub async fn connect_channel (
15+ socket_path : PathBuf ,
16+ timeout : Duration ,
17+ ) -> Result < Channel , tonic:: transport:: Error > {
18+ Endpoint :: from_static ( "http://[::]:50051" )
19+ . connect_timeout ( timeout)
20+ . connect_with_connector ( service_fn ( move |_| {
21+ let socket_path = socket_path. clone ( ) ;
22+ async move { open_socket ( & socket_path, timeout) . await . map ( TokioIo :: new) }
23+ } ) )
24+ . await
25+ }
26+
27+ async fn open_socket ( path : & Path , timeout : Duration ) -> io:: Result < TcpStream > {
28+ let address = SockAddr :: unix ( path) ?;
29+ tokio:: time:: timeout ( timeout, async {
30+ loop {
31+ match connect_socket ( & address) . await {
32+ Ok ( stream) => return Ok ( stream) ,
33+ Err ( error)
34+ if matches ! (
35+ error. kind( ) ,
36+ io:: ErrorKind :: NotFound | io:: ErrorKind :: ConnectionRefused
37+ ) => { }
38+ Err ( error) => return Err ( error) ,
39+ }
40+ tokio:: time:: sleep ( Duration :: from_millis ( 20 ) ) . await ;
41+ }
42+ } )
43+ . await
44+ . map_err ( |_| io:: Error :: new ( io:: ErrorKind :: TimedOut , "timed out connecting to OpenVMM" ) ) ?
45+ }
46+
47+ /// Registers the Winsock AF_UNIX socket with Tokio's Windows socket reactor.
48+ /// The socket remains AF_UNIX; TCP-specific options and address queries must
49+ /// not be used on the returned stream.
50+ async fn connect_socket ( address : & SockAddr ) -> io:: Result < TcpStream > {
51+ let socket = Socket :: new ( Domain :: UNIX , Type :: STREAM , None ) ?;
52+ socket. set_nonblocking ( true ) ?;
53+ match socket. connect ( address) {
54+ Ok ( ( ) ) => { }
55+ Err ( error) if error. kind ( ) == io:: ErrorKind :: WouldBlock => { }
56+ Err ( error) => return Err ( error) ,
57+ }
58+
59+ let stream = TcpStream :: from_std ( socket. into ( ) ) ?;
60+ stream. writable ( ) . await ?;
61+ if let Some ( error) = stream. take_error ( ) ? {
62+ return Err ( error) ;
63+ }
64+ Ok ( stream)
65+ }
0 commit comments