1 // Copyright 2023 The Android Open Source Project
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 //      http://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 // Frontend client for netsimd.
16 
17 #include "frontend/frontend_client_stub.h"
18 
19 #include <chrono>
20 #include <memory>
21 
22 #include "grpcpp/create_channel.h"
23 #include "grpcpp/security/credentials.h"
24 #include "netsim/frontend.grpc.pb.h"
25 #include "netsim/frontend.pb.h"
26 #include "util/os_utils.h"
27 
28 namespace netsim {
29 namespace frontend {
30 namespace {
31 const std::chrono::duration kConnectionDeadline = std::chrono::seconds(1);
32 
NewFrontendClient(uint16_t instance_num)33 std::unique_ptr<frontend::FrontendService::Stub> NewFrontendClient(
34     uint16_t instance_num) {
35   auto port = netsim::osutils::GetServerAddress(instance_num);
36   if (!port.has_value()) {
37     return nullptr;
38   }
39   auto server = "localhost:" + port.value();
40   std::shared_ptr<grpc::Channel> channel =
41       grpc::CreateChannel(server, grpc::InsecureChannelCredentials());
42 
43   auto deadline = std::chrono::system_clock::now() + kConnectionDeadline;
44   if (!channel->WaitForConnected(deadline)) {
45     return nullptr;
46   }
47 
48   return frontend::FrontendService::NewStub(channel);
49 }
50 }  // namespace
51 
IsNetsimdAlive(uint16_t instance_num)52 bool IsNetsimdAlive(uint16_t instance_num) {
53   return NewFrontendClient(instance_num) != nullptr;
54 }
55 
56 }  // namespace frontend
57 }  // namespace netsim
58