xref: /aosp_15_r20/tools/netsim/rust/daemon/src/grpc_server/server.rs (revision cf78ab8cffb8fc9207af348f23af247fb04370a6)
1 // Copyright 2024 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 use super::backend::PacketStreamerService;
16 use super::frontend::FrontendClient;
17 use grpcio::{
18     ChannelBuilder, Environment, ResourceQuota, Server, ServerBuilder, ServerCredentials,
19 };
20 use log::{info, warn};
21 use netsim_proto::frontend_grpc::create_frontend_service;
22 use netsim_proto::packet_streamer_grpc::create_packet_streamer;
23 use std::sync::Arc;
24 
start(port: u32, no_cli_ui: bool, _vsock: u16) -> anyhow::Result<(Server, u16)>25 pub fn start(port: u32, no_cli_ui: bool, _vsock: u16) -> anyhow::Result<(Server, u16)> {
26     let env = Arc::new(Environment::new(1));
27     let backend_service = create_packet_streamer(PacketStreamerService);
28     let frontend_service = create_frontend_service(FrontendClient);
29     let quota = ResourceQuota::new(Some("NetsimGrpcServerQuota")).resize_memory(1024 * 1024);
30     let ch_builder = ChannelBuilder::new(env.clone()).set_resource_quota(quota);
31     let mut server_builder = ServerBuilder::new(env);
32     if !no_cli_ui {
33         server_builder = server_builder.register_service(frontend_service);
34     }
35     let mut server = server_builder
36         .register_service(backend_service)
37         .channel_args(ch_builder.build_args())
38         .build()?;
39 
40     let addr_v4 = format!("127.0.0.1:{}", port);
41     let addr_v6 = format!("[::1]:{}", port);
42     let port = server.add_listening_port(addr_v4, ServerCredentials::insecure()).or_else(|e| {
43         warn!("Failed to bind to 127.0.0.1:{port} in grpc server. Trying [::1]:{port}. {e:?}");
44         server.add_listening_port(addr_v6, ServerCredentials::insecure())
45     })?;
46 
47     #[cfg(feature = "cuttlefish")]
48     if _vsock != 0 {
49         let vsock_uri = format!("vsock:{}:{}", libc::VMADDR_CID_ANY, _vsock);
50         info!("vsock_uri: {}", vsock_uri);
51         server.add_listening_port(vsock_uri, ServerCredentials::insecure())?;
52     }
53 
54     server.start();
55     info!("Rust gRPC listening on localhost:{port}");
56     Ok((server, port))
57 }
58