blob: 558ab2f250689443005ed140bccb8bc57964b74b [file] [log] [blame]
Hao Chen32d46702023-04-10 15:59:50 -07001/*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "GRPCVehicleProxyServer.h"
18
19#include "ProtoMessageConverter.h"
20
21#include <grpc++/grpc++.h>
22
23#include <android-base/logging.h>
24
25#include <algorithm>
26#include <condition_variable>
27#include <mutex>
28#include <unordered_set>
29#include <utility>
30#include <vector>
31
32namespace android::hardware::automotive::vehicle::virtualization {
33
34std::atomic<uint64_t> GrpcVehicleProxyServer::ConnectionDescriptor::connection_id_counter_{0};
35
36static std::shared_ptr<::grpc::ServerCredentials> getServerCredentials() {
37 // TODO(chenhaosjtuacm): get secured credentials here
38 return ::grpc::InsecureServerCredentials();
39}
40
41GrpcVehicleProxyServer::GrpcVehicleProxyServer(std::string serverAddr,
42 std::unique_ptr<IVehicleHardware>&& hardware)
43 : mServiceAddr(std::move(serverAddr)), mHardware(std::move(hardware)) {
44 mHardware->registerOnPropertyChangeEvent(
45 std::make_unique<const IVehicleHardware::PropertyChangeCallback>(
46 [this](std::vector<aidlvhal::VehiclePropValue> values) {
47 OnVehiclePropChange(values);
48 }));
49}
50
51::grpc::Status GrpcVehicleProxyServer::GetAllPropertyConfig(
52 ::grpc::ServerContext* context, const ::google::protobuf::Empty* request,
53 ::grpc::ServerWriter<proto::VehiclePropConfig>* stream) {
54 for (const auto& config : mHardware->getAllPropertyConfigs()) {
55 proto::VehiclePropConfig protoConfig;
56 proto_msg_converter::aidlToProto(config, &protoConfig);
57 if (!stream->Write(protoConfig)) {
58 return ::grpc::Status(::grpc::StatusCode::ABORTED, "Connection lost.");
59 }
60 }
61 return ::grpc::Status::OK;
62}
63
64::grpc::Status GrpcVehicleProxyServer::SetValues(::grpc::ServerContext* context,
65 const proto::VehiclePropValueRequests* requests,
66 proto::SetValueResults* results) {
67 std::vector<aidlvhal::SetValueRequest> aidlRequests;
68 for (const auto& protoRequest : requests->requests()) {
69 auto& aidlRequest = aidlRequests.emplace_back();
70 aidlRequest.requestId = protoRequest.request_id();
71 proto_msg_converter::protoToAidl(protoRequest.value(), &aidlRequest.value);
72 }
73 auto waitMtx = std::make_shared<std::mutex>();
74 auto waitCV = std::make_shared<std::condition_variable>();
75 auto complete = std::make_shared<bool>(false);
76 auto tmpResults = std::make_shared<proto::SetValueResults>();
77 auto aidlStatus = mHardware->setValues(
78 std::make_shared<const IVehicleHardware::SetValuesCallback>(
79 [waitMtx, waitCV, complete,
80 tmpResults](std::vector<aidlvhal::SetValueResult> setValueResults) {
81 for (const auto& aidlResult : setValueResults) {
82 auto& protoResult = *tmpResults->add_results();
83 protoResult.set_request_id(aidlResult.requestId);
84 protoResult.set_status(
85 static_cast<proto::StatusCode>(aidlResult.status));
86 }
87 {
88 std::lock_guard lck(*waitMtx);
89 *complete = true;
90 }
91 waitCV->notify_all();
92 }),
93 aidlRequests);
94 if (aidlStatus != aidlvhal::StatusCode::OK) {
95 return ::grpc::Status(::grpc::StatusCode::INTERNAL,
96 "The underlying hardware fails to set values, VHAL status: " +
97 toString(aidlStatus));
98 }
99 std::unique_lock lck(*waitMtx);
100 bool success = waitCV->wait_for(lck, kHardwareOpTimeout, [complete] { return *complete; });
101 if (!success) {
102 return ::grpc::Status(::grpc::StatusCode::INTERNAL,
103 "The underlying hardware set values timeout.");
104 }
105 *results = std::move(*tmpResults);
106 return ::grpc::Status::OK;
107}
108
109::grpc::Status GrpcVehicleProxyServer::GetValues(::grpc::ServerContext* context,
110 const proto::VehiclePropValueRequests* requests,
111 proto::GetValueResults* results) {
112 std::vector<aidlvhal::GetValueRequest> aidlRequests;
113 for (const auto& protoRequest : requests->requests()) {
114 auto& aidlRequest = aidlRequests.emplace_back();
115 aidlRequest.requestId = protoRequest.request_id();
116 proto_msg_converter::protoToAidl(protoRequest.value(), &aidlRequest.prop);
117 }
118 auto waitMtx = std::make_shared<std::mutex>();
119 auto waitCV = std::make_shared<std::condition_variable>();
120 auto complete = std::make_shared<bool>(false);
121 auto tmpResults = std::make_shared<proto::GetValueResults>();
122 auto aidlStatus = mHardware->getValues(
123 std::make_shared<const IVehicleHardware::GetValuesCallback>(
124 [waitMtx, waitCV, complete,
125 tmpResults](std::vector<aidlvhal::GetValueResult> getValueResults) {
126 for (const auto& aidlResult : getValueResults) {
127 auto& protoResult = *tmpResults->add_results();
128 protoResult.set_request_id(aidlResult.requestId);
129 protoResult.set_status(
130 static_cast<proto::StatusCode>(aidlResult.status));
131 if (aidlResult.prop) {
132 auto* valuePtr = protoResult.mutable_value();
133 proto_msg_converter::aidlToProto(*aidlResult.prop, valuePtr);
134 }
135 }
136 {
137 std::lock_guard lck(*waitMtx);
138 *complete = true;
139 }
140 waitCV->notify_all();
141 }),
142 aidlRequests);
143 if (aidlStatus != aidlvhal::StatusCode::OK) {
144 return ::grpc::Status(::grpc::StatusCode::INTERNAL,
145 "The underlying hardware fails to get values, VHAL status: " +
146 toString(aidlStatus));
147 }
148 std::unique_lock lck(*waitMtx);
149 bool success = waitCV->wait_for(lck, kHardwareOpTimeout, [complete] { return *complete; });
150 if (!success) {
151 return ::grpc::Status(::grpc::StatusCode::INTERNAL,
152 "The underlying hardware get values timeout.");
153 }
154 *results = std::move(*tmpResults);
155 return ::grpc::Status::OK;
156}
157
Hao Chena810fb22023-04-11 15:27:44 -0700158::grpc::Status GrpcVehicleProxyServer::UpdateSampleRate(
159 ::grpc::ServerContext* context, const proto::UpdateSampleRateRequest* request,
160 proto::VehicleHalCallStatus* status) {
161 const auto status_code = mHardware->updateSampleRate(request->prop(), request->area_id(),
162 request->sample_rate());
163 status->set_status_code(static_cast<proto::StatusCode>(status_code));
164 return ::grpc::Status::OK;
165}
166
Yu Shan5c846f72024-05-16 15:39:51 -0700167::grpc::Status GrpcVehicleProxyServer::Subscribe(::grpc::ServerContext* context,
168 const proto::SubscribeRequest* request,
169 proto::VehicleHalCallStatus* status) {
170 const auto& protoSubscribeOptions = request->options();
171 aidlvhal::SubscribeOptions aidlSubscribeOptions = {};
172 proto_msg_converter::protoToAidl(protoSubscribeOptions, &aidlSubscribeOptions);
173 const auto status_code = mHardware->subscribe(aidlSubscribeOptions);
174 status->set_status_code(static_cast<proto::StatusCode>(status_code));
175 return ::grpc::Status::OK;
176}
177
Hao Chena810fb22023-04-11 15:27:44 -0700178::grpc::Status GrpcVehicleProxyServer::CheckHealth(::grpc::ServerContext* context,
179 const ::google::protobuf::Empty*,
180 proto::VehicleHalCallStatus* status) {
181 status->set_status_code(static_cast<proto::StatusCode>(mHardware->checkHealth()));
182 return ::grpc::Status::OK;
183}
184
185::grpc::Status GrpcVehicleProxyServer::Dump(::grpc::ServerContext* context,
186 const proto::DumpOptions* options,
187 proto::DumpResult* result) {
188 std::vector<std::string> dumpOptionStrings(options->options().begin(),
189 options->options().end());
190 auto dumpResult = mHardware->dump(dumpOptionStrings);
191 result->set_caller_should_dump_state(dumpResult.callerShouldDumpState);
192 result->set_buffer(dumpResult.buffer);
193 return ::grpc::Status::OK;
194}
195
Hao Chen32d46702023-04-10 15:59:50 -0700196::grpc::Status GrpcVehicleProxyServer::StartPropertyValuesStream(
197 ::grpc::ServerContext* context, const ::google::protobuf::Empty* request,
198 ::grpc::ServerWriter<proto::VehiclePropValues>* stream) {
199 auto conn = std::make_shared<ConnectionDescriptor>(stream);
200 {
201 std::lock_guard lck(mConnectionMutex);
202 mValueStreamingConnections.push_back(conn);
203 }
204 conn->Wait();
205 LOG(ERROR) << __func__ << ": Stream lost, ID : " << conn->ID();
206 return ::grpc::Status(::grpc::StatusCode::ABORTED, "Connection lost.");
207}
208
209void GrpcVehicleProxyServer::OnVehiclePropChange(
210 const std::vector<aidlvhal::VehiclePropValue>& values) {
211 std::unordered_set<uint64_t> brokenConn;
212 proto::VehiclePropValues protoValues;
213 for (const auto& value : values) {
214 auto* protoValuePtr = protoValues.add_values();
215 proto_msg_converter::aidlToProto(value, protoValuePtr);
216 }
217 {
218 std::shared_lock read_lock(mConnectionMutex);
219 for (auto& connection : mValueStreamingConnections) {
220 auto writeOK = connection->Write(protoValues);
221 if (!writeOK) {
222 LOG(ERROR) << __func__
223 << ": Server Write failed, connection lost. ID: " << connection->ID();
224 brokenConn.insert(connection->ID());
225 }
226 }
227 }
228 if (brokenConn.empty()) {
229 return;
230 }
231 std::unique_lock write_lock(mConnectionMutex);
232 mValueStreamingConnections.erase(
233 std::remove_if(mValueStreamingConnections.begin(), mValueStreamingConnections.end(),
234 [&brokenConn](const auto& conn) {
235 return brokenConn.find(conn->ID()) != brokenConn.end();
236 }),
237 mValueStreamingConnections.end());
238}
239
240GrpcVehicleProxyServer& GrpcVehicleProxyServer::Start() {
241 if (mServer) {
242 LOG(WARNING) << __func__ << ": GrpcVehicleProxyServer has already started.";
243 return *this;
244 }
245 ::grpc::ServerBuilder builder;
246 builder.RegisterService(this);
247 builder.AddListeningPort(mServiceAddr, getServerCredentials());
248 mServer = builder.BuildAndStart();
249 CHECK(mServer) << __func__ << ": failed to create the GRPC server, "
250 << "please make sure the configuration and permissions are correct";
251 return *this;
252}
253
254GrpcVehicleProxyServer& GrpcVehicleProxyServer::Shutdown() {
255 std::shared_lock read_lock(mConnectionMutex);
256 for (auto& conn : mValueStreamingConnections) {
257 conn->Shutdown();
258 }
259 if (mServer) {
260 mServer->Shutdown();
261 }
262 return *this;
263}
264
265void GrpcVehicleProxyServer::Wait() {
266 if (mServer) {
267 mServer->Wait();
268 }
269 mServer.reset();
270}
271
272GrpcVehicleProxyServer::ConnectionDescriptor::~ConnectionDescriptor() {
273 Shutdown();
274}
275
276bool GrpcVehicleProxyServer::ConnectionDescriptor::Write(const proto::VehiclePropValues& values) {
277 if (!mStream) {
278 LOG(ERROR) << __func__ << ": Empty stream. ID: " << ID();
279 Shutdown();
280 return false;
281 }
282 {
283 std::lock_guard lck(*mMtx);
284 if (!mShutdownFlag && mStream->Write(values)) {
285 return true;
286 } else {
287 LOG(ERROR) << __func__ << ": Server Write failed, connection lost. ID: " << ID();
288 }
289 }
290 Shutdown();
291 return false;
292}
293
294void GrpcVehicleProxyServer::ConnectionDescriptor::Wait() {
295 std::unique_lock lck(*mMtx);
296 mCV->wait(lck, [this] { return mShutdownFlag; });
297}
298
299void GrpcVehicleProxyServer::ConnectionDescriptor::Shutdown() {
300 {
301 std::lock_guard lck(*mMtx);
302 mShutdownFlag = true;
303 }
304 mCV->notify_all();
305}
306
307} // namespace android::hardware::automotive::vehicle::virtualization