repo_id
stringlengths 19
138
| file_path
stringlengths 32
200
| content
stringlengths 1
12.9M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/node/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "cyber_node_hdrs",
srcs = glob([
"*.h",
]),
)
cc_library(
name = "node",
srcs = ["node.cc"],
hdrs = ["node.h"],
deps = [
":node_channel_impl",
":node_service_impl",
],
)
cc_library(
name = "node_channel_impl",
hdrs = ["node_channel_impl.h"],
deps = [
":reader",
":writer",
"//cyber/blocker:intra_reader",
"//cyber/blocker:intra_writer",
"//cyber/common:global_data",
"//cyber/message:message_traits",
"//cyber/proto:run_mode_conf_cc_proto",
],
)
cc_test(
name = "node_channel_impl_test",
size = "small",
srcs = ["node_channel_impl_test.cc"],
deps = [
"//cyber",
"//cyber/proto:unit_test_cc_proto",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_library(
name = "node_service_impl",
hdrs = ["node_service_impl.h"],
deps = [
":reader",
":writer",
"//cyber/common:global_data",
"//cyber/service",
"//cyber/service:client",
"//cyber/service_discovery:topology_manager",
],
)
cc_test(
name = "node_test",
size = "small",
srcs = ["node_test.cc"],
deps = [
"//cyber",
"//cyber/proto:unit_test_cc_proto",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_library(
name = "reader",
hdrs = ["reader.h"],
deps = [
":reader_base",
"//cyber/blocker",
"//cyber/common:global_data",
"//cyber/croutine:routine_factory",
"//cyber/data:data_visitor",
"//cyber/proto:topology_change_cc_proto",
"//cyber/scheduler",
"//cyber/service_discovery:topology_manager",
"//cyber/time",
"//cyber/transport",
],
)
cc_library(
name = "reader_base",
hdrs = ["reader_base.h"],
deps = [
"//cyber/event:perf_event_cache",
"//cyber/transport",
],
)
cc_test(
name = "reader_test",
size = "small",
srcs = ["reader_test.cc"],
deps = [
"//cyber",
"//cyber/proto:unit_test_cc_proto",
"@com_google_googletest//:gtest",
],
linkstatic = True,
)
cc_library(
name = "writer",
hdrs = ["writer.h"],
deps = [
":writer_base",
"//cyber/common:log",
"//cyber/proto:topology_change_cc_proto",
"//cyber/service_discovery:topology_manager",
"//cyber/transport",
],
)
cc_library(
name = "writer_base",
hdrs = ["writer_base.h"],
deps = [
"//cyber/common:macros",
"//cyber/common:util",
"//cyber/proto:role_attributes_cc_proto",
],
)
cc_test(
name = "writer_reader_test",
size = "small",
srcs = ["writer_reader_test.cc"],
deps = [
"//cyber",
"//cyber/proto:unit_test_cc_proto",
"@com_google_googletest//:gtest",
],
linkstatic = True,
)
cc_test(
name = "writer_test",
size = "small",
srcs = ["writer_test.cc"],
deps = [
"//cyber",
"//cyber/node:writer_base",
"//cyber/proto:unit_test_cc_proto",
"@com_google_googletest//:gtest",
],
linkstatic = True,
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/node/node_channel_impl_test.cc
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/node/node_channel_impl.h"
#include <iostream>
#include "gtest/gtest.h"
#include "cyber/proto/unit_test.pb.h"
#include "cyber/cyber.h"
#include "cyber/init.h"
#include "cyber/node/node.h"
namespace apollo {
namespace cyber {
namespace node_channel_impl {
TEST(Node_Channel_ImplTest, test1) {
auto globalData = common::GlobalData::Instance();
globalData->DisableSimulationMode();
{
NodeChannelImpl nImpl("TestConstructor");
EXPECT_EQ(nImpl.NodeName(), "TestConstructor");
}
globalData->EnableSimulationMode();
{
NodeChannelImpl nImpl("TestConstructor");
EXPECT_EQ(nImpl.NodeName(), "TestConstructor");
}
}
TEST(Node_Channel_ImplTest, test2) {
auto globalData = common::GlobalData::Instance();
std::string nodeName("TestConstructor");
std::string nameSpace("");
std::string channelName("/chatter1");
{
globalData->DisableSimulationMode();
auto n = CreateNode(nodeName, nameSpace);
EXPECT_EQ(n->Name(), nodeName);
proto::RoleAttributes role_attr;
auto w = n->CreateWriter<proto::Chatter>(role_attr);
EXPECT_EQ(w, nullptr);
role_attr.set_channel_name(std::string());
w = n->CreateWriter<proto::Chatter>(role_attr);
EXPECT_EQ(w, nullptr);
role_attr.set_channel_name(channelName);
w = n->CreateWriter<proto::Chatter>(role_attr);
EXPECT_NE(w, nullptr);
}
{
globalData->EnableSimulationMode();
auto n = CreateNode(nodeName, nameSpace);
EXPECT_EQ(n->Name(), nodeName);
proto::RoleAttributes role_attr;
auto w = n->CreateWriter<proto::Chatter>(role_attr);
EXPECT_EQ(w, nullptr);
role_attr.set_channel_name(std::string());
w = n->CreateWriter<proto::Chatter>(role_attr);
EXPECT_EQ(w, nullptr);
role_attr.set_channel_name(channelName);
w = n->CreateWriter<proto::Chatter>(role_attr);
EXPECT_NE(w, nullptr);
w = n->CreateWriter<proto::Chatter>(channelName);
EXPECT_NE(w, nullptr);
}
}
TEST(Node_Channel_ImplTest, test3) {
auto globalData = common::GlobalData::Instance();
std::string nodeName("TestConstructor");
std::string nameSpace("");
auto callback = [](const std::shared_ptr<proto::Chatter>& msg) {
std::cout << "msg size = " << msg->ByteSizeLong() << std::endl;
};
{
globalData->DisableSimulationMode();
auto n = CreateNode(nodeName, nameSpace);
EXPECT_EQ(n->Name(), nodeName);
n->Observe();
n->ClearData();
auto r = n->CreateReader<proto::Chatter>("/chatter1", callback);
EXPECT_NE(r, nullptr);
proto::RoleAttributes role_attr;
r = n->CreateReader<proto::Chatter>(role_attr, callback);
EXPECT_EQ(r, nullptr);
role_attr.set_channel_name(std::string());
r = n->CreateReader<proto::Chatter>(role_attr, callback);
EXPECT_EQ(r, nullptr);
role_attr.set_channel_name("/chatter2");
r = n->CreateReader<proto::Chatter>(role_attr, callback);
EXPECT_NE(r, nullptr);
r = n->CreateReader<proto::Chatter>(role_attr);
EXPECT_EQ(r, nullptr);
ReaderConfig rc;
rc.channel_name.assign("/chatter3");
r = n->CreateReader<proto::Chatter>(rc, callback);
EXPECT_NE(r, nullptr);
n->Observe();
n->ClearData();
}
{
globalData->EnableSimulationMode();
auto n = CreateNode(nodeName, nameSpace);
EXPECT_EQ(n->Name(), nodeName);
n->Observe();
n->ClearData();
auto r = n->CreateReader<proto::Chatter>("/chatter1", callback);
EXPECT_NE(r, nullptr);
proto::RoleAttributes role_attr;
r = n->CreateReader<proto::Chatter>(role_attr, callback);
EXPECT_EQ(r, nullptr);
role_attr.set_channel_name(std::string());
r = n->CreateReader<proto::Chatter>(role_attr, callback);
EXPECT_EQ(r, nullptr);
role_attr.set_channel_name("/chatter2");
r = n->CreateReader<proto::Chatter>(role_attr, callback);
EXPECT_NE(r, nullptr);
r = n->CreateReader<proto::Chatter>(role_attr);
EXPECT_EQ(r, nullptr);
ReaderConfig rc;
rc.channel_name.assign("/chatter3");
r = n->CreateReader<proto::Chatter>(rc, callback);
EXPECT_NE(r, nullptr);
n->Observe();
n->ClearData();
}
}
} // namespace node_channel_impl
} // namespace cyber
} // namespace apollo
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
apollo::cyber::Init(argv[0]);
return RUN_ALL_TESTS();
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/node/writer_test.cc
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/node/writer.h"
#include "gtest/gtest.h"
#include "cyber/proto/unit_test.pb.h"
#include "cyber/cyber.h"
#include "cyber/init.h"
namespace apollo {
namespace cyber {
namespace writer {
using proto::Chatter;
TEST(WriterTest, test1) {
proto::RoleAttributes role;
Writer<Chatter> w(role);
EXPECT_TRUE(w.Init());
EXPECT_TRUE(w.IsInit());
EXPECT_TRUE(w.GetChannelName().empty());
EXPECT_FALSE(w.HasReader());
}
TEST(WriterTest, test2) {
proto::RoleAttributes role;
auto qos = role.mutable_qos_profile();
qos->set_history(proto::QosHistoryPolicy::HISTORY_KEEP_LAST);
qos->set_depth(0);
qos->set_mps(0);
qos->set_reliability(proto::QosReliabilityPolicy::RELIABILITY_RELIABLE);
qos->set_durability(proto::QosDurabilityPolicy::DURABILITY_VOLATILE);
role.set_channel_name("/chatter0");
role.set_node_name("chatter_node");
Writer<Chatter> w(role);
EXPECT_TRUE(w.Init());
EXPECT_EQ(w.GetChannelName(), "/chatter0");
{
auto c = std::make_shared<Chatter>();
c->set_timestamp(Time::Now().ToNanosecond());
c->set_lidar_timestamp(Time::Now().ToNanosecond());
c->set_seq(3);
c->set_content("ChatterMsg");
EXPECT_TRUE(w.Write(c));
}
EXPECT_TRUE(w.Init());
w.Shutdown();
auto c = std::make_shared<Chatter>();
c->set_timestamp(Time::Now().ToNanosecond());
c->set_lidar_timestamp(Time::Now().ToNanosecond());
c->set_seq(3);
c->set_content("ChatterMsg");
EXPECT_FALSE(w.Write(c));
}
} // namespace writer
} // namespace cyber
} // namespace apollo
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
apollo::cyber::Init(argv[0]);
return RUN_ALL_TESTS();
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/service/client.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_CLIENT_H_
#define CYBER_SERVICE_CLIENT_H_
#include <future>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include "cyber/common/log.h"
#include "cyber/common/types.h"
#include "cyber/node/node_channel_impl.h"
#include "cyber/service/client_base.h"
namespace apollo {
namespace cyber {
/**
* @class Client
* @brief Client get `Response` from a responding `Service` by sending a Request
*
* @tparam Request the `Service` request type
* @tparam Response the `Service` response type
*
* @warning One Client can only request one Service
*/
template <typename Request, typename Response>
class Client : public ClientBase {
public:
using SharedRequest = typename std::shared_ptr<Request>;
using SharedResponse = typename std::shared_ptr<Response>;
using Promise = std::promise<SharedResponse>;
using SharedPromise = std::shared_ptr<Promise>;
using SharedFuture = std::shared_future<SharedResponse>;
using CallbackType = std::function<void(SharedFuture)>;
/**
* @brief Construct a new Client object
*
* @param node_name used to fill RoleAttribute
* @param service_name service name the Client can request
*/
Client(const std::string& node_name, const std::string& service_name)
: ClientBase(service_name),
node_name_(node_name),
request_channel_(service_name + SRV_CHANNEL_REQ_SUFFIX),
response_channel_(service_name + SRV_CHANNEL_RES_SUFFIX),
sequence_number_(0) {}
/**
* @brief forbid Constructing a new Client object with empty params
*/
Client() = delete;
virtual ~Client() {}
/**
* @brief Init the Client
*
* @return true if init successfully
* @return false if init failed
*/
bool Init();
/**
* @brief Request the Service with a shared ptr Request type
*
* @param request shared ptr of Request type
* @param timeout_s request timeout, if timeout, response will be empty
* @return SharedResponse result of this request
*/
SharedResponse SendRequest(
SharedRequest request,
const std::chrono::seconds& timeout_s = std::chrono::seconds(5));
/**
* @brief Request the Service with a Request object
*
* @param request Request object
* @param timeout_s request timeout, if timeout, response will be empty
* @return SharedResponse result of this request
*/
SharedResponse SendRequest(
const Request& request,
const std::chrono::seconds& timeout_s = std::chrono::seconds(5));
/**
* @brief Send Request shared ptr asynchronously
*/
SharedFuture AsyncSendRequest(SharedRequest request);
/**
* @brief Send Request object asynchronously
*/
SharedFuture AsyncSendRequest(const Request& request);
/**
* @brief Send Request shared ptr asynchronously and invoke `cb` after we get
* response
*
* @param request Request shared ptr
* @param cb callback function after we get response
* @return SharedFuture a `std::future` shared ptr
*/
SharedFuture AsyncSendRequest(SharedRequest request, CallbackType&& cb);
/**
* @brief Is the Service is ready?
*/
bool ServiceIsReady() const;
/**
* @brief destroy this Client
*/
void Destroy();
/**
* @brief wait for the connection with the Service established
*
* @tparam RatioT timeout unit, default is std::milli
* @param timeout wait time in unit of `RatioT`
* @return true if the connection established
* @return false if timeout
*/
template <typename RatioT = std::milli>
bool WaitForService(std::chrono::duration<int64_t, RatioT> timeout =
std::chrono::duration<int64_t, RatioT>(-1)) {
return WaitForServiceNanoseconds(
std::chrono::duration_cast<std::chrono::nanoseconds>(timeout));
}
private:
void HandleResponse(const std::shared_ptr<Response>& response,
const transport::MessageInfo& request_info);
bool IsInit(void) const { return response_receiver_ != nullptr; }
std::string node_name_;
std::function<void(const std::shared_ptr<Response>&,
const transport::MessageInfo&)>
response_callback_;
std::unordered_map<uint64_t,
std::tuple<SharedPromise, CallbackType, SharedFuture>>
pending_requests_;
std::mutex pending_requests_mutex_;
std::shared_ptr<transport::Transmitter<Request>> request_transmitter_;
std::shared_ptr<transport::Receiver<Response>> response_receiver_;
std::string request_channel_;
std::string response_channel_;
transport::Identity writer_id_;
uint64_t sequence_number_;
};
template <typename Request, typename Response>
void Client<Request, Response>::Destroy() {}
template <typename Request, typename Response>
bool Client<Request, Response>::Init() {
proto::RoleAttributes role;
role.set_node_name(node_name_);
role.set_channel_name(request_channel_);
auto channel_id = common::GlobalData::RegisterChannel(request_channel_);
role.set_channel_id(channel_id);
role.mutable_qos_profile()->CopyFrom(
transport::QosProfileConf::QOS_PROFILE_SERVICES_DEFAULT);
auto transport = transport::Transport::Instance();
request_transmitter_ =
transport->CreateTransmitter<Request>(role, proto::OptionalMode::RTPS);
if (request_transmitter_ == nullptr) {
AERROR << "Create request pub failed.";
return false;
}
writer_id_ = request_transmitter_->id();
response_callback_ =
std::bind(&Client<Request, Response>::HandleResponse, this,
std::placeholders::_1, std::placeholders::_2);
role.set_channel_name(response_channel_);
channel_id = common::GlobalData::RegisterChannel(response_channel_);
role.set_channel_id(channel_id);
response_receiver_ = transport->CreateReceiver<Response>(
role,
[=](const std::shared_ptr<Response>& response,
const transport::MessageInfo& message_info,
const proto::RoleAttributes& reader_attr) {
(void)message_info;
(void)reader_attr;
response_callback_(response, message_info);
},
proto::OptionalMode::RTPS);
if (response_receiver_ == nullptr) {
AERROR << "Create response sub failed.";
request_transmitter_.reset();
return false;
}
return true;
}
template <typename Request, typename Response>
typename Client<Request, Response>::SharedResponse
Client<Request, Response>::SendRequest(SharedRequest request,
const std::chrono::seconds& timeout_s) {
if (!IsInit()) {
return nullptr;
}
auto future = AsyncSendRequest(request);
if (!future.valid()) {
return nullptr;
}
auto status = future.wait_for(timeout_s);
if (status == std::future_status::ready) {
return future.get();
} else {
return nullptr;
}
}
template <typename Request, typename Response>
typename Client<Request, Response>::SharedResponse
Client<Request, Response>::SendRequest(const Request& request,
const std::chrono::seconds& timeout_s) {
if (!IsInit()) {
return nullptr;
}
auto request_ptr = std::make_shared<const Request>(request);
return SendRequest(request_ptr, timeout_s);
}
template <typename Request, typename Response>
typename Client<Request, Response>::SharedFuture
Client<Request, Response>::AsyncSendRequest(const Request& request) {
auto request_ptr = std::make_shared<const Request>(request);
return AsyncSendRequest(request_ptr);
}
template <typename Request, typename Response>
typename Client<Request, Response>::SharedFuture
Client<Request, Response>::AsyncSendRequest(SharedRequest request) {
return AsyncSendRequest(request, [](SharedFuture) {});
}
template <typename Request, typename Response>
typename Client<Request, Response>::SharedFuture
Client<Request, Response>::AsyncSendRequest(SharedRequest request,
CallbackType&& cb) {
if (IsInit()) {
std::lock_guard<std::mutex> lock(pending_requests_mutex_);
sequence_number_++;
transport::MessageInfo info(writer_id_, sequence_number_, writer_id_);
request_transmitter_->Transmit(request, info);
SharedPromise call_promise = std::make_shared<Promise>();
SharedFuture f(call_promise->get_future());
pending_requests_[info.seq_num()] =
std::make_tuple(call_promise, std::forward<CallbackType>(cb), f);
return f;
} else {
return std::shared_future<std::shared_ptr<Response>>();
}
}
template <typename Request, typename Response>
bool Client<Request, Response>::ServiceIsReady() const {
return true;
}
template <typename Request, typename Response>
void Client<Request, Response>::HandleResponse(
const std::shared_ptr<Response>& response,
const transport::MessageInfo& request_header) {
ADEBUG << "client recv response.";
std::lock_guard<std::mutex> lock(pending_requests_mutex_);
if (request_header.spare_id() != writer_id_) {
return;
}
uint64_t sequence_number = request_header.seq_num();
if (this->pending_requests_.count(sequence_number) == 0) {
return;
}
auto tuple = this->pending_requests_[sequence_number];
auto call_promise = std::get<0>(tuple);
auto callback = std::get<1>(tuple);
auto future = std::get<2>(tuple);
this->pending_requests_.erase(sequence_number);
call_promise->set_value(response);
callback(future);
}
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_CLIENT_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/service/service.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_SERVICE_H_
#define CYBER_SERVICE_SERVICE_H_
#include <list>
#include <memory>
#include <string>
#include <utility>
#include "cyber/common/types.h"
#include "cyber/node/node_channel_impl.h"
#include "cyber/scheduler/scheduler.h"
#include "cyber/service/service_base.h"
namespace apollo {
namespace cyber {
/**
* @class Service
* @brief Service handles `Request` from the Client, and send a `Response` to
* it.
*
* @tparam Request the request type
* @tparam Response the response type
*/
template <typename Request, typename Response>
class Service : public ServiceBase {
public:
using ServiceCallback = std::function<void(const std::shared_ptr<Request>&,
std::shared_ptr<Response>&)>;
/**
* @brief Construct a new Service object
*
* @param node_name used to fill RoleAttribute when join the topology
* @param service_name the service name we provide
* @param service_callback reference of `ServiceCallback` object
*/
Service(const std::string& node_name, const std::string& service_name,
const ServiceCallback& service_callback)
: ServiceBase(service_name),
node_name_(node_name),
service_callback_(service_callback),
request_channel_(service_name + SRV_CHANNEL_REQ_SUFFIX),
response_channel_(service_name + SRV_CHANNEL_RES_SUFFIX) {}
/**
* @brief Construct a new Service object
*
* @param node_name used to fill RoleAttribute when join the topology
* @param service_name the service name we provide
* @param service_callback rvalue reference of `ServiceCallback` object
*/
Service(const std::string& node_name, const std::string& service_name,
ServiceCallback&& service_callback)
: ServiceBase(service_name),
node_name_(node_name),
service_callback_(service_callback),
request_channel_(service_name + SRV_CHANNEL_REQ_SUFFIX),
response_channel_(service_name + SRV_CHANNEL_RES_SUFFIX) {}
/**
* @brief Forbid default constructing
*/
Service() = delete;
~Service() { destroy(); }
/**
* @brief Init the Service
*/
bool Init();
/**
* @brief Destroy the Service
*/
void destroy();
private:
void HandleRequest(const std::shared_ptr<Request>& request,
const transport::MessageInfo& message_info);
void SendResponse(const transport::MessageInfo& message_info,
const std::shared_ptr<Response>& response);
bool IsInit(void) const { return request_receiver_ != nullptr; }
std::string node_name_;
ServiceCallback service_callback_;
std::function<void(const std::shared_ptr<Request>&,
const transport::MessageInfo&)>
request_callback_;
std::shared_ptr<transport::Transmitter<Response>> response_transmitter_;
std::shared_ptr<transport::Receiver<Request>> request_receiver_;
std::string request_channel_;
std::string response_channel_;
std::mutex service_handle_request_mutex_;
volatile bool inited_ = false;
void Enqueue(std::function<void()>&& task);
void Process();
std::thread thread_;
std::mutex queue_mutex_;
std::condition_variable condition_;
std::list<std::function<void()>> tasks_;
};
template <typename Request, typename Response>
void Service<Request, Response>::destroy() {
inited_ = false;
{
std::lock_guard<std::mutex> lg(queue_mutex_);
this->tasks_.clear();
}
condition_.notify_all();
if (thread_.joinable()) {
thread_.join();
}
}
template <typename Request, typename Response>
inline void Service<Request, Response>::Enqueue(std::function<void()>&& task) {
std::lock_guard<std::mutex> lg(queue_mutex_);
tasks_.emplace_back(std::move(task));
condition_.notify_one();
}
template <typename Request, typename Response>
void Service<Request, Response>::Process() {
while (!cyber::IsShutdown()) {
std::unique_lock<std::mutex> ul(queue_mutex_);
condition_.wait(ul, [this]() { return !inited_ || !this->tasks_.empty(); });
if (!inited_) {
break;
}
if (!tasks_.empty()) {
auto task = tasks_.front();
tasks_.pop_front();
ul.unlock();
task();
}
}
}
template <typename Request, typename Response>
bool Service<Request, Response>::Init() {
if (IsInit()) {
return true;
}
proto::RoleAttributes role;
role.set_node_name(node_name_);
role.set_channel_name(response_channel_);
auto channel_id = common::GlobalData::RegisterChannel(response_channel_);
role.set_channel_id(channel_id);
role.mutable_qos_profile()->CopyFrom(
transport::QosProfileConf::QOS_PROFILE_SERVICES_DEFAULT);
auto transport = transport::Transport::Instance();
response_transmitter_ =
transport->CreateTransmitter<Response>(role, proto::OptionalMode::RTPS);
if (response_transmitter_ == nullptr) {
AERROR << " Create response pub failed.";
return false;
}
request_callback_ =
std::bind(&Service<Request, Response>::HandleRequest, this,
std::placeholders::_1, std::placeholders::_2);
role.set_channel_name(request_channel_);
channel_id = common::GlobalData::RegisterChannel(request_channel_);
role.set_channel_id(channel_id);
request_receiver_ = transport->CreateReceiver<Request>(
role,
[=](const std::shared_ptr<Request>& request,
const transport::MessageInfo& message_info,
const proto::RoleAttributes& reader_attr) {
(void)reader_attr;
auto task = [this, request, message_info]() {
this->HandleRequest(request, message_info);
};
Enqueue(std::move(task));
},
proto::OptionalMode::RTPS);
inited_ = true;
thread_ = std::thread(&Service<Request, Response>::Process, this);
if (request_receiver_ == nullptr) {
AERROR << " Create request sub failed." << request_channel_;
response_transmitter_.reset();
return false;
}
return true;
}
template <typename Request, typename Response>
void Service<Request, Response>::HandleRequest(
const std::shared_ptr<Request>& request,
const transport::MessageInfo& message_info) {
if (!IsInit()) {
// LOG_DEBUG << "not inited error.";
return;
}
ADEBUG << "handling request:" << request_channel_;
std::lock_guard<std::mutex> lk(service_handle_request_mutex_);
auto response = std::make_shared<Response>();
service_callback_(request, response);
transport::MessageInfo msg_info(message_info);
msg_info.set_sender_id(response_transmitter_->id());
SendResponse(msg_info, response);
}
template <typename Request, typename Response>
void Service<Request, Response>::SendResponse(
const transport::MessageInfo& message_info,
const std::shared_ptr<Response>& response) {
if (!IsInit()) {
// LOG_DEBUG << "not inited error.";
return;
}
// publish return value ?
// LOG_DEBUG << "send response id:" << message_id.sequence_number;
response_transmitter_->Transmit(response, message_info);
}
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_SERVICE_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/service/service_base.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_SERVICE_BASE_H_
#define CYBER_SERVICE_SERVICE_BASE_H_
#include <string>
namespace apollo {
namespace cyber {
/**
* @class ServiceBase
* @brief Base class for Service
*
*/
class ServiceBase {
public:
/**
* @brief Construct a new Service Base object
*
* @param service_name name of this Service
*/
explicit ServiceBase(const std::string& service_name)
: service_name_(service_name) {}
virtual ~ServiceBase() {}
virtual void destroy() = 0;
/**
* @brief Get the service name
*/
const std::string& service_name() const { return service_name_; }
protected:
std::string service_name_;
};
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_SERVICE_BASE_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/service/client_base.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_CLIENT_BASE_H_
#define CYBER_SERVICE_CLIENT_BASE_H_
#include <chrono>
#include <string>
#include "cyber/common/macros.h"
namespace apollo {
namespace cyber {
/**
* @class ClientBase
* @brief Base class of Client
*
*/
class ClientBase {
public:
/**
* @brief Construct a new Client Base object
*
* @param service_name the service we can request
*/
explicit ClientBase(const std::string& service_name)
: service_name_(service_name) {}
virtual ~ClientBase() {}
/**
* @brief Destroy the Client
*/
virtual void Destroy() = 0;
/**
* @brief Get the service name
*/
const std::string& ServiceName() const { return service_name_; }
/**
* @brief Ensure whether there is any Service named `service_name_`
*/
virtual bool ServiceIsReady() const = 0;
protected:
std::string service_name_;
bool WaitForServiceNanoseconds(std::chrono::nanoseconds time_out) {
bool has_service = false;
auto step_duration = std::chrono::nanoseconds(5 * 1000 * 1000);
while (time_out.count() > 0) {
has_service = service_discovery::TopologyManager::Instance()
->service_manager()
->HasService(service_name_);
if (!has_service) {
std::this_thread::sleep_for(step_duration);
time_out -= step_duration;
} else {
break;
}
}
return has_service;
}
};
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_CLIENT_BASE_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/service/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "cyber_service_hdrs",
srcs = glob([
"*.h",
]),
)
cc_library(
name = "client",
hdrs = ["client.h"],
deps = [
":client_base",
],
)
cc_library(
name = "client_base",
hdrs = ["client_base.h"],
)
cc_library(
name = "service",
hdrs = ["service.h"],
deps = [
":service_base",
"//cyber/scheduler",
],
)
cc_library(
name = "service_base",
hdrs = ["service_base.h"],
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/data/data_notifier.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_DATA_DATA_NOTIFIER_H_
#define CYBER_DATA_DATA_NOTIFIER_H_
#include <memory>
#include <mutex>
#include <vector>
#include "cyber/common/log.h"
#include "cyber/common/macros.h"
#include "cyber/data/cache_buffer.h"
#include "cyber/event/perf_event_cache.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
namespace data {
using apollo::cyber::Time;
using apollo::cyber::base::AtomicHashMap;
using apollo::cyber::event::PerfEventCache;
struct Notifier {
std::function<void()> callback;
};
class DataNotifier {
public:
using NotifyVector = std::vector<std::shared_ptr<Notifier>>;
~DataNotifier() {}
void AddNotifier(uint64_t channel_id,
const std::shared_ptr<Notifier>& notifier);
bool Notify(const uint64_t channel_id);
private:
std::mutex notifies_map_mutex_;
AtomicHashMap<uint64_t, NotifyVector> notifies_map_;
DECLARE_SINGLETON(DataNotifier)
};
inline DataNotifier::DataNotifier() {}
inline void DataNotifier::AddNotifier(
uint64_t channel_id, const std::shared_ptr<Notifier>& notifier) {
std::lock_guard<std::mutex> lock(notifies_map_mutex_);
NotifyVector* notifies = nullptr;
if (notifies_map_.Get(channel_id, ¬ifies)) {
notifies->emplace_back(notifier);
} else {
NotifyVector new_notify = {notifier};
notifies_map_.Set(channel_id, new_notify);
}
}
inline bool DataNotifier::Notify(const uint64_t channel_id) {
NotifyVector* notifies = nullptr;
if (notifies_map_.Get(channel_id, ¬ifies)) {
for (auto& notifier : *notifies) {
if (notifier && notifier->callback) {
notifier->callback();
}
}
return true;
}
return false;
}
} // namespace data
} // namespace cyber
} // namespace apollo
#endif // CYBER_DATA_DATA_NOTIFIER_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/data/channel_buffer_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/data/channel_buffer.h"
#include <memory>
#include <vector>
#include "gtest/gtest.h"
#include "cyber/common/util.h"
namespace apollo {
namespace cyber {
namespace data {
auto channel0 = common::Hash("/channel0");
TEST(ChannelBufferTest, Fetch) {
auto cache_buffer = new CacheBuffer<std::shared_ptr<int>>(2);
auto buffer = std::make_shared<ChannelBuffer<int>>(channel0, cache_buffer);
std::shared_ptr<int> msg;
uint64_t index = 0;
EXPECT_FALSE(buffer->Fetch(&index, msg));
buffer->Buffer()->Fill(std::make_shared<int>(1));
EXPECT_TRUE(buffer->Fetch(&index, msg));
EXPECT_EQ(1, *msg);
EXPECT_EQ(1, index);
index++;
EXPECT_FALSE(buffer->Fetch(&index, msg));
buffer->Buffer()->Fill(std::make_shared<int>(2));
buffer->Buffer()->Fill(std::make_shared<int>(3));
buffer->Buffer()->Fill(std::make_shared<int>(4));
EXPECT_TRUE(buffer->Fetch(&index, msg));
EXPECT_EQ(4, *msg);
EXPECT_EQ(4, index);
index++;
EXPECT_FALSE(buffer->Fetch(&index, msg));
EXPECT_EQ(4, *msg);
}
TEST(ChannelBufferTest, Latest) {
auto cache_buffer = new CacheBuffer<std::shared_ptr<int>>(10);
auto buffer = std::make_shared<ChannelBuffer<int>>(channel0, cache_buffer);
std::shared_ptr<int> msg;
EXPECT_FALSE(buffer->Latest(msg));
buffer->Buffer()->Fill(std::make_shared<int>(1));
EXPECT_TRUE(buffer->Latest(msg));
EXPECT_EQ(1, *msg);
EXPECT_TRUE(buffer->Latest(msg));
EXPECT_EQ(1, *msg);
buffer->Buffer()->Fill(std::make_shared<int>(2));
EXPECT_TRUE(buffer->Latest(msg));
EXPECT_EQ(2, *msg);
}
TEST(ChannelBufferTest, FetchMulti) {
auto cache_buffer = new CacheBuffer<std::shared_ptr<int>>(2);
auto buffer = std::make_shared<ChannelBuffer<int>>(channel0, cache_buffer);
std::vector<std::shared_ptr<int>> vector;
EXPECT_FALSE(buffer->FetchMulti(1, &vector));
buffer->Buffer()->Fill(std::make_shared<int>(1));
EXPECT_TRUE(buffer->FetchMulti(1, &vector));
EXPECT_EQ(1, vector.size());
EXPECT_EQ(1, *vector[0]);
vector.clear();
buffer->Buffer()->Fill(std::make_shared<int>(2));
EXPECT_TRUE(buffer->FetchMulti(1, &vector));
EXPECT_EQ(1, vector.size());
EXPECT_EQ(2, *vector[0]);
vector.clear();
EXPECT_TRUE(buffer->FetchMulti(2, &vector));
EXPECT_EQ(2, vector.size());
EXPECT_EQ(1, *vector[0]);
EXPECT_EQ(2, *vector[1]);
vector.clear();
EXPECT_TRUE(buffer->FetchMulti(3, &vector));
EXPECT_EQ(2, vector.size());
EXPECT_EQ(1, *vector[0]);
EXPECT_EQ(2, *vector[1]);
}
} // namespace data
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/data/data_dispatcher_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/data/data_dispatcher.h"
#include <memory>
#include <vector>
#include "gtest/gtest.h"
#include "cyber/common/util.h"
namespace apollo {
namespace cyber {
namespace data {
template <typename T>
using BufferVector =
std::vector<std::weak_ptr<CacheBuffer<std::shared_ptr<T>>>>;
auto channel0 = common::Hash("/channel0");
auto channel1 = common::Hash("/channel1");
TEST(DataDispatcher, AddBuffer) {
auto cache_buffer1 = new CacheBuffer<std::shared_ptr<int>>(2);
auto buffer0 = ChannelBuffer<int>(channel0, cache_buffer1);
auto cache_buffer2 = new CacheBuffer<std::shared_ptr<int>>(2);
auto buffer1 = ChannelBuffer<int>(channel1, cache_buffer2);
auto dispatcher = DataDispatcher<int>::Instance();
dispatcher->AddBuffer(buffer0);
dispatcher->AddBuffer(buffer1);
}
TEST(DataDispatcher, Dispatch) {
auto cache_buffer = new CacheBuffer<std::shared_ptr<int>>(10);
auto buffer = ChannelBuffer<int>(channel0, cache_buffer);
auto dispatcher = DataDispatcher<int>::Instance();
auto msg = std::make_shared<int>(1);
EXPECT_FALSE(dispatcher->Dispatch(channel0, msg));
dispatcher->AddBuffer(buffer);
EXPECT_FALSE(dispatcher->Dispatch(channel0, msg));
auto notifier = std::make_shared<Notifier>();
DataNotifier::Instance()->AddNotifier(channel0, notifier);
EXPECT_TRUE(dispatcher->Dispatch(channel0, msg));
}
} // namespace data
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/data/cache_buffer_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/data/cache_buffer.h"
#include <mutex>
#include <thread>
#include <utility>
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace data {
TEST(CacheBufferTest, cache_buffer_test) {
CacheBuffer<int> buffer(32);
EXPECT_TRUE(buffer.Empty());
for (int i = 0; i < 32 - 1; i++) {
buffer.Fill(std::move(i));
EXPECT_FALSE(buffer.Full());
EXPECT_EQ(i, buffer[i + 1]);
EXPECT_EQ(i, buffer.at(i + 1));
}
EXPECT_EQ(31, buffer.Size());
EXPECT_EQ(1, buffer.Head());
EXPECT_EQ(31, buffer.Tail());
EXPECT_EQ(0, buffer.Front());
EXPECT_EQ(30, buffer.Back());
buffer.Fill(31);
EXPECT_TRUE(buffer.Full());
EXPECT_EQ(32, buffer.Size());
CacheBuffer<int> buffer1(std::move(buffer));
EXPECT_EQ(buffer.Size(), buffer1.Size());
EXPECT_EQ(buffer.Head(), buffer1.Head());
EXPECT_EQ(buffer.Tail(), buffer1.Tail());
EXPECT_EQ(buffer.Front(), buffer1.Front());
EXPECT_EQ(buffer.Back(), buffer1.Back());
EXPECT_TRUE(buffer1.Full());
}
} // namespace data
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/data/data_visitor_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/data/data_visitor.h"
#include <memory>
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "cyber/common/log.h"
#include "cyber/cyber.h"
#include "cyber/message/raw_message.h"
namespace apollo {
namespace cyber {
namespace data {
using apollo::cyber::message::RawMessage;
using apollo::cyber::proto::RoleAttributes;
std::hash<std::string> str_hash;
auto channel0 = str_hash("/channel0");
auto channel1 = str_hash("/channel1");
auto channel2 = str_hash("/channel2");
auto channel3 = str_hash("/channel3");
void DispatchMessage(uint64_t channel_id, int num) {
for (int i = 0; i < num; ++i) {
auto raw_msg = std::make_shared<RawMessage>();
DataDispatcher<RawMessage>::Instance()->Dispatch(channel_id, raw_msg);
}
}
std::vector<VisitorConfig> InitConfigs(int num) {
std::vector<VisitorConfig> configs;
configs.reserve(num);
for (int i = 0; i < num; ++i) {
uint64_t channel_id = str_hash("/channel" + std::to_string(i));
uint32_t queue_size = 10;
configs.emplace_back(channel_id, queue_size);
}
return configs;
}
TEST(DataVisitorTest, one_channel) {
auto channel0 = str_hash("/channel");
auto dv = std::make_shared<DataVisitor<RawMessage>>(channel0, 10);
DispatchMessage(channel0, 1);
std::shared_ptr<RawMessage> msg;
EXPECT_TRUE(dv->TryFetch(msg));
EXPECT_FALSE(dv->TryFetch(msg));
DispatchMessage(channel0, 10);
for (int i = 0; i < 10; ++i) {
EXPECT_TRUE(dv->TryFetch(msg));
}
EXPECT_FALSE(dv->TryFetch(msg));
}
TEST(DataVisitorTest, two_channel) {
auto dv =
std::make_shared<DataVisitor<RawMessage, RawMessage>>(InitConfigs(2));
std::shared_ptr<RawMessage> msg0;
std::shared_ptr<RawMessage> msg1;
DispatchMessage(channel0, 1);
EXPECT_FALSE(dv->TryFetch(msg0, msg1));
DispatchMessage(channel1, 1);
EXPECT_FALSE(dv->TryFetch(msg0, msg1));
DispatchMessage(channel0, 1);
EXPECT_TRUE(dv->TryFetch(msg0, msg1));
DispatchMessage(channel0, 10);
for (int i = 0; i < 10; ++i) {
EXPECT_TRUE(dv->TryFetch(msg0, msg1));
}
EXPECT_FALSE(dv->TryFetch(msg0, msg1));
}
TEST(DataVisitorTest, three_channel) {
auto dv = std::make_shared<DataVisitor<RawMessage, RawMessage, RawMessage>>(
InitConfigs(3));
std::shared_ptr<RawMessage> msg0;
std::shared_ptr<RawMessage> msg1;
std::shared_ptr<RawMessage> msg2;
DispatchMessage(channel0, 1);
EXPECT_FALSE(dv->TryFetch(msg0, msg1, msg2));
DispatchMessage(channel1, 1);
EXPECT_FALSE(dv->TryFetch(msg0, msg1, msg2));
DispatchMessage(channel2, 1);
EXPECT_FALSE(dv->TryFetch(msg0, msg1, msg2));
DispatchMessage(channel0, 1);
EXPECT_TRUE(dv->TryFetch(msg0, msg1, msg2));
DispatchMessage(channel0, 10);
for (int i = 0; i < 10; ++i) {
EXPECT_TRUE(dv->TryFetch(msg0, msg1, msg2));
}
EXPECT_FALSE(dv->TryFetch(msg0, msg1, msg2));
}
TEST(DataVisitorTest, four_channel) {
auto dv = std::make_shared<
DataVisitor<RawMessage, RawMessage, RawMessage, RawMessage>>(
InitConfigs(4));
std::shared_ptr<RawMessage> msg0;
std::shared_ptr<RawMessage> msg1;
std::shared_ptr<RawMessage> msg2;
std::shared_ptr<RawMessage> msg3;
DispatchMessage(channel0, 1);
EXPECT_FALSE(dv->TryFetch(msg0, msg1, msg2, msg3));
DispatchMessage(channel1, 1);
EXPECT_FALSE(dv->TryFetch(msg0, msg1, msg2, msg3));
DispatchMessage(channel2, 1);
EXPECT_FALSE(dv->TryFetch(msg0, msg1, msg2, msg3));
DispatchMessage(channel3, 1);
EXPECT_FALSE(dv->TryFetch(msg0, msg1, msg2, msg3));
DispatchMessage(channel0, 1);
EXPECT_TRUE(dv->TryFetch(msg0, msg1, msg2, msg3));
DispatchMessage(channel0, 10);
for (int i = 0; i < 10; ++i) {
EXPECT_TRUE(dv->TryFetch(msg0, msg1, msg2, msg3));
}
EXPECT_FALSE(dv->TryFetch(msg0, msg1, msg2, msg3));
}
} // namespace data
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/data/data_visitor.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_DATA_DATA_VISITOR_H_
#define CYBER_DATA_DATA_VISITOR_H_
#include <algorithm>
#include <functional>
#include <memory>
#include <vector>
#include "cyber/common/log.h"
#include "cyber/data/channel_buffer.h"
#include "cyber/data/data_dispatcher.h"
#include "cyber/data/data_visitor_base.h"
#include "cyber/data/fusion/all_latest.h"
#include "cyber/data/fusion/data_fusion.h"
namespace apollo {
namespace cyber {
namespace data {
struct VisitorConfig {
VisitorConfig(uint64_t id, uint32_t size)
: channel_id(id), queue_size(size) {}
uint64_t channel_id;
uint32_t queue_size;
};
template <typename T>
using BufferType = CacheBuffer<std::shared_ptr<T>>;
template <typename M0, typename M1 = NullType, typename M2 = NullType,
typename M3 = NullType>
class DataVisitor : public DataVisitorBase {
public:
explicit DataVisitor(const std::vector<VisitorConfig>& configs)
: buffer_m0_(configs[0].channel_id,
new BufferType<M0>(configs[0].queue_size)),
buffer_m1_(configs[1].channel_id,
new BufferType<M1>(configs[1].queue_size)),
buffer_m2_(configs[2].channel_id,
new BufferType<M2>(configs[2].queue_size)),
buffer_m3_(configs[3].channel_id,
new BufferType<M3>(configs[3].queue_size)) {
DataDispatcher<M0>::Instance()->AddBuffer(buffer_m0_);
DataDispatcher<M1>::Instance()->AddBuffer(buffer_m1_);
DataDispatcher<M2>::Instance()->AddBuffer(buffer_m2_);
DataDispatcher<M3>::Instance()->AddBuffer(buffer_m3_);
data_notifier_->AddNotifier(buffer_m0_.channel_id(), notifier_);
data_fusion_ = new fusion::AllLatest<M0, M1, M2, M3>(
buffer_m0_, buffer_m1_, buffer_m2_, buffer_m3_);
}
~DataVisitor() {
if (data_fusion_) {
delete data_fusion_;
data_fusion_ = nullptr;
}
}
bool TryFetch(std::shared_ptr<M0>& m0, std::shared_ptr<M1>& m1, // NOLINT
std::shared_ptr<M2>& m2, std::shared_ptr<M3>& m3) { // NOLINT
if (data_fusion_->Fusion(&next_msg_index_, m0, m1, m2, m3)) {
next_msg_index_++;
return true;
}
return false;
}
private:
fusion::DataFusion<M0, M1, M2, M3>* data_fusion_ = nullptr;
ChannelBuffer<M0> buffer_m0_;
ChannelBuffer<M1> buffer_m1_;
ChannelBuffer<M2> buffer_m2_;
ChannelBuffer<M3> buffer_m3_;
};
template <typename M0, typename M1, typename M2>
class DataVisitor<M0, M1, M2, NullType> : public DataVisitorBase {
public:
explicit DataVisitor(const std::vector<VisitorConfig>& configs)
: buffer_m0_(configs[0].channel_id,
new BufferType<M0>(configs[0].queue_size)),
buffer_m1_(configs[1].channel_id,
new BufferType<M1>(configs[1].queue_size)),
buffer_m2_(configs[2].channel_id,
new BufferType<M2>(configs[2].queue_size)) {
DataDispatcher<M0>::Instance()->AddBuffer(buffer_m0_);
DataDispatcher<M1>::Instance()->AddBuffer(buffer_m1_);
DataDispatcher<M2>::Instance()->AddBuffer(buffer_m2_);
data_notifier_->AddNotifier(buffer_m0_.channel_id(), notifier_);
data_fusion_ =
new fusion::AllLatest<M0, M1, M2>(buffer_m0_, buffer_m1_, buffer_m2_);
}
~DataVisitor() {
if (data_fusion_) {
delete data_fusion_;
data_fusion_ = nullptr;
}
}
bool TryFetch(std::shared_ptr<M0>& m0, std::shared_ptr<M1>& m1, // NOLINT
std::shared_ptr<M2>& m2) { // NOLINT
if (data_fusion_->Fusion(&next_msg_index_, m0, m1, m2)) {
next_msg_index_++;
return true;
}
return false;
}
private:
fusion::DataFusion<M0, M1, M2>* data_fusion_ = nullptr;
ChannelBuffer<M0> buffer_m0_;
ChannelBuffer<M1> buffer_m1_;
ChannelBuffer<M2> buffer_m2_;
};
template <typename M0, typename M1>
class DataVisitor<M0, M1, NullType, NullType> : public DataVisitorBase {
public:
explicit DataVisitor(const std::vector<VisitorConfig>& configs)
: buffer_m0_(configs[0].channel_id,
new BufferType<M0>(configs[0].queue_size)),
buffer_m1_(configs[1].channel_id,
new BufferType<M1>(configs[1].queue_size)) {
DataDispatcher<M0>::Instance()->AddBuffer(buffer_m0_);
DataDispatcher<M1>::Instance()->AddBuffer(buffer_m1_);
data_notifier_->AddNotifier(buffer_m0_.channel_id(), notifier_);
data_fusion_ = new fusion::AllLatest<M0, M1>(buffer_m0_, buffer_m1_);
}
~DataVisitor() {
if (data_fusion_) {
delete data_fusion_;
data_fusion_ = nullptr;
}
}
bool TryFetch(std::shared_ptr<M0>& m0, std::shared_ptr<M1>& m1) { // NOLINT
if (data_fusion_->Fusion(&next_msg_index_, m0, m1)) {
next_msg_index_++;
return true;
}
return false;
}
private:
fusion::DataFusion<M0, M1>* data_fusion_ = nullptr;
ChannelBuffer<M0> buffer_m0_;
ChannelBuffer<M1> buffer_m1_;
};
template <typename M0>
class DataVisitor<M0, NullType, NullType, NullType> : public DataVisitorBase {
public:
explicit DataVisitor(const VisitorConfig& configs)
: buffer_(configs.channel_id, new BufferType<M0>(configs.queue_size)) {
DataDispatcher<M0>::Instance()->AddBuffer(buffer_);
data_notifier_->AddNotifier(buffer_.channel_id(), notifier_);
}
DataVisitor(uint64_t channel_id, uint32_t queue_size)
: buffer_(channel_id, new BufferType<M0>(queue_size)) {
DataDispatcher<M0>::Instance()->AddBuffer(buffer_);
data_notifier_->AddNotifier(buffer_.channel_id(), notifier_);
}
bool TryFetch(std::shared_ptr<M0>& m0) { // NOLINT
if (buffer_.Fetch(&next_msg_index_, m0)) {
next_msg_index_++;
return true;
}
return false;
}
private:
ChannelBuffer<M0> buffer_;
};
} // namespace data
} // namespace cyber
} // namespace apollo
#endif // CYBER_DATA_DATA_VISITOR_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/data/cache_buffer.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_DATA_CACHE_BUFFER_H_
#define CYBER_DATA_CACHE_BUFFER_H_
#include <functional>
#include <memory>
#include <mutex>
#include <vector>
namespace apollo {
namespace cyber {
namespace data {
template <typename T>
class CacheBuffer {
public:
using value_type = T;
using size_type = std::size_t;
using FusionCallback = std::function<void(const T&)>;
explicit CacheBuffer(uint64_t size) {
capacity_ = size + 1;
buffer_.resize(capacity_);
}
CacheBuffer(const CacheBuffer& rhs) {
std::lock_guard<std::mutex> lg(rhs.mutex_);
head_ = rhs.head_;
tail_ = rhs.tail_;
buffer_ = rhs.buffer_;
capacity_ = rhs.capacity_;
fusion_callback_ = rhs.fusion_callback_;
}
T& operator[](const uint64_t& pos) { return buffer_[GetIndex(pos)]; }
const T& at(const uint64_t& pos) const { return buffer_[GetIndex(pos)]; }
uint64_t Head() const { return head_ + 1; }
uint64_t Tail() const { return tail_; }
uint64_t Size() const { return tail_ - head_; }
const T& Front() const { return buffer_[GetIndex(head_ + 1)]; }
const T& Back() const { return buffer_[GetIndex(tail_)]; }
bool Empty() const { return tail_ == 0; }
bool Full() const { return capacity_ - 1 == tail_ - head_; }
uint64_t Capacity() const { return capacity_; }
void SetFusionCallback(const FusionCallback& callback) {
fusion_callback_ = callback;
}
void Fill(const T& value) {
if (fusion_callback_) {
fusion_callback_(value);
} else {
if (Full()) {
buffer_[GetIndex(head_)] = value;
++head_;
++tail_;
} else {
buffer_[GetIndex(tail_ + 1)] = value;
++tail_;
}
}
}
std::mutex& Mutex() { return mutex_; }
private:
CacheBuffer& operator=(const CacheBuffer& other) = delete;
uint64_t GetIndex(const uint64_t& pos) const { return pos % capacity_; }
uint64_t head_ = 0;
uint64_t tail_ = 0;
uint64_t capacity_ = 0;
std::vector<T> buffer_;
mutable std::mutex mutex_;
FusionCallback fusion_callback_;
};
} // namespace data
} // namespace cyber
} // namespace apollo
#endif // CYBER_DATA_CACHE_BUFFER_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/data/data_visitor_base.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_DATA_DATA_VISITOR_BASE_H_
#define CYBER_DATA_DATA_VISITOR_BASE_H_
#include <algorithm>
#include <functional>
#include <memory>
#include <vector>
#include "cyber/common/global_data.h"
#include "cyber/common/log.h"
#include "cyber/data/data_notifier.h"
namespace apollo {
namespace cyber {
namespace data {
class DataVisitorBase {
public:
DataVisitorBase() : notifier_(new Notifier()) {}
void RegisterNotifyCallback(std::function<void()>&& callback) {
notifier_->callback = callback;
}
protected:
DataVisitorBase(const DataVisitorBase&) = delete;
DataVisitorBase& operator=(const DataVisitorBase&) = delete;
uint64_t next_msg_index_ = 0;
DataNotifier* data_notifier_ = DataNotifier::Instance();
std::shared_ptr<Notifier> notifier_;
};
} // namespace data
} // namespace cyber
} // namespace apollo
#endif // CYBER_DATA_DATA_VISITOR_BASE_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/data/channel_buffer.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_DATA_CHANNEL_BUFFER_H_
#define CYBER_DATA_CHANNEL_BUFFER_H_
#include <algorithm>
#include <functional>
#include <memory>
#include <vector>
#include "cyber/common/global_data.h"
#include "cyber/common/log.h"
#include "cyber/data/data_notifier.h"
namespace apollo {
namespace cyber {
namespace data {
using apollo::cyber::common::GlobalData;
template <typename T>
class ChannelBuffer {
public:
using BufferType = CacheBuffer<std::shared_ptr<T>>;
ChannelBuffer(uint64_t channel_id, BufferType* buffer)
: channel_id_(channel_id), buffer_(buffer) {}
bool Fetch(uint64_t* index, std::shared_ptr<T>& m); // NOLINT
bool Latest(std::shared_ptr<T>& m); // NOLINT
bool FetchMulti(uint64_t fetch_size, std::vector<std::shared_ptr<T>>* vec);
uint64_t channel_id() const { return channel_id_; }
std::shared_ptr<BufferType> Buffer() const { return buffer_; }
private:
uint64_t channel_id_;
std::shared_ptr<BufferType> buffer_;
};
template <typename T>
bool ChannelBuffer<T>::Fetch(uint64_t* index,
std::shared_ptr<T>& m) { // NOLINT
std::lock_guard<std::mutex> lock(buffer_->Mutex());
if (buffer_->Empty()) {
return false;
}
if (*index == 0) {
*index = buffer_->Tail();
} else if (*index == buffer_->Tail() + 1) {
return false;
} else if (*index < buffer_->Head()) {
auto interval = buffer_->Tail() - *index;
AWARN << "channel[" << GlobalData::GetChannelById(channel_id_) << "] "
<< "read buffer overflow, drop_message[" << interval << "] pre_index["
<< *index << "] current_index[" << buffer_->Tail() << "] ";
*index = buffer_->Tail();
}
m = buffer_->at(*index);
return true;
}
template <typename T>
bool ChannelBuffer<T>::Latest(std::shared_ptr<T>& m) { // NOLINT
std::lock_guard<std::mutex> lock(buffer_->Mutex());
if (buffer_->Empty()) {
return false;
}
m = buffer_->Back();
return true;
}
template <typename T>
bool ChannelBuffer<T>::FetchMulti(uint64_t fetch_size,
std::vector<std::shared_ptr<T>>* vec) {
std::lock_guard<std::mutex> lock(buffer_->Mutex());
if (buffer_->Empty()) {
return false;
}
auto num = std::min(buffer_->Size(), fetch_size);
vec->reserve(num);
for (auto index = buffer_->Tail() - num + 1; index <= buffer_->Tail();
++index) {
vec->emplace_back(buffer_->at(index));
}
return true;
}
} // namespace data
} // namespace cyber
} // namespace apollo
#endif // CYBER_DATA_CHANNEL_BUFFER_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/data/data_dispatcher.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_DATA_DATA_DISPATCHER_H_
#define CYBER_DATA_DATA_DISPATCHER_H_
#include <memory>
#include <mutex>
#include <vector>
#include "cyber/common/log.h"
#include "cyber/common/macros.h"
#include "cyber/data/channel_buffer.h"
#include "cyber/state.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
namespace data {
using apollo::cyber::Time;
using apollo::cyber::base::AtomicHashMap;
template <typename T>
class DataDispatcher {
public:
using BufferVector =
std::vector<std::weak_ptr<CacheBuffer<std::shared_ptr<T>>>>;
~DataDispatcher() {}
void AddBuffer(const ChannelBuffer<T>& channel_buffer);
bool Dispatch(const uint64_t channel_id, const std::shared_ptr<T>& msg);
private:
DataNotifier* notifier_ = DataNotifier::Instance();
std::mutex buffers_map_mutex_;
AtomicHashMap<uint64_t, BufferVector> buffers_map_;
DECLARE_SINGLETON(DataDispatcher)
};
template <typename T>
inline DataDispatcher<T>::DataDispatcher() {}
template <typename T>
void DataDispatcher<T>::AddBuffer(const ChannelBuffer<T>& channel_buffer) {
std::lock_guard<std::mutex> lock(buffers_map_mutex_);
auto buffer = channel_buffer.Buffer();
BufferVector* buffers = nullptr;
if (buffers_map_.Get(channel_buffer.channel_id(), &buffers)) {
buffers->emplace_back(buffer);
} else {
BufferVector new_buffers = {buffer};
buffers_map_.Set(channel_buffer.channel_id(), new_buffers);
}
}
template <typename T>
bool DataDispatcher<T>::Dispatch(const uint64_t channel_id,
const std::shared_ptr<T>& msg) {
BufferVector* buffers = nullptr;
if (apollo::cyber::IsShutdown()) {
return false;
}
if (buffers_map_.Get(channel_id, &buffers)) {
for (auto& buffer_wptr : *buffers) {
if (auto buffer = buffer_wptr.lock()) {
std::lock_guard<std::mutex> lock(buffer->Mutex());
buffer->Fill(msg);
}
}
} else {
return false;
}
return notifier_->Notify(channel_id);
}
} // namespace data
} // namespace cyber
} // namespace apollo
#endif // CYBER_DATA_DATA_DISPATCHER_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/data/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "cyber_data_hdrs",
srcs = glob([
"*.h",
"fusion/*.h"
]),
)
cc_library(
name = "data",
deps = [
":all_latest",
":cache_buffer",
":channel_buffer",
":data_dispatcher",
":data_fusion",
":data_notifier",
":data_visitor",
":data_visitor_base",
],
)
cc_library(
name = "cache_buffer",
srcs = ["cache_buffer.h"],
)
cc_test(
name = "cache_buffer_test",
size = "small",
srcs = ["cache_buffer_test.cc"],
deps = [
":cache_buffer",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "channel_buffer",
hdrs = ["channel_buffer.h"],
deps = [
":data_notifier",
"//cyber/proto:component_conf_cc_proto",
],
)
cc_library(
name = "data_dispatcher",
hdrs = ["data_dispatcher.h"],
deps = [
":channel_buffer",
],
)
cc_library(
name = "data_visitor",
hdrs = ["data_visitor.h"],
)
cc_test(
name = "data_visitor_test",
size = "small",
srcs = ["data_visitor_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "data_visitor_base",
hdrs = ["data_visitor_base.h"],
)
cc_library(
name = "data_notifier",
hdrs = ["data_notifier.h"],
deps = [
":cache_buffer",
],
)
cc_test(
name = "data_dispatcher_test",
size = "small",
srcs = ["data_dispatcher_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "channel_buffer_test",
size = "small",
srcs = ["channel_buffer_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "data_fusion",
hdrs = ["fusion/data_fusion.h"],
)
cc_library(
name = "all_latest",
hdrs = ["fusion/all_latest.h"],
deps = [
":channel_buffer",
":data_fusion",
],
)
cc_test(
name = "all_latest_test",
size = "small",
srcs = ["fusion/all_latest_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber/data
|
apollo_public_repos/apollo/cyber/data/fusion/all_latest_test.cc
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <memory>
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "cyber/common/log.h"
#include "cyber/cyber.h"
#include "cyber/data/data_visitor.h"
#include "cyber/data/fusion/all_latest.h"
namespace apollo {
namespace cyber {
namespace data {
using apollo::cyber::message::RawMessage;
using apollo::cyber::proto::RoleAttributes;
std::hash<std::string> str_hash;
TEST(AllLatestTest, two_channels) {
auto cache0 = new CacheBuffer<std::shared_ptr<RawMessage>>(10);
auto cache1 = new CacheBuffer<std::shared_ptr<RawMessage>>(10);
ChannelBuffer<RawMessage> buffer0(static_cast<uint64_t>(0), cache0);
ChannelBuffer<RawMessage> buffer1(static_cast<uint64_t>(1), cache1);
std::shared_ptr<RawMessage> m;
std::shared_ptr<RawMessage> m0;
std::shared_ptr<RawMessage> m1;
uint64_t index = 0;
fusion::AllLatest<RawMessage, RawMessage> fusion(buffer0, buffer1);
// normal fusion
EXPECT_FALSE(fusion.Fusion(&index, m0, m1));
cache0->Fill(std::make_shared<RawMessage>("0-0"));
EXPECT_FALSE(fusion.Fusion(&index, m0, m1));
cache1->Fill(std::make_shared<RawMessage>("1-0"));
EXPECT_FALSE(fusion.Fusion(&index, m0, m1));
cache0->Fill(std::make_shared<RawMessage>("0-1"));
EXPECT_TRUE(fusion.Fusion(&index, m0, m1));
index++;
EXPECT_EQ(std::string("0-1"), m0->message);
EXPECT_EQ(std::string("1-0"), m1->message);
EXPECT_FALSE(fusion.Fusion(&index, m0, m1));
// use 0-2 and lateste m1
cache0->Fill(std::make_shared<RawMessage>("0-2"));
EXPECT_TRUE(fusion.Fusion(&index, m0, m1));
index++;
EXPECT_EQ(std::string("0-2"), m0->message);
EXPECT_EQ(std::string("1-0"), m1->message);
EXPECT_FALSE(fusion.Fusion(&index, m0, m1));
// sub channel will not trigger fusion
cache1->Fill(std::make_shared<RawMessage>("1-1"));
EXPECT_FALSE(fusion.Fusion(&index, m0, m1));
// m0 overflow
for (int i = 0; i < 100; i++) {
cache0->Fill(std::make_shared<RawMessage>(std::string("0-") +
std::to_string(2 + i + 1)));
}
// EXPECT_TRUE(fusion.buffer_fusion_->Buffer()->Full());
EXPECT_TRUE(fusion.Fusion(&index, m0, m1));
index++;
EXPECT_EQ(std::string("0-102"), m0->message);
}
TEST(AllLatestTest, three_channels) {
auto cache0 = new CacheBuffer<std::shared_ptr<RawMessage>>(10);
auto cache1 = new CacheBuffer<std::shared_ptr<RawMessage>>(10);
auto cache2 = new CacheBuffer<std::shared_ptr<RawMessage>>(10);
ChannelBuffer<RawMessage> buffer0(0, cache0);
ChannelBuffer<RawMessage> buffer1(1, cache1);
ChannelBuffer<RawMessage> buffer2(2, cache2);
std::shared_ptr<RawMessage> m;
std::shared_ptr<RawMessage> m0;
std::shared_ptr<RawMessage> m1;
std::shared_ptr<RawMessage> m2;
uint64_t index = 0;
fusion::AllLatest<RawMessage, RawMessage, RawMessage> fusion(buffer0, buffer1,
buffer2);
// normal fusion
EXPECT_FALSE(fusion.Fusion(&index, m0, m1, m2));
cache0->Fill(std::make_shared<RawMessage>("0-0"));
EXPECT_FALSE(fusion.Fusion(&index, m0, m1, m2));
cache1->Fill(std::make_shared<RawMessage>("1-0"));
EXPECT_FALSE(fusion.Fusion(&index, m0, m1, m2));
cache2->Fill(std::make_shared<RawMessage>("2-0"));
EXPECT_FALSE(fusion.Fusion(&index, m0, m1, m2));
cache0->Fill(std::make_shared<RawMessage>("0-1"));
EXPECT_TRUE(fusion.Fusion(&index, m0, m1, m2));
index++;
EXPECT_EQ(std::string("0-1"), m0->message);
EXPECT_EQ(std::string("1-0"), m1->message);
EXPECT_EQ(std::string("2-0"), m2->message);
}
TEST(AllLatestTest, four_channels) {
auto cache0 = new CacheBuffer<std::shared_ptr<RawMessage>>(10);
auto cache1 = new CacheBuffer<std::shared_ptr<RawMessage>>(10);
auto cache2 = new CacheBuffer<std::shared_ptr<RawMessage>>(10);
auto cache3 = new CacheBuffer<std::shared_ptr<RawMessage>>(10);
ChannelBuffer<RawMessage> buffer0(0, cache0);
ChannelBuffer<RawMessage> buffer1(1, cache1);
ChannelBuffer<RawMessage> buffer2(2, cache2);
ChannelBuffer<RawMessage> buffer3(3, cache3);
std::shared_ptr<RawMessage> m;
std::shared_ptr<RawMessage> m0;
std::shared_ptr<RawMessage> m1;
std::shared_ptr<RawMessage> m2;
std::shared_ptr<RawMessage> m3;
uint64_t index = 0;
fusion::AllLatest<RawMessage, RawMessage, RawMessage, RawMessage> fusion(
buffer0, buffer1, buffer2, buffer3);
// normal fusion
EXPECT_FALSE(fusion.Fusion(&index, m0, m1, m2, m3));
cache0->Fill(std::make_shared<RawMessage>("0-0"));
EXPECT_FALSE(fusion.Fusion(&index, m0, m1, m2, m3));
cache1->Fill(std::make_shared<RawMessage>("1-0"));
EXPECT_FALSE(fusion.Fusion(&index, m0, m1, m2, m3));
cache2->Fill(std::make_shared<RawMessage>("2-0"));
EXPECT_FALSE(fusion.Fusion(&index, m0, m1, m2, m3));
cache3->Fill(std::make_shared<RawMessage>("3-0"));
EXPECT_FALSE(fusion.Fusion(&index, m0, m1, m2, m3));
cache0->Fill(std::make_shared<RawMessage>("0-1"));
EXPECT_TRUE(fusion.Fusion(&index, m0, m1, m2, m3));
index++;
EXPECT_EQ(std::string("0-1"), m0->message);
EXPECT_EQ(std::string("1-0"), m1->message);
EXPECT_EQ(std::string("2-0"), m2->message);
EXPECT_EQ(std::string("3-0"), m3->message);
}
} // namespace data
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/data
|
apollo_public_repos/apollo/cyber/data/fusion/data_fusion.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_DATA_FUSION_DATA_FUSION_H_
#define CYBER_DATA_FUSION_DATA_FUSION_H_
#include <deque>
#include <memory>
#include <string>
#include <type_traits>
#include <typeinfo>
#include <vector>
#include "cyber/common/types.h"
namespace apollo {
namespace cyber {
namespace data {
namespace fusion {
template <typename M0, typename M1 = NullType, typename M2 = NullType,
typename M3 = NullType>
class DataFusion {
public:
virtual ~DataFusion() {}
virtual bool Fusion(uint64_t* index, std::shared_ptr<M0>& m0, // NOLINT
std::shared_ptr<M1>& m1, // NOLINT
std::shared_ptr<M2>& m2, // NOLINT
std::shared_ptr<M3>& m3) = 0; // NOLINT
};
template <typename M0, typename M1, typename M2>
class DataFusion<M0, M1, M2, NullType> {
public:
virtual ~DataFusion() {}
virtual bool Fusion(uint64_t* index, std::shared_ptr<M0>& m0, // NOLINT
std::shared_ptr<M1>& m1, // NOLINT
std::shared_ptr<M2>& m2) = 0; // NOLINT
};
template <typename M0, typename M1>
class DataFusion<M0, M1, NullType, NullType> {
public:
virtual ~DataFusion() {}
virtual bool Fusion(uint64_t* index, std::shared_ptr<M0>& m0, // NOLINT
std::shared_ptr<M1>& m1) = 0; // NOLINT
};
} // namespace fusion
} // namespace data
} // namespace cyber
} // namespace apollo
#endif // CYBER_DATA_FUSION_DATA_FUSION_H_
| 0
|
apollo_public_repos/apollo/cyber/data
|
apollo_public_repos/apollo/cyber/data/fusion/all_latest.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_DATA_FUSION_ALL_LATEST_H_
#define CYBER_DATA_FUSION_ALL_LATEST_H_
#include <deque>
#include <memory>
#include <string>
#include <tuple>
#include <type_traits>
#include <typeinfo>
#include <vector>
#include "cyber/common/types.h"
#include "cyber/data/channel_buffer.h"
#include "cyber/data/fusion/data_fusion.h"
namespace apollo {
namespace cyber {
namespace data {
namespace fusion {
template <typename M0, typename M1 = NullType, typename M2 = NullType,
typename M3 = NullType>
class AllLatest : public DataFusion<M0, M1, M2, M3> {
using FusionDataType = std::tuple<std::shared_ptr<M0>, std::shared_ptr<M1>,
std::shared_ptr<M2>, std::shared_ptr<M3>>;
public:
AllLatest(const ChannelBuffer<M0>& buffer_0,
const ChannelBuffer<M1>& buffer_1,
const ChannelBuffer<M2>& buffer_2,
const ChannelBuffer<M3>& buffer_3)
: buffer_m0_(buffer_0),
buffer_m1_(buffer_1),
buffer_m2_(buffer_2),
buffer_m3_(buffer_3),
buffer_fusion_(buffer_m0_.channel_id(),
new CacheBuffer<std::shared_ptr<FusionDataType>>(
buffer_0.Buffer()->Capacity() - uint64_t(1))) {
buffer_m0_.Buffer()->SetFusionCallback(
[this](const std::shared_ptr<M0>& m0) {
std::shared_ptr<M1> m1;
std::shared_ptr<M2> m2;
std::shared_ptr<M3> m3;
if (!buffer_m1_.Latest(m1) || !buffer_m2_.Latest(m2) ||
!buffer_m3_.Latest(m3)) {
return;
}
auto data = std::make_shared<FusionDataType>(m0, m1, m2, m3);
std::lock_guard<std::mutex> lg(buffer_fusion_.Buffer()->Mutex());
buffer_fusion_.Buffer()->Fill(data);
});
}
bool Fusion(uint64_t* index, std::shared_ptr<M0>& m0, std::shared_ptr<M1>& m1,
std::shared_ptr<M2>& m2, std::shared_ptr<M3>& m3) override {
std::shared_ptr<FusionDataType> fusion_data;
if (!buffer_fusion_.Fetch(index, fusion_data)) {
return false;
}
m0 = std::get<0>(*fusion_data);
m1 = std::get<1>(*fusion_data);
m2 = std::get<2>(*fusion_data);
m3 = std::get<3>(*fusion_data);
return true;
}
private:
ChannelBuffer<M0> buffer_m0_;
ChannelBuffer<M1> buffer_m1_;
ChannelBuffer<M2> buffer_m2_;
ChannelBuffer<M3> buffer_m3_;
ChannelBuffer<FusionDataType> buffer_fusion_;
};
template <typename M0, typename M1, typename M2>
class AllLatest<M0, M1, M2, NullType> : public DataFusion<M0, M1, M2> {
using FusionDataType =
std::tuple<std::shared_ptr<M0>, std::shared_ptr<M1>, std::shared_ptr<M2>>;
public:
AllLatest(const ChannelBuffer<M0>& buffer_0,
const ChannelBuffer<M1>& buffer_1,
const ChannelBuffer<M2>& buffer_2)
: buffer_m0_(buffer_0),
buffer_m1_(buffer_1),
buffer_m2_(buffer_2),
buffer_fusion_(buffer_m0_.channel_id(),
new CacheBuffer<std::shared_ptr<FusionDataType>>(
buffer_0.Buffer()->Capacity() - uint64_t(1))) {
buffer_m0_.Buffer()->SetFusionCallback(
[this](const std::shared_ptr<M0>& m0) {
std::shared_ptr<M1> m1;
std::shared_ptr<M2> m2;
if (!buffer_m1_.Latest(m1) || !buffer_m2_.Latest(m2)) {
return;
}
auto data = std::make_shared<FusionDataType>(m0, m1, m2);
std::lock_guard<std::mutex> lg(buffer_fusion_.Buffer()->Mutex());
buffer_fusion_.Buffer()->Fill(data);
});
}
bool Fusion(uint64_t* index, std::shared_ptr<M0>& m0, std::shared_ptr<M1>& m1,
std::shared_ptr<M2>& m2) override {
std::shared_ptr<FusionDataType> fusion_data;
if (!buffer_fusion_.Fetch(index, fusion_data)) {
return false;
}
m0 = std::get<0>(*fusion_data);
m1 = std::get<1>(*fusion_data);
m2 = std::get<2>(*fusion_data);
return true;
}
private:
ChannelBuffer<M0> buffer_m0_;
ChannelBuffer<M1> buffer_m1_;
ChannelBuffer<M2> buffer_m2_;
ChannelBuffer<FusionDataType> buffer_fusion_;
};
template <typename M0, typename M1>
class AllLatest<M0, M1, NullType, NullType> : public DataFusion<M0, M1> {
using FusionDataType = std::tuple<std::shared_ptr<M0>, std::shared_ptr<M1>>;
public:
AllLatest(const ChannelBuffer<M0>& buffer_0,
const ChannelBuffer<M1>& buffer_1)
: buffer_m0_(buffer_0),
buffer_m1_(buffer_1),
buffer_fusion_(buffer_m0_.channel_id(),
new CacheBuffer<std::shared_ptr<FusionDataType>>(
buffer_0.Buffer()->Capacity() - uint64_t(1))) {
buffer_m0_.Buffer()->SetFusionCallback(
[this](const std::shared_ptr<M0>& m0) {
std::shared_ptr<M1> m1;
if (!buffer_m1_.Latest(m1)) {
return;
}
auto data = std::make_shared<FusionDataType>(m0, m1);
std::lock_guard<std::mutex> lg(buffer_fusion_.Buffer()->Mutex());
buffer_fusion_.Buffer()->Fill(data);
});
}
bool Fusion(uint64_t* index, std::shared_ptr<M0>& m0,
std::shared_ptr<M1>& m1) override {
std::shared_ptr<FusionDataType> fusion_data;
if (!buffer_fusion_.Fetch(index, fusion_data)) {
return false;
}
m0 = std::get<0>(*fusion_data);
m1 = std::get<1>(*fusion_data);
return true;
}
private:
ChannelBuffer<M0> buffer_m0_;
ChannelBuffer<M1> buffer_m1_;
ChannelBuffer<FusionDataType> buffer_fusion_;
};
} // namespace fusion
} // namespace data
} // namespace cyber
} // namespace apollo
#endif // CYBER_DATA_FUSION_ALL_LATEST_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/service_discovery/topology_manager_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/topology_manager.h"
#include <memory>
#include "gtest/gtest.h"
#include "cyber/common/log.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class TopologyTest : public ::testing::Test {
protected:
TopologyTest() { topology_ = TopologyManager::Instance(); }
virtual ~TopologyTest() { topology_->Shutdown(); }
virtual void SetUp() {}
virtual void TearDown() {}
TopologyManager* topology_;
};
TEST_F(TopologyTest, add_and_remove_change_listener) {
proto::RoleAttributes attr;
attr.set_host_name("");
attr.set_process_id(0);
// add change listener
auto conn =
topology_->AddChangeListener([&attr](const ChangeMsg& change_msg) {
if (change_msg.change_type() == ChangeType::CHANGE_PARTICIPANT &&
change_msg.operate_type() == OperateType::OPT_JOIN &&
change_msg.role_type() == RoleType::ROLE_PARTICIPANT) {
attr.CopyFrom(change_msg.role_attr());
}
});
// remove change listener
topology_->RemoveChangeListener(conn);
}
TEST_F(TopologyTest, get_manager) {
auto node_manager = topology_->node_manager();
EXPECT_NE(node_manager, nullptr);
auto channel_manager = topology_->channel_manager();
EXPECT_NE(channel_manager, nullptr);
auto service_manager = topology_->service_manager();
EXPECT_NE(service_manager, nullptr);
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/service_discovery/topology_manager.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_DISCOVERY_TOPOLOGY_MANAGER_H_
#define CYBER_SERVICE_DISCOVERY_TOPOLOGY_MANAGER_H_
#include <atomic>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include "cyber/base/signal.h"
#include "cyber/common/macros.h"
#include "cyber/service_discovery/communication/participant_listener.h"
#include "cyber/service_discovery/specific_manager/channel_manager.h"
#include "cyber/service_discovery/specific_manager/node_manager.h"
#include "cyber/service_discovery/specific_manager/service_manager.h"
#include "cyber/transport/rtps/participant.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class NodeManager;
using NodeManagerPtr = std::shared_ptr<NodeManager>;
class ChannelManager;
using ChannelManagerPtr = std::shared_ptr<ChannelManager>;
class ServiceManager;
using ServiceManagerPtr = std::shared_ptr<ServiceManager>;
/**
* @class TopologyManager
* @brief elements in Cyber -- Node, Channel, Service, Writer, Reader, Client
* and Server's relationship is presented by Topology. You can Imagine that a
* directed graph -- Node is the container of Server/Client/Writer/Reader, and
* they are the vertice of the graph and Channel is the Edge from Writer flow to
* the Reader, Service is the Edge from Server to Client. Thus we call Writer
* and Server `Upstream`, Reader and Client `Downstream` To generate this graph,
* we use TopologyManager, it has three sub managers -- NodeManager: You can
* find Nodes in this topology ChannelManager: You can find Channels in this
* topology, and their Writers and Readers ServiceManager: You can find Services
* in this topology, and their Servers and Clients TopologyManager use
* fast-rtps' Participant to communicate. It can broadcast Join or Leave
* messages of those elements. Also, you can register you own `ChangeFunc` to
* monitor topology change
*/
class TopologyManager {
public:
using ChangeSignal = base::Signal<const ChangeMsg&>;
using ChangeFunc = std::function<void(const ChangeMsg&)>;
using ChangeConnection = base::Connection<const ChangeMsg&>;
using PartNameContainer =
std::map<eprosima::fastrtps::rtps::GUID_t, std::string>;
using PartInfo = eprosima::fastrtps::ParticipantDiscoveryInfo;
virtual ~TopologyManager();
/**
* @brief Shutdown the TopologyManager
*/
void Shutdown();
/**
* @brief To observe the topology change, you can register a `ChangeFunc`
*
* @param func is the observe function
* @return ChangeConnection is the connection that connected to
* `change_signal_`. Used to Remove your observe function
*/
ChangeConnection AddChangeListener(const ChangeFunc& func);
/**
* @brief Remove the observe function connect to `change_signal_` by `conn`
*/
void RemoveChangeListener(const ChangeConnection& conn);
/**
* @brief Get shared_ptr for NodeManager
*/
NodeManagerPtr& node_manager() { return node_manager_; }
/**
* @brief Get shared_ptr for ChannelManager
*/
ChannelManagerPtr& channel_manager() { return channel_manager_; }
/**
* @brief Get shared_ptr for ServiceManager
*/
ServiceManagerPtr& service_manager() { return service_manager_; }
private:
bool Init();
bool InitNodeManager();
bool InitChannelManager();
bool InitServiceManager();
bool CreateParticipant();
void OnParticipantChange(const PartInfo& info);
bool Convert(const PartInfo& info, ChangeMsg* change_msg);
bool ParseParticipantName(const std::string& participant_name,
std::string* host_name, int* process_id);
std::atomic<bool> init_; /// Is TopologyManager inited
NodeManagerPtr node_manager_; /// shared ptr of NodeManager
ChannelManagerPtr channel_manager_; /// shared ptr of ChannelManager
ServiceManagerPtr service_manager_; /// shared ptr of ServiceManager
/// rtps participant to publish and subscribe
transport::ParticipantPtr participant_;
ParticipantListener* participant_listener_;
ChangeSignal change_signal_; /// topology changing signal,
///< connect to `ChangeFunc`s
PartNameContainer participant_names_; /// other participant in the topology
DECLARE_SINGLETON(TopologyManager)
};
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_DISCOVERY_TOPOLOGY_MANAGER_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/service_discovery/topology_manager.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/topology_manager.h"
#include "cyber/common/global_data.h"
#include "cyber/common/log.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
TopologyManager::TopologyManager()
: init_(false),
node_manager_(nullptr),
channel_manager_(nullptr),
service_manager_(nullptr),
participant_(nullptr),
participant_listener_(nullptr) {
Init();
}
TopologyManager::~TopologyManager() { Shutdown(); }
void TopologyManager::Shutdown() {
ADEBUG << "topology shutdown.";
// avoid shutdown twice
if (!init_.exchange(false)) {
return;
}
node_manager_->Shutdown();
channel_manager_->Shutdown();
service_manager_->Shutdown();
participant_->Shutdown();
delete participant_listener_;
participant_listener_ = nullptr;
change_signal_.DisconnectAllSlots();
}
TopologyManager::ChangeConnection TopologyManager::AddChangeListener(
const ChangeFunc& func) {
return change_signal_.Connect(func);
}
void TopologyManager::RemoveChangeListener(const ChangeConnection& conn) {
auto local_conn = conn;
local_conn.Disconnect();
}
bool TopologyManager::Init() {
if (init_.exchange(true)) {
return true;
}
node_manager_ = std::make_shared<NodeManager>();
channel_manager_ = std::make_shared<ChannelManager>();
service_manager_ = std::make_shared<ServiceManager>();
CreateParticipant();
bool result =
InitNodeManager() && InitChannelManager() && InitServiceManager();
if (!result) {
AERROR << "init manager failed.";
participant_ = nullptr;
delete participant_listener_;
participant_listener_ = nullptr;
node_manager_ = nullptr;
channel_manager_ = nullptr;
service_manager_ = nullptr;
init_.store(false);
return false;
}
return true;
}
bool TopologyManager::InitNodeManager() {
return node_manager_->StartDiscovery(participant_->fastrtps_participant());
}
bool TopologyManager::InitChannelManager() {
return channel_manager_->StartDiscovery(participant_->fastrtps_participant());
}
bool TopologyManager::InitServiceManager() {
return service_manager_->StartDiscovery(participant_->fastrtps_participant());
}
bool TopologyManager::CreateParticipant() {
std::string participant_name =
common::GlobalData::Instance()->HostName() + '+' +
std::to_string(common::GlobalData::Instance()->ProcessId());
participant_listener_ = new ParticipantListener(std::bind(
&TopologyManager::OnParticipantChange, this, std::placeholders::_1));
participant_ = std::make_shared<transport::Participant>(
participant_name, 11511, participant_listener_);
return true;
}
void TopologyManager::OnParticipantChange(const PartInfo& info) {
ChangeMsg msg;
if (!Convert(info, &msg)) {
return;
}
if (!init_.load()) {
return;
}
if (msg.operate_type() == OperateType::OPT_LEAVE) {
auto& host_name = msg.role_attr().host_name();
int process_id = msg.role_attr().process_id();
node_manager_->OnTopoModuleLeave(host_name, process_id);
channel_manager_->OnTopoModuleLeave(host_name, process_id);
service_manager_->OnTopoModuleLeave(host_name, process_id);
}
change_signal_(msg);
}
bool TopologyManager::Convert(const PartInfo& info, ChangeMsg* msg) {
auto guid = info.rtps.m_guid;
auto status = info.rtps.m_status;
std::string participant_name("");
OperateType opt_type = OperateType::OPT_JOIN;
switch (status) {
case eprosima::fastrtps::rtps::DISCOVERY_STATUS::DISCOVERED_RTPSPARTICIPANT:
participant_name = info.rtps.m_RTPSParticipantName;
participant_names_[guid] = participant_name;
opt_type = OperateType::OPT_JOIN;
break;
case eprosima::fastrtps::rtps::DISCOVERY_STATUS::REMOVED_RTPSPARTICIPANT:
case eprosima::fastrtps::rtps::DISCOVERY_STATUS::DROPPED_RTPSPARTICIPANT:
if (participant_names_.find(guid) != participant_names_.end()) {
participant_name = participant_names_[guid];
participant_names_.erase(guid);
}
opt_type = OperateType::OPT_LEAVE;
break;
default:
break;
}
std::string host_name("");
int process_id = 0;
if (!ParseParticipantName(participant_name, &host_name, &process_id)) {
return false;
}
msg->set_timestamp(cyber::Time::Now().ToNanosecond());
msg->set_change_type(ChangeType::CHANGE_PARTICIPANT);
msg->set_operate_type(opt_type);
msg->set_role_type(RoleType::ROLE_PARTICIPANT);
auto role_attr = msg->mutable_role_attr();
role_attr->set_host_name(host_name);
role_attr->set_process_id(process_id);
return true;
}
bool TopologyManager::ParseParticipantName(const std::string& participant_name,
std::string* host_name,
int* process_id) {
// participant_name format: host_name+process_id
auto pos = participant_name.find('+');
if (pos == std::string::npos) {
ADEBUG << "participant_name [" << participant_name << "] format mismatch.";
return false;
}
*host_name = participant_name.substr(0, pos);
std::string pid_str = participant_name.substr(pos + 1);
try {
*process_id = std::stoi(pid_str);
} catch (const std::exception& e) {
AERROR << "invalid process_id:" << e.what();
return false;
}
return true;
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/service_discovery/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "cyber_service_discovery_hdrs",
srcs = glob([
"*.h",
"**/*.h",
]),
)
cc_library(
name = "topology_manager",
srcs = ["topology_manager.cc"],
hdrs = ["topology_manager.h"],
deps = [
":channel_manager",
":node_manager",
":service_manager",
"//cyber/service_discovery/communication:participant_listener",
"//cyber/transport/rtps:participant",
],
)
cc_test(
name = "topology_manager_test",
size = "small",
srcs = ["topology_manager_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "graph",
srcs = ["container/graph.cc"],
hdrs = ["container/graph.h"],
deps = ["//cyber/base:atomic_rw_lock"],
)
cc_test(
name = "graph_test",
size = "small",
srcs = ["container/graph_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_library(
name = "multi_value_warehouse",
srcs = ["container/multi_value_warehouse.cc"],
hdrs = ["container/multi_value_warehouse.h"],
deps = [
":warehouse_base",
"//cyber/base:atomic_rw_lock",
],
)
cc_test(
name = "multi_value_warehouse_test",
size = "small",
srcs = ["container/multi_value_warehouse_test.cc"],
deps = [
":multi_value_warehouse",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "single_value_warehouse",
srcs = ["container/single_value_warehouse.cc"],
hdrs = ["container/single_value_warehouse.h"],
deps = [
":warehouse_base",
"//cyber/base:atomic_rw_lock",
],
)
cc_test(
name = "single_value_warehouse_test",
size = "small",
srcs = ["container/single_value_warehouse_test.cc"],
deps = [
":single_value_warehouse",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "warehouse_base",
hdrs = ["container/warehouse_base.h"],
deps = ["role"],
)
cc_library(
name = "role",
srcs = ["role/role.cc"],
hdrs = ["role/role.h"],
deps = [
"//cyber:binary",
"//cyber/common:log",
"//cyber/common:types",
"//cyber/proto:role_attributes_cc_proto",
],
)
cc_test(
name = "role_test",
size = "small",
srcs = ["role/role_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "manager",
srcs = ["specific_manager/manager.cc"],
hdrs = ["specific_manager/manager.h"],
deps = [
"//cyber:state",
"//cyber/base:signal",
"//cyber/message:message_traits",
"//cyber/message:protobuf_factory",
"//cyber/proto:proto_desc_cc_proto",
"//cyber/proto:role_attributes_cc_proto",
"//cyber/proto:topology_change_cc_proto",
"//cyber/service_discovery/communication:subscriber_listener",
"//cyber/time",
"//cyber/transport/qos",
"//cyber/transport/rtps:attributes_filler",
"//cyber/transport/rtps:underlay_message_type",
"@fastrtps",
],
)
cc_library(
name = "channel_manager",
srcs = ["specific_manager/channel_manager.cc"],
hdrs = ["specific_manager/channel_manager.h"],
deps = [
":graph",
":manager",
":multi_value_warehouse",
":single_value_warehouse",
],
)
cc_test(
name = "channel_manager_test",
size = "small",
srcs = ["specific_manager/channel_manager_test.cc"],
deps = [
"//cyber",
"//cyber/proto:unit_test_cc_proto",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_library(
name = "node_manager",
srcs = ["specific_manager/node_manager.cc"],
hdrs = ["specific_manager/node_manager.h"],
deps = [
":manager",
":multi_value_warehouse",
":single_value_warehouse",
],
)
cc_test(
name = "node_manager_test",
size = "small",
srcs = ["specific_manager/node_manager_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_library(
name = "service_manager",
srcs = ["specific_manager/service_manager.cc"],
hdrs = ["specific_manager/service_manager.h"],
deps = [
":manager",
":multi_value_warehouse",
":single_value_warehouse",
],
)
cc_test(
name = "service_manager_test",
size = "small",
srcs = ["specific_manager/service_manager_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/role/role.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_DISCOVERY_ROLE_ROLE_H_
#define CYBER_SERVICE_DISCOVERY_ROLE_ROLE_H_
#include <cstdint>
#include <memory>
#include <string>
#include "cyber/proto/role_attributes.pb.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class RoleBase;
using RolePtr = std::shared_ptr<RoleBase>;
using RoleNode = RoleBase;
using RoleNodePtr = std::shared_ptr<RoleNode>;
class RoleWriter;
using RoleWriterPtr = std::shared_ptr<RoleWriter>;
using RoleReader = RoleWriter;
using RoleReaderPtr = std::shared_ptr<RoleReader>;
class RoleServer;
using RoleServerPtr = std::shared_ptr<RoleServer>;
using RoleClient = RoleServer;
using RoleClientPtr = std::shared_ptr<RoleClient>;
class RoleBase {
public:
RoleBase();
explicit RoleBase(const proto::RoleAttributes& attr,
uint64_t timestamp_ns = 0);
virtual ~RoleBase() = default;
virtual bool Match(const proto::RoleAttributes& target_attr) const;
bool IsEarlierThan(const RoleBase& other) const;
const proto::RoleAttributes& attributes() const { return attributes_; }
void set_attributes(const proto::RoleAttributes& attr) { attributes_ = attr; }
uint64_t timestamp_ns() const { return timestamp_ns_; }
void set_timestamp_ns(uint64_t timestamp_ns) { timestamp_ns_ = timestamp_ns; }
protected:
proto::RoleAttributes attributes_;
uint64_t timestamp_ns_;
};
class RoleWriter : public RoleBase {
public:
RoleWriter() {}
explicit RoleWriter(const proto::RoleAttributes& attr,
uint64_t timestamp_ns = 0);
virtual ~RoleWriter() = default;
bool Match(const proto::RoleAttributes& target_attr) const override;
};
class RoleServer : public RoleBase {
public:
RoleServer() {}
explicit RoleServer(const proto::RoleAttributes& attr,
uint64_t timestamp_ns = 0);
virtual ~RoleServer() = default;
bool Match(const proto::RoleAttributes& target_attr) const override;
};
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_DISCOVERY_ROLE_ROLE_H_
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/role/role.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/role/role.h"
#include "cyber/common/log.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
using proto::RoleAttributes;
RoleBase::RoleBase() : timestamp_ns_(0) {}
RoleBase::RoleBase(const RoleAttributes& attr, uint64_t timestamp_ns)
: attributes_(attr), timestamp_ns_(timestamp_ns) {}
bool RoleBase::Match(const RoleAttributes& target_attr) const {
if (target_attr.has_node_id() &&
target_attr.node_id() != attributes_.node_id()) {
return false;
}
if (target_attr.has_process_id() &&
target_attr.process_id() != attributes_.process_id()) {
return false;
}
if (target_attr.has_host_name() &&
target_attr.host_name() != attributes_.host_name()) {
return false;
}
return true;
}
bool RoleBase::IsEarlierThan(const RoleBase& other) const {
return timestamp_ns_ < other.timestamp_ns();
}
RoleWriter::RoleWriter(const RoleAttributes& attr, uint64_t timestamp_ns)
: RoleBase(attr, timestamp_ns) {}
bool RoleWriter::Match(const RoleAttributes& target_attr) const {
if (target_attr.has_channel_id() &&
target_attr.channel_id() != attributes_.channel_id()) {
return false;
}
if (target_attr.has_id() && target_attr.id() != attributes_.id()) {
return false;
}
return RoleBase::Match(target_attr);
}
RoleServer::RoleServer(const RoleAttributes& attr, uint64_t timestamp_ns)
: RoleBase(attr, timestamp_ns) {}
bool RoleServer::Match(const RoleAttributes& target_attr) const {
if (target_attr.has_service_id() &&
target_attr.service_id() != attributes_.service_id()) {
return false;
}
return RoleBase::Match(target_attr);
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/role/role_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/role/role.h"
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
using proto::RoleAttributes;
TEST(RoleTest, constructor_getter_setter) {
RoleBase role_a;
EXPECT_EQ(role_a.timestamp_ns(), 0);
role_a.set_timestamp_ns(123);
EXPECT_EQ(role_a.timestamp_ns(), 123);
RoleWriter role_writer_a;
EXPECT_EQ(role_writer_a.timestamp_ns(), 0);
RoleServer role_server_a;
EXPECT_EQ(role_server_a.timestamp_ns(), 0);
RoleAttributes attr;
attr.set_host_name("caros");
attr.set_process_id(12345);
role_a.set_attributes(attr);
EXPECT_EQ(role_a.attributes().host_name(), "caros");
EXPECT_EQ(role_a.attributes().process_id(), 12345);
RoleBase role_b(attr, 321);
EXPECT_EQ(role_b.timestamp_ns(), 321);
RoleWriter role_writer_b(attr, 321);
EXPECT_EQ(role_writer_b.timestamp_ns(), 321);
RoleWriter role_server_b(attr, 321);
EXPECT_EQ(role_server_b.timestamp_ns(), 321);
}
TEST(RoleTest, is_earlier_than) {
RoleBase role_a;
role_a.set_timestamp_ns(123);
RoleBase role_b;
role_b.set_timestamp_ns(456);
EXPECT_TRUE(role_a.IsEarlierThan(role_b));
EXPECT_FALSE(role_b.IsEarlierThan(role_a));
}
TEST(RoleTest, rolebase_match) {
RoleAttributes attr;
attr.set_host_name("caros");
attr.set_process_id(12345);
attr.set_node_id(1);
RoleBase role(attr, 1234567);
RoleAttributes target_attr;
EXPECT_TRUE(role.Match(target_attr));
target_attr.set_host_name("sorac");
EXPECT_FALSE(role.Match(target_attr));
target_attr.set_host_name("caros");
EXPECT_TRUE(role.Match(target_attr));
target_attr.set_process_id(54321);
EXPECT_FALSE(role.Match(target_attr));
target_attr.set_process_id(12345);
EXPECT_TRUE(role.Match(target_attr));
target_attr.set_node_id(2);
EXPECT_FALSE(role.Match(target_attr));
target_attr.set_node_id(1);
EXPECT_TRUE(role.Match(target_attr));
}
TEST(RoleTest, rolewriter_match) {
RoleAttributes attr;
attr.set_host_name("caros");
attr.set_process_id(12345);
attr.set_node_id(1);
RoleAttributes target_attr(attr);
attr.set_channel_id(2);
attr.set_id(3);
RoleWriter role(attr, 1234567);
EXPECT_TRUE(role.Match(target_attr));
target_attr.set_id(4);
EXPECT_FALSE(role.Match(target_attr));
target_attr.set_id(3);
EXPECT_TRUE(role.Match(target_attr));
target_attr.set_channel_id(3);
EXPECT_FALSE(role.Match(target_attr));
target_attr.set_channel_id(2);
EXPECT_TRUE(role.Match(target_attr));
}
TEST(RoleTest, roleserver_match) {
RoleAttributes attr;
attr.set_host_name("caros");
attr.set_process_id(12345);
attr.set_node_id(1);
RoleAttributes target_attr(attr);
attr.set_service_id(2);
RoleServer role(attr, 1234567);
EXPECT_TRUE(role.Match(target_attr));
target_attr.set_service_id(3);
EXPECT_FALSE(role.Match(target_attr));
target_attr.set_service_id(2);
EXPECT_TRUE(role.Match(target_attr));
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/specific_manager/node_manager.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/specific_manager/node_manager.h"
#include "cyber/common/global_data.h"
#include "cyber/common/log.h"
#include "cyber/state.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
NodeManager::NodeManager() {
allowed_role_ |= 1 << RoleType::ROLE_NODE;
change_type_ = ChangeType::CHANGE_NODE;
channel_name_ = "node_change_broadcast";
}
NodeManager::~NodeManager() {}
bool NodeManager::HasNode(const std::string& node_name) {
uint64_t key = common::GlobalData::RegisterNode(node_name);
return nodes_.Search(key);
}
void NodeManager::GetNodes(RoleAttrVec* nodes) {
RETURN_IF_NULL(nodes);
nodes_.GetAllRoles(nodes);
}
bool NodeManager::Check(const RoleAttributes& attr) {
RETURN_VAL_IF(!attr.has_node_name(), false);
RETURN_VAL_IF(!attr.has_node_id(), false);
return true;
}
void NodeManager::Dispose(const ChangeMsg& msg) {
if (msg.operate_type() == OperateType::OPT_JOIN) {
DisposeJoin(msg);
} else {
DisposeLeave(msg);
}
Notify(msg);
}
void NodeManager::OnTopoModuleLeave(const std::string& host_name,
int process_id) {
RETURN_IF(!is_discovery_started_.load());
RoleAttributes attr;
attr.set_host_name(host_name);
attr.set_process_id(process_id);
std::vector<RolePtr> nodes_to_remove;
nodes_.Search(attr, &nodes_to_remove);
for (auto& node : nodes_to_remove) {
nodes_.Remove(node->attributes().node_id());
}
ChangeMsg msg;
for (auto& node : nodes_to_remove) {
Convert(node->attributes(), RoleType::ROLE_NODE, OperateType::OPT_LEAVE,
&msg);
Notify(msg);
}
}
void NodeManager::DisposeJoin(const ChangeMsg& msg) {
auto node = std::make_shared<RoleNode>(msg.role_attr(), msg.timestamp());
uint64_t key = node->attributes().node_id();
// duplicated node
if (!nodes_.Add(key, node, false)) {
RolePtr existing_node;
if (!nodes_.Search(key, &existing_node)) {
nodes_.Add(key, node);
return;
}
RolePtr newer_node = existing_node;
if (node->IsEarlierThan(*newer_node)) {
nodes_.Add(key, node);
} else {
newer_node = node;
}
if (newer_node->attributes().process_id() == process_id_ &&
newer_node->attributes().host_name() == host_name_) {
AERROR << "this process will be terminated due to duplicated node["
<< node->attributes().node_name()
<< "], please ensure that each node has a unique name.";
AsyncShutdown();
}
}
}
void NodeManager::DisposeLeave(const ChangeMsg& msg) {
auto node = std::make_shared<RoleNode>(msg.role_attr(), msg.timestamp());
nodes_.Remove(node->attributes().node_id());
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/specific_manager/channel_manager.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/specific_manager/channel_manager.h"
#include <algorithm>
#include <set>
#include <utility>
#include "cyber/common/global_data.h"
#include "cyber/common/log.h"
#include "cyber/message/message_traits.h"
#include "cyber/message/py_message.h"
#include "cyber/message/raw_message.h"
#include "cyber/state.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
ChannelManager::ChannelManager() {
allowed_role_ |= 1 << RoleType::ROLE_WRITER;
allowed_role_ |= 1 << RoleType::ROLE_READER;
change_type_ = ChangeType::CHANGE_CHANNEL;
channel_name_ = "channel_change_broadcast";
exempted_msg_types_.emplace(message::MessageType<message::RawMessage>());
exempted_msg_types_.emplace(message::MessageType<message::PyMessageWrap>());
}
ChannelManager::~ChannelManager() {}
void ChannelManager::GetChannelNames(std::vector<std::string>* channels) {
RETURN_IF_NULL(channels);
std::unordered_set<std::string> local_channels;
std::vector<RolePtr> roles;
channel_writers_.GetAllRoles(&roles);
channel_readers_.GetAllRoles(&roles);
for (auto& role : roles) {
local_channels.emplace(role->attributes().channel_name());
}
std::move(local_channels.begin(), local_channels.end(),
std::back_inserter(*channels));
}
void ChannelManager::GetProtoDesc(const std::string& channel_name,
std::string* proto_desc) {
RETURN_IF_NULL(proto_desc);
uint64_t key = common::GlobalData::RegisterChannel(channel_name);
RolePtr writer = nullptr;
if (!channel_writers_.Search(key, &writer)) {
return;
}
if (writer->attributes().has_proto_desc()) {
*proto_desc = writer->attributes().proto_desc();
}
}
void ChannelManager::GetMsgType(const std::string& channel_name,
std::string* msg_type) {
RETURN_IF_NULL(msg_type);
uint64_t key = common::GlobalData::RegisterChannel(channel_name);
RolePtr writer = nullptr;
if (!channel_writers_.Search(key, &writer)) {
AERROR << "cannot find writer of channel: " << channel_name
<< " key: " << key;
return;
}
if (writer->attributes().has_message_type()) {
*msg_type = writer->attributes().message_type();
}
}
bool ChannelManager::HasWriter(const std::string& channel_name) {
uint64_t key = common::GlobalData::RegisterChannel(channel_name);
return channel_writers_.Search(key);
}
void ChannelManager::GetWriters(RoleAttrVec* writers) {
RETURN_IF_NULL(writers);
channel_writers_.GetAllRoles(writers);
}
void ChannelManager::GetWritersOfNode(const std::string& node_name,
RoleAttrVec* writers) {
RETURN_IF_NULL(writers);
uint64_t key = common::GlobalData::RegisterNode(node_name);
node_writers_.Search(key, writers);
}
void ChannelManager::GetWritersOfChannel(const std::string& channel_name,
RoleAttrVec* writers) {
RETURN_IF_NULL(writers);
uint64_t key = common::GlobalData::RegisterChannel(channel_name);
channel_writers_.Search(key, writers);
}
bool ChannelManager::HasReader(const std::string& channel_name) {
uint64_t key = common::GlobalData::RegisterChannel(channel_name);
return channel_readers_.Search(key);
}
void ChannelManager::GetReaders(RoleAttrVec* readers) {
RETURN_IF_NULL(readers);
channel_readers_.GetAllRoles(readers);
}
void ChannelManager::GetReadersOfNode(const std::string& node_name,
RoleAttrVec* readers) {
RETURN_IF_NULL(readers);
uint64_t key = common::GlobalData::RegisterNode(node_name);
node_readers_.Search(key, readers);
}
void ChannelManager::GetReadersOfChannel(const std::string& channel_name,
RoleAttrVec* readers) {
RETURN_IF_NULL(readers);
uint64_t key = common::GlobalData::RegisterChannel(channel_name);
channel_readers_.Search(key, readers);
}
void ChannelManager::GetUpstreamOfNode(const std::string& node_name,
RoleAttrVec* upstream_nodes) {
RETURN_IF_NULL(upstream_nodes);
RoleAttrVec readers;
GetReadersOfNode(node_name, &readers);
if (readers.empty()) {
return;
}
std::unordered_set<std::string> channels;
for (auto& reader : readers) {
channels.emplace(reader.channel_name());
}
RoleAttrVec writers;
for (auto& channel : channels) {
GetWritersOfChannel(channel, &writers);
}
std::unordered_map<std::string, proto::RoleAttributes> nodes;
for (auto& writer : writers) {
proto::RoleAttributes attr;
attr.set_host_name(writer.host_name());
attr.set_process_id(writer.process_id());
attr.set_node_name(writer.node_name());
attr.set_node_id(writer.node_id());
nodes[attr.node_name()] = attr;
}
for (auto& item : nodes) {
upstream_nodes->emplace_back(item.second);
}
}
void ChannelManager::GetDownstreamOfNode(const std::string& node_name,
RoleAttrVec* downstream_nodes) {
RETURN_IF_NULL(downstream_nodes);
RoleAttrVec writers;
GetWritersOfNode(node_name, &writers);
if (writers.empty()) {
return;
}
std::unordered_set<std::string> channels;
for (auto& writer : writers) {
channels.emplace(writer.channel_name());
}
RoleAttrVec readers;
for (auto& channel : channels) {
GetReadersOfChannel(channel, &readers);
}
std::unordered_map<std::string, proto::RoleAttributes> nodes;
for (auto& reader : readers) {
proto::RoleAttributes attr;
attr.set_host_name(reader.host_name());
attr.set_process_id(reader.process_id());
attr.set_node_name(reader.node_name());
attr.set_node_id(reader.node_id());
nodes[attr.node_name()] = attr;
}
for (auto& item : nodes) {
downstream_nodes->emplace_back(item.second);
}
}
FlowDirection ChannelManager::GetFlowDirection(
const std::string& lhs_node_name, const std::string& rhs_node_name) {
Vertice lhs(lhs_node_name);
Vertice rhs(rhs_node_name);
return node_graph_.GetDirectionOf(lhs, rhs);
}
bool ChannelManager::IsMessageTypeMatching(const std::string& lhs,
const std::string& rhs) {
if (lhs == rhs) {
return true;
}
if (exempted_msg_types_.count(lhs) > 0) {
return true;
}
if (exempted_msg_types_.count(rhs) > 0) {
return true;
}
return false;
}
bool ChannelManager::Check(const RoleAttributes& attr) {
RETURN_VAL_IF(!attr.has_channel_name(), false);
RETURN_VAL_IF(!attr.has_channel_id(), false);
RETURN_VAL_IF(!attr.has_id(), false);
return true;
}
void ChannelManager::Dispose(const ChangeMsg& msg) {
if (msg.operate_type() == OperateType::OPT_JOIN) {
DisposeJoin(msg);
} else {
DisposeLeave(msg);
}
Notify(msg);
}
void ChannelManager::OnTopoModuleLeave(const std::string& host_name,
int process_id) {
RETURN_IF(!is_discovery_started_.load());
RoleAttributes attr;
attr.set_host_name(host_name);
attr.set_process_id(process_id);
std::vector<RolePtr> writers_to_remove;
channel_writers_.Search(attr, &writers_to_remove);
std::vector<RolePtr> readers_to_remove;
channel_readers_.Search(attr, &readers_to_remove);
ChangeMsg msg;
for (auto& writer : writers_to_remove) {
Convert(writer->attributes(), RoleType::ROLE_WRITER, OperateType::OPT_LEAVE,
&msg);
DisposeLeave(msg);
Notify(msg);
}
for (auto& reader : readers_to_remove) {
Convert(reader->attributes(), RoleType::ROLE_READER, OperateType::OPT_LEAVE,
&msg);
DisposeLeave(msg);
Notify(msg);
}
}
void ChannelManager::DisposeJoin(const ChangeMsg& msg) {
ScanMessageType(msg);
Vertice v(msg.role_attr().node_name());
Edge e;
e.set_value(msg.role_attr().channel_name());
if (msg.role_type() == RoleType::ROLE_WRITER) {
if (msg.role_attr().has_proto_desc() &&
msg.role_attr().proto_desc() != "") {
message::ProtobufFactory::Instance()->RegisterMessage(
msg.role_attr().proto_desc());
}
auto role = std::make_shared<RoleWriter>(msg.role_attr(), msg.timestamp());
node_writers_.Add(role->attributes().node_id(), role);
channel_writers_.Add(role->attributes().channel_id(), role);
e.set_src(v);
} else {
auto role = std::make_shared<RoleReader>(msg.role_attr(), msg.timestamp());
node_readers_.Add(role->attributes().node_id(), role);
channel_readers_.Add(role->attributes().channel_id(), role);
e.set_dst(v);
}
node_graph_.Insert(e);
}
void ChannelManager::DisposeLeave(const ChangeMsg& msg) {
Vertice v(msg.role_attr().node_name());
Edge e;
e.set_value(msg.role_attr().channel_name());
if (msg.role_type() == RoleType::ROLE_WRITER) {
auto role = std::make_shared<RoleWriter>(msg.role_attr());
node_writers_.Remove(role->attributes().node_id(), role);
channel_writers_.Remove(role->attributes().channel_id(), role);
e.set_src(v);
} else {
auto role = std::make_shared<RoleReader>(msg.role_attr());
node_readers_.Remove(role->attributes().node_id(), role);
channel_readers_.Remove(role->attributes().channel_id(), role);
e.set_dst(v);
}
node_graph_.Delete(e);
}
void ChannelManager::ScanMessageType(const ChangeMsg& msg) {
uint64_t key = msg.role_attr().channel_id();
std::string role_type("reader");
if (msg.role_type() == RoleType::ROLE_WRITER) {
role_type = "writer";
}
RoleAttrVec existed_writers;
channel_writers_.Search(key, &existed_writers);
for (auto& w_attr : existed_writers) {
if (!IsMessageTypeMatching(msg.role_attr().message_type(),
w_attr.message_type())) {
AERROR << "newly added " << role_type << "(belongs to node["
<< msg.role_attr().node_name() << "])"
<< "'s message type[" << msg.role_attr().message_type()
<< "] does not match the exsited writer(belongs to node["
<< w_attr.node_name() << "])'s message type["
<< w_attr.message_type() << "].";
}
}
RoleAttrVec existed_readers;
channel_readers_.Search(key, &existed_readers);
for (auto& r_attr : existed_readers) {
if (!IsMessageTypeMatching(msg.role_attr().message_type(),
r_attr.message_type())) {
AERROR << "newly added " << role_type << "(belongs to node["
<< msg.role_attr().node_name() << "])"
<< "'s message type[" << msg.role_attr().message_type()
<< "] does not match the exsited reader(belongs to node["
<< r_attr.node_name() << "])'s message type["
<< r_attr.message_type() << "].";
}
}
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/specific_manager/channel_manager_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/specific_manager/channel_manager.h"
#include <memory>
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "cyber/common/global_data.h"
#include "cyber/message/message_traits.h"
#include "cyber/message/protobuf_factory.h"
#include "cyber/proto/unit_test.pb.h"
#include "cyber/transport/common/identity.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class ChannelManagerTest : public ::testing::Test {
protected:
ChannelManagerTest() : channel_num_(10) {
RoleAttributes role_attr;
role_attr.set_host_name(common::GlobalData::Instance()->HostName());
role_attr.set_process_id(common::GlobalData::Instance()->ProcessId());
// add writers
for (int i = 0; i < channel_num_; ++i) {
role_attr.set_node_name("node_" + std::to_string(i));
uint64_t node_id =
common::GlobalData::RegisterNode(role_attr.node_name());
role_attr.set_node_id(node_id);
role_attr.set_channel_name("channel_" + std::to_string(i));
uint64_t channel_id = common::GlobalData::Instance()->RegisterChannel(
role_attr.channel_name());
role_attr.set_channel_id(channel_id);
transport::Identity id;
role_attr.set_id(id.HashValue());
channel_manager_.Join(role_attr, RoleType::ROLE_WRITER);
}
// add readers
for (int i = 0; i < channel_num_; ++i) {
role_attr.set_node_name("node_" + std::to_string(i));
uint64_t node_id =
common::GlobalData::RegisterNode(role_attr.node_name());
role_attr.set_node_id(node_id);
role_attr.set_channel_name("channel_" + std::to_string(i));
uint64_t channel_id = common::GlobalData::Instance()->RegisterChannel(
role_attr.channel_name());
role_attr.set_channel_id(channel_id);
transport::Identity id;
role_attr.set_id(id.HashValue());
channel_manager_.Join(role_attr, RoleType::ROLE_READER);
}
}
virtual ~ChannelManagerTest() { channel_manager_.Shutdown(); }
virtual void SetUp() {}
virtual void TearDown() {}
int channel_num_;
ChannelManager channel_manager_;
};
TEST_F(ChannelManagerTest, get_channel_names) {
std::vector<std::string> channels;
EXPECT_TRUE(channels.empty());
channel_manager_.GetChannelNames(&channels);
EXPECT_EQ(channels.size(), channel_num_);
}
TEST_F(ChannelManagerTest, get_proto_desc) {
const std::string guard = "guard";
std::string proto_desc(guard);
// channel does not exist
channel_manager_.GetProtoDesc("wasd", &proto_desc);
EXPECT_EQ(proto_desc, guard);
// channel exists, but no proto desc
channel_manager_.GetProtoDesc("channel_0", &proto_desc);
EXPECT_EQ(proto_desc, guard);
// add a writer with empty proto desc
RoleAttributes role_attr;
role_attr.set_host_name(common::GlobalData::Instance()->HostName());
role_attr.set_process_id(common::GlobalData::Instance()->ProcessId());
role_attr.set_node_name("proto");
uint64_t node_id = common::GlobalData::RegisterNode("proto");
role_attr.set_node_id(node_id);
role_attr.set_channel_name("wasd");
uint64_t channel_id = common::GlobalData::Instance()->RegisterChannel("wasd");
role_attr.set_channel_id(channel_id);
transport::Identity id_0;
role_attr.set_id(id_0.HashValue());
role_attr.set_proto_desc("");
EXPECT_FALSE(channel_manager_.Join(role_attr, RoleType::ROLE_WRITER));
channel_manager_.GetProtoDesc("wasd", &proto_desc);
EXPECT_EQ(proto_desc, "");
EXPECT_FALSE(channel_manager_.Leave(role_attr, RoleType::ROLE_WRITER));
// add a writer with real proto desc
role_attr.set_node_name("proto");
node_id = common::GlobalData::RegisterNode("proto");
role_attr.set_node_id(node_id);
role_attr.set_channel_name("jkl");
channel_id = common::GlobalData::Instance()->RegisterChannel("jkl");
role_attr.set_channel_id(channel_id);
transport::Identity id_1;
role_attr.set_id(id_1.HashValue());
std::string tmp("");
message::GetDescriptorString<proto::Chatter>(
message::MessageType<proto::Chatter>(), &tmp);
role_attr.set_proto_desc(tmp);
EXPECT_FALSE(channel_manager_.Join(role_attr, RoleType::ROLE_WRITER));
proto_desc = guard;
EXPECT_TRUE(channel_manager_.HasWriter("jkl"));
channel_manager_.GetProtoDesc("jkl", &proto_desc);
EXPECT_NE(proto_desc, guard);
EXPECT_FALSE(channel_manager_.Leave(role_attr, RoleType::ROLE_WRITER));
}
TEST_F(ChannelManagerTest, has_writer) {
for (int i = 0; i < channel_num_; ++i) {
EXPECT_TRUE(channel_manager_.HasWriter("channel_" + std::to_string(i)));
}
}
TEST_F(ChannelManagerTest, get_writers_attr) {
std::vector<proto::RoleAttributes> writers;
EXPECT_TRUE(writers.empty());
channel_manager_.GetWriters(&writers);
EXPECT_EQ(writers.size(), channel_num_);
writers.clear();
for (int i = 0; i < channel_num_; ++i) {
channel_manager_.GetWritersOfChannel("channel_" + std::to_string(i),
&writers);
EXPECT_EQ(writers.size(), 1);
writers.clear();
channel_manager_.GetWritersOfNode("node_" + std::to_string(i), &writers);
EXPECT_EQ(writers.size(), 1);
writers.clear();
}
RoleAttributes role_attr;
role_attr.set_host_name(common::GlobalData::Instance()->HostName());
role_attr.set_process_id(common::GlobalData::Instance()->ProcessId());
role_attr.set_node_name("node_extra");
uint64_t node_id = common::GlobalData::RegisterNode("node_extra");
role_attr.set_node_id(node_id);
// add writers
for (int i = 0; i < 100; ++i) {
role_attr.set_channel_name("channel_" + std::to_string(i));
uint64_t channel_id = common::GlobalData::Instance()->RegisterChannel(
role_attr.channel_name());
role_attr.set_channel_id(channel_id);
transport::Identity id;
role_attr.set_id(id.HashValue());
channel_manager_.Join(role_attr, RoleType::ROLE_WRITER);
}
writers.clear();
channel_manager_.GetWritersOfNode("node_extra", &writers);
EXPECT_EQ(writers.size(), 100);
}
TEST_F(ChannelManagerTest, has_reader) {
for (int i = 0; i < channel_num_; ++i) {
EXPECT_TRUE(channel_manager_.HasReader("channel_" + std::to_string(i)));
}
}
TEST_F(ChannelManagerTest, get_readers_attr) {
std::vector<proto::RoleAttributes> readers;
EXPECT_TRUE(readers.empty());
channel_manager_.GetReaders(&readers);
EXPECT_EQ(readers.size(), channel_num_);
readers.clear();
for (int i = 0; i < channel_num_; ++i) {
channel_manager_.GetReadersOfChannel("channel_" + std::to_string(i),
&readers);
EXPECT_EQ(readers.size(), 1);
readers.clear();
channel_manager_.GetReadersOfNode("node_" + std::to_string(i), &readers);
EXPECT_EQ(readers.size(), 1);
readers.clear();
}
channel_manager_.GetReadersOfChannel("channel_0", &readers);
EXPECT_EQ(readers.size(), 1);
RoleAttributes role_attr(readers[0]);
EXPECT_FALSE(channel_manager_.Leave(role_attr, RoleType::ROLE_READER));
readers.clear();
channel_manager_.GetReadersOfChannel("channel_0", &readers);
EXPECT_EQ(readers.size(), 0);
EXPECT_FALSE(channel_manager_.Join(role_attr, RoleType::ROLE_READER));
readers.clear();
channel_manager_.GetReadersOfChannel("channel_0", &readers);
EXPECT_EQ(readers.size(), 1);
role_attr.set_host_name(common::GlobalData::Instance()->HostName());
role_attr.set_process_id(common::GlobalData::Instance()->ProcessId());
role_attr.set_node_name("node_extra");
uint64_t node_id = common::GlobalData::RegisterNode("node_extra");
role_attr.set_node_id(node_id);
// add readers
for (int i = 0; i < 100; ++i) {
role_attr.set_channel_name("channel_" + std::to_string(i));
uint64_t channel_id = common::GlobalData::Instance()->RegisterChannel(
role_attr.channel_name());
role_attr.set_channel_id(channel_id);
transport::Identity id;
role_attr.set_id(id.HashValue());
channel_manager_.Join(role_attr, RoleType::ROLE_READER);
}
readers.clear();
channel_manager_.GetReadersOfNode("node_extra", &readers);
EXPECT_EQ(readers.size(), 100);
}
TEST_F(ChannelManagerTest, change) {
RoleAttributes role_attr;
EXPECT_FALSE(channel_manager_.Join(role_attr, RoleType::ROLE_NODE));
EXPECT_FALSE(channel_manager_.Join(role_attr, RoleType::ROLE_WRITER));
role_attr.set_host_name(common::GlobalData::Instance()->HostName());
role_attr.set_process_id(common::GlobalData::Instance()->ProcessId());
role_attr.set_node_name("add_change");
uint64_t node_id = common::GlobalData::RegisterNode("add_change");
role_attr.set_node_id(node_id);
role_attr.set_channel_name("wasd");
uint64_t channel_id = common::GlobalData::Instance()->RegisterChannel("wasd");
role_attr.set_channel_id(channel_id);
EXPECT_FALSE(channel_manager_.Join(role_attr, RoleType::ROLE_WRITER));
transport::Identity id;
role_attr.set_id(id.HashValue());
EXPECT_FALSE(channel_manager_.Join(role_attr, RoleType::ROLE_WRITER));
EXPECT_TRUE(channel_manager_.HasWriter("channel_0"));
}
TEST_F(ChannelManagerTest, get_upstream_downstream) {
std::vector<proto::RoleAttributes> nodes;
for (int i = 0; i < channel_num_; ++i) {
channel_manager_.GetUpstreamOfNode("node_" + std::to_string(i), &nodes);
EXPECT_EQ(nodes.size(), 1);
nodes.clear();
channel_manager_.GetDownstreamOfNode("node_" + std::to_string(i), &nodes);
EXPECT_EQ(nodes.size(), 1);
nodes.clear();
}
// add dag like this
// A---a---B---c---D
// | |
// ----b---C---d----
RoleAttributes role_attr;
role_attr.set_host_name(common::GlobalData::Instance()->HostName());
role_attr.set_process_id(common::GlobalData::Instance()->ProcessId());
role_attr.set_node_name("A");
uint64_t node_id = common::GlobalData::RegisterNode(role_attr.node_name());
role_attr.set_node_id(node_id);
role_attr.set_channel_name("a");
uint64_t channel_id =
common::GlobalData::Instance()->RegisterChannel(role_attr.channel_name());
role_attr.set_channel_id(channel_id);
role_attr.set_id(transport::Identity().HashValue());
channel_manager_.Join(role_attr, RoleType::ROLE_WRITER);
role_attr.set_channel_name("b");
channel_id =
common::GlobalData::Instance()->RegisterChannel(role_attr.channel_name());
role_attr.set_channel_id(channel_id);
role_attr.set_id(transport::Identity().HashValue());
channel_manager_.Join(role_attr, RoleType::ROLE_WRITER);
role_attr.set_node_name("B");
node_id = common::GlobalData::RegisterNode(role_attr.node_name());
role_attr.set_node_id(node_id);
role_attr.set_channel_name("c");
channel_id =
common::GlobalData::Instance()->RegisterChannel(role_attr.channel_name());
role_attr.set_channel_id(channel_id);
role_attr.set_id(transport::Identity().HashValue());
channel_manager_.Join(role_attr, RoleType::ROLE_WRITER);
role_attr.set_channel_name("a");
channel_id =
common::GlobalData::Instance()->RegisterChannel(role_attr.channel_name());
role_attr.set_channel_id(channel_id);
role_attr.set_id(transport::Identity().HashValue());
channel_manager_.Join(role_attr, RoleType::ROLE_READER);
role_attr.set_node_name("C");
node_id = common::GlobalData::RegisterNode(role_attr.node_name());
role_attr.set_node_id(node_id);
role_attr.set_channel_name("b");
channel_id =
common::GlobalData::Instance()->RegisterChannel(role_attr.channel_name());
role_attr.set_channel_id(channel_id);
role_attr.set_id(transport::Identity().HashValue());
channel_manager_.Join(role_attr, RoleType::ROLE_READER);
role_attr.set_channel_name("d");
channel_id =
common::GlobalData::Instance()->RegisterChannel(role_attr.channel_name());
role_attr.set_channel_id(channel_id);
role_attr.set_id(transport::Identity().HashValue());
channel_manager_.Join(role_attr, RoleType::ROLE_WRITER);
role_attr.set_node_name("D");
node_id = common::GlobalData::RegisterNode(role_attr.node_name());
role_attr.set_node_id(node_id);
role_attr.set_channel_name("c");
channel_id =
common::GlobalData::Instance()->RegisterChannel(role_attr.channel_name());
role_attr.set_channel_id(channel_id);
role_attr.set_id(transport::Identity().HashValue());
channel_manager_.Join(role_attr, RoleType::ROLE_READER);
role_attr.set_channel_name("d");
channel_id =
common::GlobalData::Instance()->RegisterChannel(role_attr.channel_name());
role_attr.set_channel_id(channel_id);
role_attr.set_id(transport::Identity().HashValue());
channel_manager_.Join(role_attr, RoleType::ROLE_READER);
nodes.clear();
channel_manager_.GetUpstreamOfNode("A", &nodes);
EXPECT_TRUE(nodes.empty());
nodes.clear();
channel_manager_.GetDownstreamOfNode("A", &nodes);
EXPECT_EQ(nodes.size(), 2);
nodes.clear();
channel_manager_.GetUpstreamOfNode("B", &nodes);
EXPECT_EQ(nodes.size(), 1);
nodes.clear();
channel_manager_.GetDownstreamOfNode("B", &nodes);
EXPECT_EQ(nodes.size(), 1);
nodes.clear();
channel_manager_.GetUpstreamOfNode("C", &nodes);
EXPECT_EQ(nodes.size(), 1);
nodes.clear();
channel_manager_.GetDownstreamOfNode("C", &nodes);
EXPECT_EQ(nodes.size(), 1);
nodes.clear();
channel_manager_.GetUpstreamOfNode("D", &nodes);
EXPECT_EQ(nodes.size(), 2);
nodes.clear();
channel_manager_.GetDownstreamOfNode("D", &nodes);
EXPECT_TRUE(nodes.empty());
nodes.clear();
channel_manager_.GetUpstreamOfNode("E", &nodes);
EXPECT_TRUE(nodes.empty());
nodes.clear();
channel_manager_.GetDownstreamOfNode("E", &nodes);
EXPECT_TRUE(nodes.empty());
EXPECT_EQ(channel_manager_.GetFlowDirection("A", "B"), UPSTREAM);
EXPECT_EQ(channel_manager_.GetFlowDirection("A", "C"), UPSTREAM);
EXPECT_EQ(channel_manager_.GetFlowDirection("A", "D"), UPSTREAM);
EXPECT_EQ(channel_manager_.GetFlowDirection("B", "D"), UPSTREAM);
EXPECT_EQ(channel_manager_.GetFlowDirection("C", "D"), UPSTREAM);
EXPECT_EQ(channel_manager_.GetFlowDirection("B", "A"), DOWNSTREAM);
EXPECT_EQ(channel_manager_.GetFlowDirection("C", "A"), DOWNSTREAM);
EXPECT_EQ(channel_manager_.GetFlowDirection("D", "A"), DOWNSTREAM);
EXPECT_EQ(channel_manager_.GetFlowDirection("D", "B"), DOWNSTREAM);
EXPECT_EQ(channel_manager_.GetFlowDirection("D", "C"), DOWNSTREAM);
EXPECT_EQ(channel_manager_.GetFlowDirection("A", "E"), UNREACHABLE);
EXPECT_EQ(channel_manager_.GetFlowDirection("E", "A"), UNREACHABLE);
}
TEST_F(ChannelManagerTest, is_message_type_matching) {
const std::string raw_msg_type_1 =
message::MessageType<message::RawMessage>();
const std::string py_msg_type =
message::MessageType<message::PyMessageWrap>();
const std::string chatter_msg_type = message::MessageType<proto::Chatter>();
const std::string change_msg_type = message::MessageType<proto::ChangeMsg>();
EXPECT_TRUE(channel_manager_.IsMessageTypeMatching(chatter_msg_type,
chatter_msg_type));
EXPECT_FALSE(channel_manager_.IsMessageTypeMatching(chatter_msg_type,
change_msg_type));
EXPECT_TRUE(
channel_manager_.IsMessageTypeMatching(chatter_msg_type, raw_msg_type_1));
EXPECT_TRUE(
channel_manager_.IsMessageTypeMatching(chatter_msg_type, py_msg_type));
EXPECT_TRUE(
channel_manager_.IsMessageTypeMatching(raw_msg_type_1, py_msg_type));
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/specific_manager/channel_manager.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_DISCOVERY_SPECIFIC_MANAGER_CHANNEL_MANAGER_H_
#define CYBER_SERVICE_DISCOVERY_SPECIFIC_MANAGER_CHANNEL_MANAGER_H_
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "cyber/service_discovery/container/graph.h"
#include "cyber/service_discovery/container/multi_value_warehouse.h"
#include "cyber/service_discovery/container/single_value_warehouse.h"
#include "cyber/service_discovery/role/role.h"
#include "cyber/service_discovery/specific_manager/manager.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class TopologyManager;
/**
* @class ChannelManager
* @brief Topology Manager of Service related
*/
class ChannelManager : public Manager {
friend class TopologyManager;
public:
using RoleAttrVec = std::vector<proto::RoleAttributes>;
using WriterWarehouse = MultiValueWarehouse;
using ReaderWarehouse = MultiValueWarehouse;
using ExemptedMessageTypes = std::unordered_set<std::string>;
/**
* @brief Construct a new Channel Manager object
*/
ChannelManager();
/**
* @brief Destroy the Channel Manager object
*/
virtual ~ChannelManager();
/**
* @brief Get all channel names in the topology
*
* @param channels result vector
*/
void GetChannelNames(std::vector<std::string>* channels);
/**
* @brief Get the Protocol Desc of `channel_name`
*
* @param channel_name channel name we want to inquire
* @param proto_desc result string, empty if inquire failed
*/
void GetProtoDesc(const std::string& channel_name, std::string* proto_desc);
/**
* @brief Get the Msg Type of `channel_name`
*
* @param channel_name channel name we want to inquire
* @param msg_type result string, empty if inquire failed
*/
void GetMsgType(const std::string& channel_name, std::string* msg_type);
/**
* @brief Inquire if there is at least one Writer that publishes
* `channel_name`
*
* @param channel_name channel name we want to inquire
* @return true if there is at least one Writer
* @return false if there are no Writers
*/
bool HasWriter(const std::string& channel_name);
/**
* @brief Get All Writers object
*
* @param writers result RoleAttr vector
*/
void GetWriters(RoleAttrVec* writers);
/**
* @brief Get the Writers Of Node object
*
* @param node_name node's name we want to inquire
* @param writers result RoleAttribute vector
*/
void GetWritersOfNode(const std::string& node_name, RoleAttrVec* writers);
/**
* @brief Get the Writers Of Channel object
*
* @param channel_name channel's name we want to inquire
* @param writers result RoleAttribute vector
*/
void GetWritersOfChannel(const std::string& channel_name,
RoleAttrVec* writers);
/**
* @brief Inquire if there is at least one Reader that publishes
* `channel_name`
*
* @param channel_name channel name we want to inquire
* @return true if there is at least one Reader
* @return false if there are no Reader
*/
bool HasReader(const std::string& channel_name);
/**
* @brief Get All Readers object
*
* @param readers result RoleAttr vector
*/
void GetReaders(RoleAttrVec* readers);
/**
* @brief Get the Readers Of Node object
*
* @param node_name node's name we want to inquire
* @param readers result RoleAttribute vector
*/
void GetReadersOfNode(const std::string& node_name, RoleAttrVec* readers);
/**
* @brief Get the Readers Of Channel object
*
* @param channel_name channel's name we want to inquire
* @param readers result RoleAttribute vector
*/
void GetReadersOfChannel(const std::string& channel_name,
RoleAttrVec* readers);
/**
* @brief Get the Upstream Of Node object.
* If Node A has writer that publishes channel-1, and Node B has reader that
* subscribes channel-1 then A is B's Upstream node, and B is A's Downstream
* node
*
* @param node_name node's name we want to inquire
* @param upstream_nodes result RoleAttribute vector
*/
void GetUpstreamOfNode(const std::string& node_name,
RoleAttrVec* upstream_nodes);
/**
* @brief Get the Downstream Of Node object.
* If Node A has writer that publishes channel-1, and Node B has reader that
* subscribes channel-1 then A is B's Upstream node, and B is A's Downstream
* node
*
* @param node_name node's name we want to inquire
* @param downstream_nodes result RoleAttribute vector
*/
void GetDownstreamOfNode(const std::string& node_name,
RoleAttrVec* downstream_nodes);
/**
* @brief Get the Flow Direction from `lhs_node_node` to `rhs_node_name`
* You can see FlowDirection's description for more information
* @return FlowDirection result direction
*/
FlowDirection GetFlowDirection(const std::string& lhs_node_name,
const std::string& rhs_node_name);
/**
* @brief Is `lhs` and `rhs` have same MessageType
*
* @param lhs the left message type to compare
* @param rhs the right message type to compare
* @return true if type matches
* @return false if type does not matches
*/
bool IsMessageTypeMatching(const std::string& lhs, const std::string& rhs);
private:
bool Check(const RoleAttributes& attr) override;
void Dispose(const ChangeMsg& msg) override;
void OnTopoModuleLeave(const std::string& host_name, int process_id) override;
void DisposeJoin(const ChangeMsg& msg);
void DisposeLeave(const ChangeMsg& msg);
void ScanMessageType(const ChangeMsg& msg);
ExemptedMessageTypes exempted_msg_types_;
Graph node_graph_;
// key: node_id
WriterWarehouse node_writers_;
ReaderWarehouse node_readers_;
// key: channel_id
WriterWarehouse channel_writers_;
ReaderWarehouse channel_readers_;
};
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_DISCOVERY_SPECIFIC_MANAGER_CHANNEL_MANAGER_H_
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/specific_manager/manager.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/specific_manager/manager.h"
#include "cyber/common/global_data.h"
#include "cyber/common/log.h"
#include "cyber/message/message_traits.h"
#include "cyber/time/time.h"
#include "cyber/transport/qos/qos_profile_conf.h"
#include "cyber/transport/rtps/attributes_filler.h"
#include "cyber/transport/rtps/underlay_message.h"
#include "cyber/transport/rtps/underlay_message_type.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
using transport::AttributesFiller;
using transport::QosProfileConf;
Manager::Manager()
: is_shutdown_(false),
is_discovery_started_(false),
allowed_role_(0),
change_type_(proto::ChangeType::CHANGE_PARTICIPANT),
channel_name_(""),
publisher_(nullptr),
subscriber_(nullptr),
listener_(nullptr) {
host_name_ = common::GlobalData::Instance()->HostName();
process_id_ = common::GlobalData::Instance()->ProcessId();
}
Manager::~Manager() { Shutdown(); }
bool Manager::StartDiscovery(RtpsParticipant* participant) {
if (participant == nullptr) {
return false;
}
if (is_discovery_started_.exchange(true)) {
return true;
}
if (!CreatePublisher(participant) || !CreateSubscriber(participant)) {
AERROR << "create publisher or subscriber failed.";
StopDiscovery();
return false;
}
return true;
}
void Manager::StopDiscovery() {
if (!is_discovery_started_.exchange(false)) {
return;
}
{
std::lock_guard<std::mutex> lg(lock_);
if (publisher_ != nullptr) {
eprosima::fastrtps::Domain::removePublisher(publisher_);
publisher_ = nullptr;
}
}
if (subscriber_ != nullptr) {
eprosima::fastrtps::Domain::removeSubscriber(subscriber_);
subscriber_ = nullptr;
}
if (listener_ != nullptr) {
delete listener_;
listener_ = nullptr;
}
}
void Manager::Shutdown() {
if (is_shutdown_.exchange(true)) {
return;
}
StopDiscovery();
signal_.DisconnectAllSlots();
}
bool Manager::Join(const RoleAttributes& attr, RoleType role,
bool need_publish) {
if (is_shutdown_.load()) {
ADEBUG << "the manager has been shut down.";
return false;
}
RETURN_VAL_IF(!((1 << role) & allowed_role_), false);
RETURN_VAL_IF(!Check(attr), false);
ChangeMsg msg;
Convert(attr, role, OperateType::OPT_JOIN, &msg);
Dispose(msg);
if (need_publish) {
return Publish(msg);
}
return true;
}
bool Manager::Leave(const RoleAttributes& attr, RoleType role) {
if (is_shutdown_.load()) {
ADEBUG << "the manager has been shut down.";
return false;
}
RETURN_VAL_IF(!((1 << role) & allowed_role_), false);
RETURN_VAL_IF(!Check(attr), false);
ChangeMsg msg;
Convert(attr, role, OperateType::OPT_LEAVE, &msg);
Dispose(msg);
if (NeedPublish(msg)) {
return Publish(msg);
}
return true;
}
Manager::ChangeConnection Manager::AddChangeListener(const ChangeFunc& func) {
return signal_.Connect(func);
}
void Manager::RemoveChangeListener(const ChangeConnection& conn) {
auto local_conn = conn;
local_conn.Disconnect();
}
bool Manager::CreatePublisher(RtpsParticipant* participant) {
RtpsPublisherAttr pub_attr;
RETURN_VAL_IF(
!AttributesFiller::FillInPubAttr(
channel_name_, QosProfileConf::QOS_PROFILE_TOPO_CHANGE, &pub_attr),
false);
publisher_ =
eprosima::fastrtps::Domain::createPublisher(participant, pub_attr);
return publisher_ != nullptr;
}
bool Manager::CreateSubscriber(RtpsParticipant* participant) {
RtpsSubscriberAttr sub_attr;
RETURN_VAL_IF(
!AttributesFiller::FillInSubAttr(
channel_name_, QosProfileConf::QOS_PROFILE_TOPO_CHANGE, &sub_attr),
false);
listener_ = new SubscriberListener(
std::bind(&Manager::OnRemoteChange, this, std::placeholders::_1));
subscriber_ = eprosima::fastrtps::Domain::createSubscriber(
participant, sub_attr, listener_);
return subscriber_ != nullptr;
}
bool Manager::NeedPublish(const ChangeMsg& msg) const {
(void)msg;
return true;
}
void Manager::Convert(const RoleAttributes& attr, RoleType role,
OperateType opt, ChangeMsg* msg) {
msg->set_timestamp(cyber::Time::Now().ToNanosecond());
msg->set_change_type(change_type_);
msg->set_operate_type(opt);
msg->set_role_type(role);
auto role_attr = msg->mutable_role_attr();
role_attr->CopyFrom(attr);
if (!role_attr->has_host_name()) {
role_attr->set_host_name(host_name_);
}
if (!role_attr->has_process_id()) {
role_attr->set_process_id(process_id_);
}
}
void Manager::Notify(const ChangeMsg& msg) { signal_(msg); }
void Manager::OnRemoteChange(const std::string& msg_str) {
if (is_shutdown_.load()) {
ADEBUG << "the manager has been shut down.";
return;
}
ChangeMsg msg;
RETURN_IF(!message::ParseFromString(msg_str, &msg));
if (IsFromSameProcess(msg)) {
return;
}
RETURN_IF(!Check(msg.role_attr()));
Dispose(msg);
}
bool Manager::Publish(const ChangeMsg& msg) {
if (!is_discovery_started_.load()) {
ADEBUG << "discovery is not started.";
return false;
}
apollo::cyber::transport::UnderlayMessage m;
RETURN_VAL_IF(!message::SerializeToString(msg, &m.data()), false);
{
std::lock_guard<std::mutex> lg(lock_);
if (publisher_ != nullptr) {
return publisher_->write(reinterpret_cast<void*>(&m));
}
}
return true;
}
bool Manager::IsFromSameProcess(const ChangeMsg& msg) {
auto& host_name = msg.role_attr().host_name();
int process_id = msg.role_attr().process_id();
if (process_id != process_id_ || host_name != host_name_) {
return false;
}
return true;
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/specific_manager/manager.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_DISCOVERY_SPECIFIC_MANAGER_MANAGER_H_
#define CYBER_SERVICE_DISCOVERY_SPECIFIC_MANAGER_MANAGER_H_
#include <atomic>
#include <functional>
#include <mutex>
#include <string>
#include "fastrtps/Domain.h"
#include "fastrtps/attributes/PublisherAttributes.h"
#include "fastrtps/attributes/SubscriberAttributes.h"
#include "fastrtps/participant/Participant.h"
#include "fastrtps/publisher/Publisher.h"
#include "fastrtps/subscriber/Subscriber.h"
#include "cyber/base/signal.h"
#include "cyber/proto/topology_change.pb.h"
#include "cyber/service_discovery/communication/subscriber_listener.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
using proto::ChangeMsg;
using proto::ChangeType;
using proto::OperateType;
using proto::RoleAttributes;
using proto::RoleType;
/**
* @class Manager
* @brief Base class for management of Topology elements.
* Manager can Join/Leave the Topology, and Listen the topology change
*/
class Manager {
public:
using ChangeSignal = base::Signal<const ChangeMsg&>;
using ChangeFunc = std::function<void(const ChangeMsg&)>;
using ChangeConnection = base::Connection<const ChangeMsg&>;
using RtpsParticipant = eprosima::fastrtps::Participant;
using RtpsPublisherAttr = eprosima::fastrtps::PublisherAttributes;
using RtpsSubscriberAttr = eprosima::fastrtps::SubscriberAttributes;
/**
* @brief Construct a new Manager object
*/
Manager();
/**
* @brief Destroy the Manager object
*/
virtual ~Manager();
/**
* @brief Startup topology discovery
*
* @param participant is used to create rtps Publisher and Subscriber
* @return true if start successfully
* @return false if start fail
*/
bool StartDiscovery(RtpsParticipant* participant);
/**
* @brief Stop topology discovery
*/
void StopDiscovery();
/**
* @brief Shutdown module
*/
virtual void Shutdown();
/**
* @brief Join the topology
*
* @param attr is the attributes that will be sent to other Manager(include
* ourselves)
* @param role is one of RoleType enum
* @return true if Join topology successfully
* @return false if Join topology failed
*/
bool Join(const RoleAttributes& attr, RoleType role,
bool need_publish = true);
/**
* @brief Leave the topology
*
* @param attr is the attributes that will be sent to other Manager(include
* ourselves)
* @param role if one of RoleType enum.
* @return true if Leave topology successfully
* @return false if Leave topology failed
*/
bool Leave(const RoleAttributes& attr, RoleType role);
/**
* @brief Add topology change listener, when topology changed, func will be
* called.
*
* @param func the callback function
* @return ChangeConnection Store it to use when you want to stop listening.
*/
ChangeConnection AddChangeListener(const ChangeFunc& func);
/**
* @brief Remove our listener for topology change.
*
* @param conn is the return value of `AddChangeListener`
*/
void RemoveChangeListener(const ChangeConnection& conn);
/**
* @brief Called when a process' topology manager instance leave
*
* @param host_name is the process's host's name
* @param process_id is the process' id
*/
virtual void OnTopoModuleLeave(const std::string& host_name,
int process_id) = 0;
protected:
bool CreatePublisher(RtpsParticipant* participant);
bool CreateSubscriber(RtpsParticipant* participant);
virtual bool Check(const RoleAttributes& attr) = 0;
virtual void Dispose(const ChangeMsg& msg) = 0;
virtual bool NeedPublish(const ChangeMsg& msg) const;
void Convert(const RoleAttributes& attr, RoleType role, OperateType opt,
ChangeMsg* msg);
void Notify(const ChangeMsg& msg);
bool Publish(const ChangeMsg& msg);
void OnRemoteChange(const std::string& msg_str);
bool IsFromSameProcess(const ChangeMsg& msg);
std::atomic<bool> is_shutdown_;
std::atomic<bool> is_discovery_started_;
int allowed_role_;
ChangeType change_type_;
std::string host_name_;
int process_id_;
std::string channel_name_;
eprosima::fastrtps::Publisher* publisher_;
std::mutex lock_;
eprosima::fastrtps::Subscriber* subscriber_;
SubscriberListener* listener_;
ChangeSignal signal_;
};
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_DISCOVERY_SPECIFIC_MANAGER_MANAGER_H_
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/specific_manager/node_manager.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_DISCOVERY_SPECIFIC_MANAGER_NODE_MANAGER_H_
#define CYBER_SERVICE_DISCOVERY_SPECIFIC_MANAGER_NODE_MANAGER_H_
#include <memory>
#include <string>
#include <vector>
#include "cyber/service_discovery/container/single_value_warehouse.h"
#include "cyber/service_discovery/role/role.h"
#include "cyber/service_discovery/specific_manager/manager.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class TopologyManager;
/**
* @class NodeManager
* @brief Topology Manager of Node related
*/
class NodeManager : public Manager {
friend class TopologyManager;
public:
using RoleAttrVec = std::vector<RoleAttributes>;
using NodeWarehouse = SingleValueWarehouse;
/**
* @brief Construct a new Node Manager object
*/
NodeManager();
/**
* @brief Destroy the Node Manager object
*/
virtual ~NodeManager();
/**
* @brief Checkout whether we have `node_name` in topology
*
* @param node_name Node's name we want to inquire
* @return true if this node found
* @return false if this node not exits
*/
bool HasNode(const std::string& node_name);
/**
* @brief Get the Nodes object
*
* @param nodes result RoleAttr vector
*/
void GetNodes(RoleAttrVec* nodes);
private:
bool Check(const RoleAttributes& attr) override;
void Dispose(const ChangeMsg& msg) override;
void OnTopoModuleLeave(const std::string& host_name, int process_id) override;
void DisposeJoin(const ChangeMsg& msg);
void DisposeLeave(const ChangeMsg& msg);
NodeWarehouse nodes_;
};
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_DISCOVERY_SPECIFIC_MANAGER_NODE_MANAGER_H_
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/specific_manager/service_manager_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/specific_manager/service_manager.h"
#include <memory>
#include <vector>
#include "gtest/gtest.h"
#include "cyber/common/global_data.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class ServiceManagerTest : public ::testing::Test {
protected:
ServiceManagerTest() {
service_manager_ = std::make_shared<ServiceManager>();
}
virtual ~ServiceManagerTest() { service_manager_->Shutdown(); }
virtual void SetUp() {}
virtual void TearDown() {}
std::shared_ptr<ServiceManager> service_manager_;
};
TEST_F(ServiceManagerTest, server_operation) {
// join
RoleAttributes role_attr;
EXPECT_FALSE(service_manager_->Join(role_attr, RoleType::ROLE_SERVER));
EXPECT_FALSE(service_manager_->Join(role_attr, RoleType::ROLE_NODE));
role_attr.set_host_name(common::GlobalData::Instance()->HostName());
role_attr.set_process_id(common::GlobalData::Instance()->ProcessId());
role_attr.set_node_name("node");
uint64_t node_id = common::GlobalData::RegisterNode("node");
role_attr.set_node_id(node_id);
role_attr.set_service_name("service");
uint64_t service_id = common::GlobalData::RegisterService("service");
role_attr.set_service_id(service_id);
EXPECT_FALSE(service_manager_->Join(role_attr, RoleType::ROLE_SERVER));
EXPECT_FALSE(service_manager_->Join(role_attr, RoleType::ROLE_NODE));
EXPECT_TRUE(service_manager_->HasService("service"));
EXPECT_FALSE(service_manager_->HasService("client"));
// repeated call
EXPECT_FALSE(service_manager_->Join(role_attr, RoleType::ROLE_SERVER));
// get servers
std::vector<RoleAttributes> servers;
EXPECT_TRUE(servers.empty());
service_manager_->GetServers(&servers);
EXPECT_EQ(servers.size(), 1);
// leave
EXPECT_FALSE(service_manager_->Leave(role_attr, RoleType::ROLE_SERVER));
EXPECT_FALSE(service_manager_->HasService("service"));
servers.clear();
EXPECT_TRUE(servers.empty());
service_manager_->GetServers(&servers);
EXPECT_TRUE(servers.empty());
}
TEST_F(ServiceManagerTest, client_operation) {
// join
RoleAttributes role_attr;
role_attr.set_host_name(common::GlobalData::Instance()->HostName());
role_attr.set_process_id(common::GlobalData::Instance()->ProcessId());
role_attr.set_node_name("node");
uint64_t node_id = common::GlobalData::RegisterNode("node");
role_attr.set_node_id(node_id);
role_attr.set_service_name("service");
uint64_t service_id = common::GlobalData::RegisterService("service");
role_attr.set_service_id(service_id);
EXPECT_FALSE(service_manager_->Join(role_attr, RoleType::ROLE_CLIENT));
// repeated call
EXPECT_FALSE(service_manager_->Join(role_attr, RoleType::ROLE_CLIENT));
// get clients
std::vector<RoleAttributes> clients;
EXPECT_TRUE(clients.empty());
service_manager_->GetClients("service", &clients);
EXPECT_EQ(clients.size(), 2);
// leave
EXPECT_FALSE(service_manager_->Leave(role_attr, RoleType::ROLE_CLIENT));
clients.clear();
EXPECT_TRUE(clients.empty());
service_manager_->GetClients("service", &clients);
EXPECT_TRUE(clients.empty());
}
TEST_F(ServiceManagerTest, topo_module_leave) {
RoleAttributes role_attr;
role_attr.set_host_name(common::GlobalData::Instance()->HostName());
role_attr.set_process_id(common::GlobalData::Instance()->ProcessId());
role_attr.set_node_name("node");
uint64_t node_id = common::GlobalData::RegisterNode("node");
role_attr.set_node_id(node_id);
role_attr.set_service_name("service");
uint64_t service_id = common::GlobalData::RegisterService("service");
role_attr.set_service_id(service_id);
EXPECT_FALSE(service_manager_->Join(role_attr, RoleType::ROLE_SERVER));
EXPECT_FALSE(service_manager_->Join(role_attr, RoleType::ROLE_CLIENT));
EXPECT_TRUE(service_manager_->HasService("service"));
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/specific_manager/service_manager.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/specific_manager/service_manager.h"
#include "cyber/common/global_data.h"
#include "cyber/common/log.h"
#include "cyber/common/util.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
ServiceManager::ServiceManager() {
allowed_role_ |= 1 << RoleType::ROLE_SERVER;
allowed_role_ |= 1 << RoleType::ROLE_CLIENT;
change_type_ = ChangeType::CHANGE_SERVICE;
channel_name_ = "service_change_broadcast";
}
ServiceManager::~ServiceManager() {}
bool ServiceManager::HasService(const std::string& service_name) {
uint64_t key = common::Hash(service_name);
return servers_.Search(key);
}
void ServiceManager::GetServers(RoleAttrVec* servers) {
RETURN_IF_NULL(servers);
servers_.GetAllRoles(servers);
}
void ServiceManager::GetClients(const std::string& service_name,
RoleAttrVec* clients) {
RETURN_IF_NULL(clients);
uint64_t key = common::Hash(service_name);
clients_.Search(key, clients);
}
bool ServiceManager::Check(const RoleAttributes& attr) {
RETURN_VAL_IF(!attr.has_service_name(), false);
RETURN_VAL_IF(!attr.has_service_id(), false);
return true;
}
void ServiceManager::Dispose(const ChangeMsg& msg) {
if (msg.operate_type() == OperateType::OPT_JOIN) {
DisposeJoin(msg);
} else {
DisposeLeave(msg);
}
Notify(msg);
}
void ServiceManager::OnTopoModuleLeave(const std::string& host_name,
int process_id) {
RETURN_IF(!is_discovery_started_.load());
RoleAttributes attr;
attr.set_host_name(host_name);
attr.set_process_id(process_id);
std::vector<RolePtr> servers_to_remove;
servers_.Search(attr, &servers_to_remove);
for (auto& server : servers_to_remove) {
servers_.Remove(server->attributes().service_id());
}
std::vector<RolePtr> clients_to_remove;
clients_.Search(attr, &clients_to_remove);
for (auto& client : clients_to_remove) {
clients_.Remove(client->attributes().service_id(), client);
}
ChangeMsg msg;
for (auto& server : servers_to_remove) {
Convert(server->attributes(), RoleType::ROLE_SERVER, OperateType::OPT_LEAVE,
&msg);
Notify(msg);
}
for (auto& client : clients_to_remove) {
Convert(client->attributes(), RoleType::ROLE_CLIENT, OperateType::OPT_LEAVE,
&msg);
Notify(msg);
}
}
void ServiceManager::DisposeJoin(const ChangeMsg& msg) {
if (msg.role_type() == RoleType::ROLE_SERVER) {
auto role = std::make_shared<RoleServer>(msg.role_attr());
servers_.Add(role->attributes().service_id(), role);
} else {
auto role = std::make_shared<RoleClient>(msg.role_attr());
clients_.Add(role->attributes().service_id(), role);
}
}
void ServiceManager::DisposeLeave(const ChangeMsg& msg) {
if (msg.role_type() == RoleType::ROLE_SERVER) {
auto role = std::make_shared<RoleServer>(msg.role_attr());
servers_.Remove(role->attributes().service_id());
} else {
auto role = std::make_shared<RoleClient>(msg.role_attr());
clients_.Remove(role->attributes().service_id(), role);
}
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/specific_manager/node_manager_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/specific_manager/node_manager.h"
#include <memory>
#include <vector>
#include "gtest/gtest.h"
#include "cyber/common/global_data.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class NodeManagerTest : public ::testing::Test {
protected:
NodeManagerTest() { node_manager_ = std::make_shared<NodeManager>(); }
virtual ~NodeManagerTest() { node_manager_->Shutdown(); }
virtual void SetUp() {}
virtual void TearDown() {}
std::shared_ptr<NodeManager> node_manager_;
};
TEST_F(NodeManagerTest, node_change) {
EXPECT_FALSE(node_manager_->HasNode("node"));
// node join
RoleAttributes role_attr;
EXPECT_FALSE(node_manager_->Join(role_attr, RoleType::ROLE_WRITER));
EXPECT_FALSE(node_manager_->Join(role_attr, RoleType::ROLE_NODE));
role_attr.set_host_name(common::GlobalData::Instance()->HostName());
role_attr.set_process_id(common::GlobalData::Instance()->ProcessId());
role_attr.set_node_name("node");
uint64_t node_id = common::GlobalData::RegisterNode("node");
role_attr.set_node_id(node_id);
EXPECT_FALSE(node_manager_->Join(role_attr, RoleType::ROLE_WRITER));
EXPECT_FALSE(node_manager_->Join(role_attr, RoleType::ROLE_NODE));
EXPECT_TRUE(node_manager_->HasNode("node"));
// node leave
EXPECT_FALSE(node_manager_->Leave(role_attr, RoleType::ROLE_WRITER));
EXPECT_FALSE(node_manager_->Leave(role_attr, RoleType::ROLE_NODE));
EXPECT_FALSE(node_manager_->HasNode("node"));
}
TEST_F(NodeManagerTest, topo_module_leave) {
RoleAttributes role_attr;
role_attr.set_host_name(common::GlobalData::Instance()->HostName());
role_attr.set_process_id(common::GlobalData::Instance()->ProcessId());
role_attr.set_node_name("node");
uint64_t node_id = common::GlobalData::RegisterNode("node");
role_attr.set_node_id(node_id);
EXPECT_FALSE(node_manager_->Join(role_attr, RoleType::ROLE_NODE));
EXPECT_TRUE(node_manager_->HasNode("node"));
}
TEST_F(NodeManagerTest, add_and_remove_change_listener) {
bool recv_flag = false;
auto conn = node_manager_->AddChangeListener(
[&recv_flag](const ChangeMsg& msg) { recv_flag = true; });
RoleAttributes role_attr;
role_attr.set_host_name("caros");
role_attr.set_process_id(1024);
role_attr.set_node_name("node");
uint64_t node_id = common::GlobalData::RegisterNode("node");
role_attr.set_node_id(node_id);
EXPECT_FALSE(node_manager_->Join(role_attr, RoleType::ROLE_NODE));
EXPECT_TRUE(recv_flag);
node_manager_->RemoveChangeListener(conn);
recv_flag = false;
EXPECT_FALSE(node_manager_->Leave(role_attr, RoleType::ROLE_NODE));
EXPECT_FALSE(recv_flag);
}
TEST_F(NodeManagerTest, has_node) {
RoleAttributes role_attr;
role_attr.set_host_name("caros");
role_attr.set_process_id(1024);
role_attr.set_node_name("node");
uint64_t node_id = common::GlobalData::RegisterNode("node");
role_attr.set_node_id(node_id);
EXPECT_FALSE(node_manager_->Join(role_attr, RoleType::ROLE_NODE));
EXPECT_TRUE(node_manager_->HasNode("node"));
EXPECT_FALSE(node_manager_->HasNode("node11"));
}
TEST_F(NodeManagerTest, get_nodes) {
RoleAttributes role_attr;
role_attr.set_host_name("caros");
role_attr.set_process_id(1024);
role_attr.set_node_name("node_1");
uint64_t node_id = common::GlobalData::RegisterNode("node_1");
role_attr.set_node_id(node_id);
EXPECT_FALSE(node_manager_->Join(role_attr, RoleType::ROLE_NODE));
std::vector<RoleAttributes> attr_nodes;
node_manager_->GetNodes(&attr_nodes);
EXPECT_EQ(attr_nodes.size(), 1);
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/specific_manager/service_manager.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_DISCOVERY_SPECIFIC_MANAGER_SERVICE_MANAGER_H_
#define CYBER_SERVICE_DISCOVERY_SPECIFIC_MANAGER_SERVICE_MANAGER_H_
#include <memory>
#include <string>
#include <vector>
#include "cyber/service_discovery/container/multi_value_warehouse.h"
#include "cyber/service_discovery/container/single_value_warehouse.h"
#include "cyber/service_discovery/role/role.h"
#include "cyber/service_discovery/specific_manager/manager.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class TopologyManager;
/**
* @class ServiceManager
* @brief Topology Manager of Service related
*/
class ServiceManager : public Manager {
friend class TopologyManager;
public:
using RoleAttrVec = std::vector<RoleAttributes>;
using ServerWarehouse = SingleValueWarehouse;
using ClientWarehouse = MultiValueWarehouse;
/**
* @brief Construct a new Service Manager object
*/
ServiceManager();
/**
* @brief Destroy the Service Manager object
*/
virtual ~ServiceManager();
/**
* @brief Inquire whether `service_name` exists in topology
*
* @param service_name the name we inquire
* @return true if service exists
* @return false if service not exists
*/
bool HasService(const std::string& service_name);
/**
* @brief Get the All Server in the topology
*
* @param servers result RoleAttr vector
*/
void GetServers(RoleAttrVec* servers);
/**
* @brief Get the Clients object that subscribes `service_name`
*
* @param service_name Name of service you want to get
* @param clients result vector
*/
void GetClients(const std::string& service_name, RoleAttrVec* clients);
private:
bool Check(const RoleAttributes& attr) override;
void Dispose(const ChangeMsg& msg) override;
void OnTopoModuleLeave(const std::string& host_name, int process_id) override;
void DisposeJoin(const ChangeMsg& msg);
void DisposeLeave(const ChangeMsg& msg);
ServerWarehouse servers_;
ClientWarehouse clients_;
};
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_DISCOVERY_SPECIFIC_MANAGER_SERVICE_MANAGER_H_
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/container/graph_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/container/graph.h"
#include <string>
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
TEST(GraphTest, vertice) {
Vertice a;
EXPECT_TRUE(a.IsDummy());
Vertice b(a);
EXPECT_TRUE(b.IsDummy());
EXPECT_EQ(b, a);
Vertice c = a;
EXPECT_TRUE(c.IsDummy());
EXPECT_EQ(c.GetKey(), a.GetKey());
a = a;
Vertice d("d");
EXPECT_FALSE(d.IsDummy());
EXPECT_NE(d, a);
EXPECT_NE(d.GetKey(), a.GetKey());
EXPECT_EQ(d.value(), "d");
}
TEST(GraphTest, edge) {
Edge a;
EXPECT_FALSE(a.IsValid());
Edge b(a);
EXPECT_FALSE(b.IsValid());
EXPECT_EQ(b, a);
EXPECT_EQ(b.GetKey(), a.GetKey());
Edge c = a;
EXPECT_FALSE(c.IsValid());
EXPECT_EQ(c, a);
EXPECT_EQ(c.GetKey(), a.GetKey());
a = a;
Edge d;
d = c;
EXPECT_FALSE(d.IsValid());
EXPECT_EQ(d, c);
EXPECT_EQ(d.GetKey(), c.GetKey());
const std::string value = "value";
a.set_value(value);
EXPECT_EQ(a.value(), value);
EXPECT_FALSE(a == b);
EXPECT_FALSE(a.IsValid());
b.set_value(value);
EXPECT_EQ(a, b);
Vertice src("src");
Vertice dst("dst");
a.set_src(src);
b.set_dst(dst);
EXPECT_EQ(a.src(), src);
EXPECT_EQ(b.dst(), dst);
EXPECT_FALSE(a == b);
EXPECT_TRUE(a.IsValid());
EXPECT_TRUE(b.IsValid());
a.set_dst(dst);
b.set_src(src);
EXPECT_EQ(a, b);
EXPECT_EQ(a.GetKey(), "value_dst");
Edge e(src, dst, value);
EXPECT_EQ(e, a);
}
TEST(GraphTest, graph) {
Graph g;
EXPECT_EQ(g.GetNumOfEdge(), 0);
Vertice dummy;
Vertice a("a");
Vertice b("b");
Edge ab;
g.Insert(ab);
EXPECT_EQ(g.GetNumOfEdge(), 0);
ab.set_src(a);
ab.set_dst(b);
ab.set_value("ab");
g.Insert(ab);
EXPECT_EQ(g.GetNumOfEdge(), 1);
// repeated insert
g.Insert(ab);
EXPECT_EQ(g.GetNumOfEdge(), 1);
Vertice c("c");
Vertice d("d");
Edge cd(c, d, "cd");
g.Insert(cd);
EXPECT_EQ(g.GetNumOfEdge(), 2);
Vertice e("e");
Edge ce(c, e, "ce");
g.Insert(ce);
EXPECT_EQ(g.GetNumOfEdge(), 3);
Edge ac;
ac.set_src(a);
ac.set_dst(dummy);
ac.set_value("ac");
g.Insert(ac);
EXPECT_EQ(g.GetNumOfEdge(), 3);
ac.set_src(dummy);
ac.set_dst(c);
g.Insert(ac);
EXPECT_EQ(g.GetNumOfEdge(), 4);
Edge be;
be.set_src(dummy);
be.set_dst(e);
be.set_value("be");
g.Insert(be);
EXPECT_EQ(g.GetNumOfEdge(), 4);
be.set_dst(dummy);
be.set_src(b);
g.Insert(be);
EXPECT_EQ(g.GetNumOfEdge(), 5);
EXPECT_EQ(g.GetDirectionOf(a, b), UPSTREAM);
EXPECT_EQ(g.GetDirectionOf(b, a), DOWNSTREAM);
EXPECT_EQ(g.GetDirectionOf(a, c), UPSTREAM);
EXPECT_EQ(g.GetDirectionOf(c, a), DOWNSTREAM);
EXPECT_EQ(g.GetDirectionOf(b, e), UPSTREAM);
EXPECT_EQ(g.GetDirectionOf(e, b), DOWNSTREAM);
EXPECT_EQ(g.GetDirectionOf(c, d), UPSTREAM);
EXPECT_EQ(g.GetDirectionOf(d, c), DOWNSTREAM);
EXPECT_EQ(g.GetDirectionOf(c, e), UPSTREAM);
EXPECT_EQ(g.GetDirectionOf(e, c), DOWNSTREAM);
EXPECT_EQ(g.GetDirectionOf(a, e), UPSTREAM);
EXPECT_EQ(g.GetDirectionOf(e, a), DOWNSTREAM);
EXPECT_EQ(g.GetDirectionOf(a, d), UPSTREAM);
EXPECT_EQ(g.GetDirectionOf(d, a), DOWNSTREAM);
EXPECT_EQ(g.GetDirectionOf(b, d), UNREACHABLE);
EXPECT_EQ(g.GetDirectionOf(d, b), UNREACHABLE);
EXPECT_EQ(g.GetDirectionOf(d, e), UNREACHABLE);
EXPECT_EQ(g.GetDirectionOf(e, d), UNREACHABLE);
EXPECT_EQ(g.GetDirectionOf(dummy, dummy), UNREACHABLE);
EXPECT_EQ(g.GetDirectionOf(a, dummy), UNREACHABLE);
EXPECT_EQ(g.GetDirectionOf(dummy, a), UNREACHABLE);
Vertice f("f");
EXPECT_EQ(g.GetDirectionOf(a, f), UNREACHABLE);
EXPECT_EQ(g.GetDirectionOf(f, a), UNREACHABLE);
g.Delete(be);
EXPECT_EQ(g.GetDirectionOf(b, e), UNREACHABLE);
EXPECT_EQ(g.GetDirectionOf(e, b), UNREACHABLE);
EXPECT_EQ(g.GetNumOfEdge(), 4);
g.Delete(be);
g.Delete(ac);
EXPECT_EQ(g.GetNumOfEdge(), 3);
EXPECT_EQ(g.GetDirectionOf(a, c), UNREACHABLE);
EXPECT_EQ(g.GetDirectionOf(d, a), UNREACHABLE);
g.Delete(cd);
EXPECT_EQ(g.GetNumOfEdge(), 2);
EXPECT_EQ(g.GetDirectionOf(c, d), UNREACHABLE);
EXPECT_EQ(g.GetDirectionOf(d, c), UNREACHABLE);
g.Delete(ab);
EXPECT_EQ(g.GetNumOfEdge(), 1);
g.Delete(ce);
EXPECT_EQ(g.GetNumOfEdge(), 0);
Vertice q("q");
Edge qa;
g.Delete(qa);
qa.set_src(q);
qa.set_dst(a);
qa.set_value("qa");
g.Delete(qa);
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/container/single_value_warehouse.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/container/single_value_warehouse.h"
#include "cyber/common/log.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
using base::AtomicRWLock;
using base::ReadLockGuard;
using base::WriteLockGuard;
using proto::RoleAttributes;
bool SingleValueWarehouse::Add(uint64_t key, const RolePtr& role,
bool ignore_if_exist) {
WriteLockGuard<AtomicRWLock> lock(rw_lock_);
if (!ignore_if_exist) {
if (roles_.find(key) != roles_.end()) {
return false;
}
}
roles_[key] = role;
return true;
}
void SingleValueWarehouse::Clear() {
WriteLockGuard<AtomicRWLock> lock(rw_lock_);
roles_.clear();
}
std::size_t SingleValueWarehouse::Size() {
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
return roles_.size();
}
void SingleValueWarehouse::Remove(uint64_t key) {
WriteLockGuard<AtomicRWLock> lock(rw_lock_);
roles_.erase(key);
}
void SingleValueWarehouse::Remove(uint64_t key, const RolePtr& role) {
WriteLockGuard<AtomicRWLock> lock(rw_lock_);
auto search = roles_.find(key);
if (search == roles_.end()) {
return;
}
if (!search->second->Match(role->attributes())) {
return;
}
roles_.erase(search);
}
void SingleValueWarehouse::Remove(const RoleAttributes& target_attr) {
WriteLockGuard<AtomicRWLock> lock(rw_lock_);
for (auto it = roles_.begin(); it != roles_.end();) {
auto curr_role = it->second;
if (curr_role->Match(target_attr)) {
it = roles_.erase(it);
} else {
++it;
}
}
}
bool SingleValueWarehouse::Search(uint64_t key) {
RolePtr role;
return Search(key, &role);
}
bool SingleValueWarehouse::Search(uint64_t key, RolePtr* first_matched_role) {
RETURN_VAL_IF_NULL(first_matched_role, false);
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
auto search = roles_.find(key);
if (search == roles_.end()) {
return false;
}
*first_matched_role = search->second;
return true;
}
bool SingleValueWarehouse::Search(uint64_t key,
RoleAttributes* first_matched_role_attr) {
RETURN_VAL_IF_NULL(first_matched_role_attr, false);
RolePtr role;
if (!Search(key, &role)) {
return false;
}
first_matched_role_attr->CopyFrom(role->attributes());
return true;
}
bool SingleValueWarehouse::Search(uint64_t key,
std::vector<RolePtr>* matched_roles) {
RETURN_VAL_IF_NULL(matched_roles, false);
RolePtr role;
if (!Search(key, &role)) {
return false;
}
matched_roles->emplace_back(role);
return true;
}
bool SingleValueWarehouse::Search(
uint64_t key, std::vector<RoleAttributes>* matched_roles_attr) {
RETURN_VAL_IF_NULL(matched_roles_attr, false);
RolePtr role;
if (!Search(key, &role)) {
return false;
}
matched_roles_attr->emplace_back(role->attributes());
return true;
}
bool SingleValueWarehouse::Search(const RoleAttributes& target_attr) {
RolePtr role;
return Search(target_attr, &role);
}
bool SingleValueWarehouse::Search(const RoleAttributes& target_attr,
RolePtr* first_matched_role) {
RETURN_VAL_IF_NULL(first_matched_role, false);
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
for (auto& item : roles_) {
if (item.second->Match(target_attr)) {
*first_matched_role = item.second;
return true;
}
}
return false;
}
bool SingleValueWarehouse::Search(const RoleAttributes& target_attr,
RoleAttributes* first_matched_role_attr) {
RETURN_VAL_IF_NULL(first_matched_role_attr, false);
RolePtr role;
if (!Search(target_attr, &role)) {
return false;
}
first_matched_role_attr->CopyFrom(role->attributes());
return true;
}
bool SingleValueWarehouse::Search(const RoleAttributes& target_attr,
std::vector<RolePtr>* matched_roles) {
RETURN_VAL_IF_NULL(matched_roles, false);
bool find = false;
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
for (auto& item : roles_) {
if (item.second->Match(target_attr)) {
matched_roles->emplace_back(item.second);
find = true;
}
}
return find;
}
bool SingleValueWarehouse::Search(
const RoleAttributes& target_attr,
std::vector<RoleAttributes>* matched_roles_attr) {
RETURN_VAL_IF_NULL(matched_roles_attr, false);
bool find = false;
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
for (auto& item : roles_) {
if (item.second->Match(target_attr)) {
matched_roles_attr->emplace_back(item.second->attributes());
find = true;
}
}
return find;
}
void SingleValueWarehouse::GetAllRoles(std::vector<RolePtr>* roles) {
RETURN_IF_NULL(roles);
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
for (auto& item : roles_) {
roles->emplace_back(item.second);
}
}
void SingleValueWarehouse::GetAllRoles(
std::vector<RoleAttributes>* roles_attr) {
RETURN_IF_NULL(roles_attr);
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
for (auto& item : roles_) {
roles_attr->emplace_back(item.second->attributes());
}
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/container/single_value_warehouse_test.cc
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/container/single_value_warehouse.h"
#include <utility>
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
using proto::RoleAttributes;
TEST(SingleValueWarehouseTest, test1) {
{ SingleValueWarehouse sh; }
{
SingleValueWarehouse sh;
EXPECT_EQ(sh.Size(), 0);
RoleAttributes attr;
attr.set_host_name("caros");
attr.set_process_id(12345);
int i = 0, id = 0;
{
attr.set_node_id(i);
auto role = std::make_shared<RoleBase>();
role->set_attributes(attr);
sh.Add(id++, role);
role = std::make_shared<RoleBase>();
role->set_attributes(attr);
sh.Add(id++, role);
role = std::make_shared<RoleBase>();
role->set_attributes(attr);
sh.Add(id++, role);
}
{
auto role = std::make_shared<RoleBase>();
attr.set_node_id(i++);
role->set_attributes(attr);
sh.Add(id++, role);
}
{
auto role = std::make_shared<RoleBase>();
attr.set_node_id(i);
role->set_attributes(attr);
sh.Add(id++, role);
}
{
attr.set_node_id(i++);
auto role = std::make_shared<RoleWriter>();
role->set_attributes(attr);
role->set_timestamp_ns(54321);
sh.Add(id++, role);
role = std::make_shared<RoleWriter>();
role->set_attributes(attr);
role->set_timestamp_ns(54321);
sh.Add(id++, role);
}
{
auto role = std::make_shared<RoleBase>();
attr.set_node_id(i);
role->set_attributes(attr);
sh.Add(id++, role);
}
{
auto role = std::make_shared<RoleWriter>();
attr.set_node_id(i);
role->set_attributes(attr);
role->set_timestamp_ns(54321);
sh.Add(id++, role);
}
EXPECT_EQ(sh.Size(), 9);
std::vector<RoleAttributes> roles_attr;
std::vector<RolePtr> roles;
sh.GetAllRoles(&roles_attr);
sh.GetAllRoles(&roles);
EXPECT_EQ(roles.size(), roles_attr.size());
EXPECT_EQ(roles.size(), sh.Size());
roles.clear();
roles_attr.clear();
attr.set_node_id(0);
EXPECT_TRUE(sh.Search(attr, &roles_attr));
EXPECT_TRUE(sh.Search(attr, &roles));
EXPECT_EQ(roles.size(), roles_attr.size());
EXPECT_EQ(roles.size(), 4);
RolePtr role;
RoleAttributes rattr;
EXPECT_TRUE(sh.Search(attr, &rattr));
EXPECT_TRUE(sh.Search(attr, &role));
EXPECT_TRUE(sh.Search(attr));
roles_attr.clear();
roles.clear();
EXPECT_TRUE(sh.Search(5, &roles_attr));
EXPECT_TRUE(sh.Search(5, &roles));
EXPECT_EQ(roles.size(), roles_attr.size());
EXPECT_EQ(roles.size(), 1);
EXPECT_TRUE(sh.Search(5, &rattr));
EXPECT_TRUE(sh.Search(5, &role));
EXPECT_TRUE(sh.Search(5));
roles_attr.clear();
roles.clear();
attr.set_node_id(i + 10);
EXPECT_FALSE(sh.Search(attr, &roles_attr));
EXPECT_FALSE(sh.Search(attr, &roles));
EXPECT_EQ(roles.size(), roles_attr.size());
EXPECT_EQ(roles.size(), 0);
EXPECT_FALSE(sh.Search(attr, &rattr));
EXPECT_FALSE(sh.Search(attr, &role));
EXPECT_FALSE(sh.Search(attr));
roles_attr.clear();
roles.clear();
EXPECT_FALSE(sh.Search(i + 10, &roles_attr));
EXPECT_FALSE(sh.Search(i + 10, &roles));
EXPECT_EQ(roles.size(), roles_attr.size());
EXPECT_EQ(roles.size(), 0);
EXPECT_FALSE(sh.Search(i + 10, &rattr));
EXPECT_FALSE(sh.Search(i + 10, &role));
EXPECT_FALSE(sh.Search(i + 10));
attr.set_node_id(0);
sh.Remove(attr);
EXPECT_EQ(sh.Size(), 5);
attr.set_node_id(i + 10);
sh.Remove(attr);
EXPECT_EQ(sh.Size(), 5);
EXPECT_TRUE(sh.Search(5, &role));
sh.Remove(i + 10, role);
EXPECT_EQ(sh.Size(), 5);
sh.Remove(8, role);
EXPECT_EQ(sh.Size(), 5);
sh.Remove(6, role);
EXPECT_EQ(sh.Size(), 4);
sh.Remove(5, role);
EXPECT_EQ(sh.Size(), 3);
sh.Remove(6);
EXPECT_EQ(sh.Size(), 3);
sh.Remove(8);
EXPECT_EQ(sh.Size(), 2);
sh.Clear();
EXPECT_EQ(sh.Size(), 0);
}
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/container/warehouse_base.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_DISCOVERY_CONTAINER_WAREHOUSE_BASE_H_
#define CYBER_SERVICE_DISCOVERY_CONTAINER_WAREHOUSE_BASE_H_
#include <cstdint>
#include <vector>
#include "cyber/service_discovery/role/role.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class WarehouseBase {
public:
WarehouseBase() {}
virtual ~WarehouseBase() {}
virtual bool Add(uint64_t key, const RolePtr& role, bool ignore_if_exist) = 0;
virtual void Clear() = 0;
virtual std::size_t Size() = 0;
virtual void Remove(uint64_t key) = 0;
virtual void Remove(uint64_t key, const RolePtr& role) = 0;
virtual void Remove(const proto::RoleAttributes& target_attr) = 0;
virtual bool Search(uint64_t key) = 0;
virtual bool Search(uint64_t key, RolePtr* first_matched_role) = 0;
virtual bool Search(uint64_t key,
proto::RoleAttributes* first_matched_role_attr) = 0;
virtual bool Search(uint64_t key, std::vector<RolePtr>* matched_roles) = 0;
virtual bool Search(
uint64_t key, std::vector<proto::RoleAttributes>* matched_roles_attr) = 0;
virtual bool Search(const proto::RoleAttributes& target_attr) = 0;
virtual bool Search(const proto::RoleAttributes& target_attr,
RolePtr* first_matched) = 0;
virtual bool Search(const proto::RoleAttributes& target_attr,
proto::RoleAttributes* first_matched_role_attr) = 0;
virtual bool Search(const proto::RoleAttributes& target_attr,
std::vector<RolePtr>* matched_roles) = 0;
virtual bool Search(
const proto::RoleAttributes& target_attr,
std::vector<proto::RoleAttributes>* matched_roles_attr) = 0;
virtual void GetAllRoles(std::vector<RolePtr>* roles) = 0;
virtual void GetAllRoles(std::vector<proto::RoleAttributes>* roles_attr) = 0;
};
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_DISCOVERY_CONTAINER_WAREHOUSE_BASE_H_
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/container/graph.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_DISCOVERY_CONTAINER_GRAPH_H_
#define CYBER_SERVICE_DISCOVERY_CONTAINER_GRAPH_H_
#include <cstdint>
#include <string>
#include <unordered_map>
#include "cyber/base/atomic_rw_lock.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
/**
* @brief describe the flow direction between nodes
* As the DAG below
* A---->B----->C<-----D
* GetDirectionOf(A, B) is UPSTREAM
* GetDirectionOf(C, A) is DOWNSTREAM
* GetDirectionOf(D, A) is UNREACHABLE
* GetDirectionOf(A, D) is UNREACHABLE
*/
enum FlowDirection {
UNREACHABLE,
UPSTREAM,
DOWNSTREAM,
};
// opt impl of Vertice/Edge/Graph, replace stl with base
class Vertice {
public:
explicit Vertice(const std::string& val = "");
Vertice(const Vertice& other);
virtual ~Vertice();
Vertice& operator=(const Vertice& rhs);
bool operator==(const Vertice& rhs) const;
bool operator!=(const Vertice& rhs) const;
bool IsDummy() const;
const std::string& GetKey() const;
const std::string& value() const { return value_; }
private:
std::string value_;
};
class Edge {
public:
Edge();
Edge(const Edge& other);
Edge(const Vertice& src, const Vertice& dst, const std::string& val);
virtual ~Edge();
Edge& operator=(const Edge& rhs);
bool operator==(const Edge& rhs) const;
bool IsValid() const;
std::string GetKey() const;
const Vertice& src() const { return src_; }
void set_src(const Vertice& v) { src_ = v; }
const Vertice& dst() const { return dst_; }
void set_dst(const Vertice& v) { dst_ = v; }
const std::string& value() const { return value_; }
void set_value(const std::string& val) { value_ = val; }
private:
Vertice src_;
Vertice dst_;
std::string value_;
};
class Graph {
public:
using VerticeSet = std::unordered_map<std::string, Vertice>;
using AdjacencyList = std::unordered_map<std::string, VerticeSet>;
Graph();
virtual ~Graph();
void Insert(const Edge& e);
void Delete(const Edge& e);
uint32_t GetNumOfEdge();
FlowDirection GetDirectionOf(const Vertice& lhs, const Vertice& rhs);
private:
struct RelatedVertices {
RelatedVertices() {}
VerticeSet src;
VerticeSet dst;
};
using EdgeInfo = std::unordered_map<std::string, RelatedVertices>;
void InsertOutgoingEdge(const Edge& e);
void InsertIncomingEdge(const Edge& e);
void InsertCompleteEdge(const Edge& e);
void DeleteOutgoingEdge(const Edge& e);
void DeleteIncomingEdge(const Edge& e);
void DeleteCompleteEdge(const Edge& e);
bool LevelTraverse(const Vertice& start, const Vertice& end);
EdgeInfo edges_;
AdjacencyList list_;
base::AtomicRWLock rw_lock_;
};
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_DISCOVERY_CONTAINER_GRAPH_H_
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/container/graph.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/container/graph.h"
#include <queue>
namespace apollo {
namespace cyber {
namespace service_discovery {
using base::AtomicRWLock;
using base::ReadLockGuard;
using base::WriteLockGuard;
Vertice::Vertice(const std::string& val) : value_(val) {}
Vertice::Vertice(const Vertice& other) { this->value_ = other.value_; }
Vertice::~Vertice() {}
Vertice& Vertice::operator=(const Vertice& rhs) {
if (this != &rhs) {
this->value_ = rhs.value_;
}
return *this;
}
bool Vertice::operator==(const Vertice& rhs) const {
return this->value_ == rhs.value_;
}
bool Vertice::operator!=(const Vertice& rhs) const {
return this->value_ != rhs.value_;
}
bool Vertice::IsDummy() const { return value_.empty(); }
const std::string& Vertice::GetKey() const { return value_; }
Edge::Edge() {}
Edge::Edge(const Edge& other) {
this->src_ = other.src_;
this->dst_ = other.dst_;
this->value_ = other.value_;
}
Edge::Edge(const Vertice& src, const Vertice& dst, const std::string& val)
: src_(src), dst_(dst), value_(val) {}
Edge::~Edge() {}
Edge& Edge::operator=(const Edge& rhs) {
if (this != &rhs) {
this->src_ = rhs.src_;
this->dst_ = rhs.dst_;
this->value_ = rhs.value_;
}
return *this;
}
bool Edge::operator==(const Edge& rhs) const {
return this->src_ == rhs.src_ && this->dst_ == rhs.dst_ &&
this->value_ == rhs.value_;
}
bool Edge::IsValid() const {
if (value_.empty()) {
return false;
}
if (src_.IsDummy() && dst_.IsDummy()) {
return false;
}
return true;
}
std::string Edge::GetKey() const { return value_ + "_" + dst_.GetKey(); }
Graph::Graph() {}
Graph::~Graph() {
edges_.clear();
list_.clear();
}
void Graph::Insert(const Edge& e) {
if (!e.IsValid()) {
return;
}
WriteLockGuard<AtomicRWLock> lock(rw_lock_);
auto& e_v = e.value();
if (edges_.find(e_v) == edges_.end()) {
edges_[e_v] = RelatedVertices();
}
if (!e.src().IsDummy()) {
InsertOutgoingEdge(e);
}
if (!e.dst().IsDummy()) {
InsertIncomingEdge(e);
}
}
void Graph::Delete(const Edge& e) {
if (!e.IsValid()) {
return;
}
WriteLockGuard<AtomicRWLock> lock(rw_lock_);
auto& e_v = e.value();
if (edges_.find(e_v) == edges_.end()) {
return;
}
if (!e.src().IsDummy()) {
DeleteOutgoingEdge(e);
}
if (!e.dst().IsDummy()) {
DeleteIncomingEdge(e);
}
}
uint32_t Graph::GetNumOfEdge() {
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
uint32_t num = 0;
for (auto& item : list_) {
num += static_cast<int>(item.second.size());
}
return num;
}
FlowDirection Graph::GetDirectionOf(const Vertice& lhs, const Vertice& rhs) {
if (lhs.IsDummy() || rhs.IsDummy()) {
return UNREACHABLE;
}
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
if (list_.count(lhs.GetKey()) == 0 || list_.count(rhs.GetKey()) == 0) {
return UNREACHABLE;
}
if (LevelTraverse(lhs, rhs)) {
return UPSTREAM;
}
if (LevelTraverse(rhs, lhs)) {
return DOWNSTREAM;
}
return UNREACHABLE;
}
void Graph::InsertOutgoingEdge(const Edge& e) {
auto& e_v = e.value();
auto& src_v_set = edges_[e_v].src;
auto& src_v = e.src();
auto& v_k = src_v.GetKey();
if (src_v_set.find(v_k) != src_v_set.end()) {
return;
}
src_v_set[v_k] = src_v;
auto& dst_v_set = edges_[e_v].dst;
Edge insert_e;
insert_e.set_src(src_v);
insert_e.set_value(e.value());
for (auto& item : dst_v_set) {
insert_e.set_dst(item.second);
InsertCompleteEdge(insert_e);
}
}
void Graph::InsertIncomingEdge(const Edge& e) {
auto& e_v = e.value();
auto& dst_v_set = edges_[e_v].dst;
auto& dst_v = e.dst();
auto& v_k = dst_v.GetKey();
if (dst_v_set.find(v_k) != dst_v_set.end()) {
return;
}
dst_v_set[v_k] = dst_v;
auto& src_v_set = edges_[e_v].src;
Edge insert_e;
insert_e.set_dst(dst_v);
insert_e.set_value(e.value());
for (auto& item : src_v_set) {
insert_e.set_src(item.second);
InsertCompleteEdge(insert_e);
}
}
void Graph::InsertCompleteEdge(const Edge& e) {
auto& src_v_k = e.src().GetKey();
if (list_.find(src_v_k) == list_.end()) {
list_[src_v_k] = VerticeSet();
}
auto& dst_v_k = e.dst().GetKey();
if (list_.find(dst_v_k) == list_.end()) {
list_[dst_v_k] = VerticeSet();
}
list_[src_v_k][e.GetKey()] = e.dst();
}
void Graph::DeleteOutgoingEdge(const Edge& e) {
auto& e_v = e.value();
auto& src_v_set = edges_[e_v].src;
auto& src_v = e.src();
auto& v_k = src_v.GetKey();
if (src_v_set.find(v_k) == src_v_set.end()) {
return;
}
src_v_set.erase(v_k);
auto& dst_v_set = edges_[e_v].dst;
Edge delete_e;
delete_e.set_src(src_v);
delete_e.set_value(e.value());
for (auto& item : dst_v_set) {
delete_e.set_dst(item.second);
DeleteCompleteEdge(delete_e);
}
}
void Graph::DeleteIncomingEdge(const Edge& e) {
auto& e_v = e.value();
auto& dst_v_set = edges_[e_v].dst;
auto& dst_v = e.dst();
auto& v_k = dst_v.GetKey();
if (dst_v_set.find(v_k) == dst_v_set.end()) {
return;
}
dst_v_set.erase(v_k);
auto& src_v_set = edges_[e_v].src;
Edge delete_e;
delete_e.set_dst(dst_v);
delete_e.set_value(e.value());
for (auto& item : src_v_set) {
delete_e.set_src(item.second);
DeleteCompleteEdge(delete_e);
}
}
void Graph::DeleteCompleteEdge(const Edge& e) {
auto& src_v_k = e.src().GetKey();
list_[src_v_k].erase(e.GetKey());
}
bool Graph::LevelTraverse(const Vertice& start, const Vertice& end) {
std::unordered_map<std::string, bool> visited;
visited[end.GetKey()] = false;
std::queue<Vertice> unvisited;
unvisited.emplace(start);
while (!unvisited.empty()) {
auto curr = unvisited.front();
unvisited.pop();
if (visited[curr.GetKey()]) {
continue;
}
visited[curr.GetKey()] = true;
if (curr == end) {
break;
}
for (auto& item : list_[curr.GetKey()]) {
unvisited.push(item.second);
}
}
return visited[end.GetKey()];
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/container/warehouse_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/container/multi_value_warehouse.h"
#include "cyber/service_discovery/container/single_value_warehouse.h"
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
using proto::RoleAttributes;
class WarehouseTest : public ::testing::Test {
protected:
WarehouseTest() : key_num_(256) {}
virtual ~WarehouseTest() {}
virtual void SetUp() {
FillSingle();
FillMulti();
}
virtual void TearDown() {
single_.Clear();
multi_.Clear();
}
int key_num_;
SingleValueWarehouse single_;
MultiValueWarehouse multi_;
private:
void FillSingle() {
RoleAttributes attr;
attr.set_host_name("caros");
attr.set_process_id(12345);
for (int i = 0; i < key_num_; ++i) {
auto role = std::make_shared<RoleBase>();
attr.set_node_id(i);
role->set_attributes(attr);
single_.Add(i, role);
}
}
void FillMulti() {
RoleAttributes attr;
attr.set_host_name("caros");
attr.set_process_id(12345);
for (int i = 0; i < key_num_; ++i) {
auto role_a = std::make_shared<RoleWriter>();
attr.set_node_id(i);
attr.set_channel_id(i);
attr.set_id(2 * i);
role_a->set_attributes(attr);
multi_.Add(i, role_a);
attr.set_id(2 * i + 1);
auto role_b = std::make_shared<RoleWriter>();
role_b->set_attributes(attr);
multi_.Add(i, role_b);
}
}
};
TEST_F(WarehouseTest, size) {
EXPECT_EQ(single_.Size(), key_num_);
EXPECT_EQ(multi_.Size(), 2 * key_num_);
single_.Clear();
multi_.Clear();
EXPECT_EQ(single_.Size(), 0);
EXPECT_EQ(multi_.Size(), 0);
}
TEST_F(WarehouseTest, add) {
auto role = std::make_shared<RoleBase>();
EXPECT_TRUE(single_.Add(key_num_, role, false));
EXPECT_FALSE(single_.Add(key_num_, role, false));
EXPECT_TRUE(multi_.Add(key_num_, role, false));
EXPECT_FALSE(multi_.Add(key_num_, role, false));
}
TEST_F(WarehouseTest, remove) {
// key
single_.Remove(0);
EXPECT_EQ(single_.Size(), key_num_ - 1);
multi_.Remove(0);
EXPECT_EQ(multi_.Size(), 2 * key_num_ - 2);
// key and role
RoleAttributes attr;
attr.set_host_name("caros");
attr.set_process_id(12345);
attr.set_node_id(0);
auto role = std::make_shared<RoleBase>();
role->set_attributes(attr);
single_.Remove(0, role);
single_.Remove(1, role);
EXPECT_EQ(single_.Size(), key_num_ - 1);
attr.set_node_id(1);
role->set_attributes(attr);
single_.Remove(1, role);
EXPECT_EQ(single_.Size(), key_num_ - 2);
attr.set_channel_id(1);
attr.set_id(2);
role = std::make_shared<RoleWriter>();
role->set_attributes(attr);
multi_.Remove(0, role);
EXPECT_EQ(multi_.Size(), 2 * key_num_ - 2);
multi_.Remove(1, role);
EXPECT_EQ(multi_.Size(), 2 * key_num_ - 3);
attr.set_id(5);
role->set_attributes(attr);
multi_.Remove(1, role);
EXPECT_EQ(multi_.Size(), 2 * key_num_ - 3);
// attr
RoleAttributes target_attr;
target_attr.set_host_name("caros");
target_attr.set_process_id(54321);
single_.Remove(target_attr);
EXPECT_EQ(single_.Size(), key_num_ - 2);
multi_.Remove(target_attr);
EXPECT_EQ(multi_.Size(), 2 * key_num_ - 3);
target_attr.set_process_id(12345);
single_.Remove(target_attr);
EXPECT_EQ(single_.Size(), 0);
multi_.Remove(target_attr);
EXPECT_EQ(multi_.Size(), 0);
}
TEST_F(WarehouseTest, search) {
// key
for (int i = 0; i < key_num_; ++i) {
EXPECT_TRUE(single_.Search(i));
EXPECT_TRUE(multi_.Search(i));
}
// key and role
RolePtr role;
for (int i = 0; i < key_num_; ++i) {
EXPECT_TRUE(single_.Search(i, &role));
EXPECT_TRUE(multi_.Search(i, &role));
}
// key and role attr
RoleAttributes attr;
for (int i = 0; i < key_num_; ++i) {
EXPECT_TRUE(single_.Search(i, &attr));
EXPECT_EQ(attr.node_id(), i);
EXPECT_TRUE(multi_.Search(i, &attr));
EXPECT_EQ(attr.channel_id(), i);
}
// key and role vec
std::vector<RolePtr> role_vec;
for (int i = 0; i < key_num_; ++i) {
EXPECT_TRUE(single_.Search(i, &role_vec));
EXPECT_EQ(role_vec.size(), 1);
role_vec.clear();
EXPECT_TRUE(multi_.Search(i, &role_vec));
EXPECT_EQ(role_vec.size(), 2);
role_vec.clear();
}
// key and role attr vec
std::vector<RoleAttributes> role_attr_vec;
for (int i = 0; i < key_num_; ++i) {
EXPECT_TRUE(single_.Search(i, &role_attr_vec));
EXPECT_EQ(role_attr_vec.size(), 1);
role_attr_vec.clear();
EXPECT_TRUE(multi_.Search(i, &role_attr_vec));
EXPECT_EQ(role_attr_vec.size(), 2);
role_attr_vec.clear();
}
// attr
RoleAttributes target_attr;
for (int i = 0; i < key_num_; ++i) {
target_attr.set_node_id(i);
EXPECT_TRUE(single_.Search(target_attr));
target_attr.set_channel_id(i);
EXPECT_TRUE(multi_.Search(target_attr));
}
// attr and role
for (int i = 0; i < key_num_; ++i) {
target_attr.set_node_id(i);
EXPECT_TRUE(single_.Search(target_attr, &role));
target_attr.set_channel_id(i);
EXPECT_TRUE(multi_.Search(target_attr, &role));
}
// attr and role attr
for (int i = 0; i < key_num_; ++i) {
target_attr.set_node_id(i);
EXPECT_TRUE(single_.Search(target_attr, &attr));
EXPECT_EQ(attr.node_id(), i);
target_attr.set_channel_id(i);
EXPECT_TRUE(multi_.Search(target_attr, &attr));
EXPECT_EQ(attr.channel_id(), i);
}
// attr and role vec
for (int i = 0; i < key_num_; ++i) {
target_attr.set_node_id(i);
EXPECT_TRUE(single_.Search(target_attr, &role_vec));
EXPECT_EQ(role_vec.size(), 1);
role_vec.clear();
target_attr.set_channel_id(i);
EXPECT_TRUE(multi_.Search(target_attr, &role_vec));
EXPECT_EQ(role_vec.size(), 2);
role_vec.clear();
}
// attr and role attr vec
for (int i = 0; i < key_num_; ++i) {
target_attr.set_node_id(i);
EXPECT_TRUE(single_.Search(target_attr, &role_attr_vec));
EXPECT_EQ(role_attr_vec.size(), 1);
role_attr_vec.clear();
target_attr.set_channel_id(i);
EXPECT_TRUE(multi_.Search(target_attr, &role_attr_vec));
EXPECT_EQ(role_attr_vec.size(), 2);
role_attr_vec.clear();
}
}
TEST_F(WarehouseTest, get_all_roles) {
// role vec
std::vector<RolePtr> role_vec;
single_.GetAllRoles(&role_vec);
EXPECT_EQ(role_vec.size(), key_num_);
role_vec.clear();
multi_.GetAllRoles(&role_vec);
EXPECT_EQ(role_vec.size(), 2 * key_num_);
// role attr vec
std::vector<RoleAttributes> role_attr_vec;
single_.GetAllRoles(&role_attr_vec);
EXPECT_EQ(role_attr_vec.size(), key_num_);
role_attr_vec.clear();
multi_.GetAllRoles(&role_attr_vec);
EXPECT_EQ(role_attr_vec.size(), 2 * key_num_);
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/container/multi_value_warehouse.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/container/multi_value_warehouse.h"
#include <algorithm>
#include <utility>
#include "cyber/common/log.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
using base::AtomicRWLock;
using base::ReadLockGuard;
using base::WriteLockGuard;
using proto::RoleAttributes;
bool MultiValueWarehouse::Add(uint64_t key, const RolePtr& role,
bool ignore_if_exist) {
WriteLockGuard<AtomicRWLock> lock(rw_lock_);
if (!ignore_if_exist) {
if (roles_.find(key) != roles_.end()) {
return false;
}
}
std::pair<uint64_t, RolePtr> role_pair(key, role);
roles_.insert(role_pair);
return true;
}
void MultiValueWarehouse::Clear() {
WriteLockGuard<AtomicRWLock> lock(rw_lock_);
roles_.clear();
}
std::size_t MultiValueWarehouse::Size() {
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
return roles_.size();
}
void MultiValueWarehouse::Remove(uint64_t key) {
WriteLockGuard<AtomicRWLock> lock(rw_lock_);
roles_.erase(key);
}
void MultiValueWarehouse::Remove(uint64_t key, const RolePtr& role) {
WriteLockGuard<AtomicRWLock> lock(rw_lock_);
auto range = roles_.equal_range(key);
for (auto it = range.first; it != range.second;) {
if (it->second->Match(role->attributes())) {
it = roles_.erase(it);
} else {
++it;
}
}
}
void MultiValueWarehouse::Remove(const RoleAttributes& target_attr) {
WriteLockGuard<AtomicRWLock> lock(rw_lock_);
for (auto it = roles_.begin(); it != roles_.end();) {
auto curr_role = it->second;
if (curr_role->Match(target_attr)) {
it = roles_.erase(it);
} else {
++it;
}
}
}
bool MultiValueWarehouse::Search(uint64_t key) {
RolePtr role;
return Search(key, &role);
}
bool MultiValueWarehouse::Search(uint64_t key, RolePtr* first_matched_role) {
RETURN_VAL_IF_NULL(first_matched_role, false);
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
auto search = roles_.find(key);
if (search == roles_.end()) {
return false;
}
*first_matched_role = search->second;
return true;
}
bool MultiValueWarehouse::Search(uint64_t key,
RoleAttributes* first_matched_role_attr) {
RETURN_VAL_IF_NULL(first_matched_role_attr, false);
RolePtr role;
if (!Search(key, &role)) {
return false;
}
first_matched_role_attr->CopyFrom(role->attributes());
return true;
}
bool MultiValueWarehouse::Search(uint64_t key,
std::vector<RolePtr>* matched_roles) {
RETURN_VAL_IF_NULL(matched_roles, false);
bool find = false;
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
auto range = roles_.equal_range(key);
for_each(range.first, range.second,
[&matched_roles, &find](RoleMap::value_type& item) {
matched_roles->emplace_back(item.second);
find = true;
});
return find;
}
bool MultiValueWarehouse::Search(
uint64_t key, std::vector<RoleAttributes>* matched_roles_attr) {
RETURN_VAL_IF_NULL(matched_roles_attr, false);
bool find = false;
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
auto range = roles_.equal_range(key);
for_each(range.first, range.second,
[&matched_roles_attr, &find](RoleMap::value_type& item) {
matched_roles_attr->emplace_back(item.second->attributes());
find = true;
});
return find;
}
bool MultiValueWarehouse::Search(const RoleAttributes& target_attr) {
RolePtr role;
return Search(target_attr, &role);
}
bool MultiValueWarehouse::Search(const RoleAttributes& target_attr,
RolePtr* first_matched_role) {
RETURN_VAL_IF_NULL(first_matched_role, false);
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
for (auto& item : roles_) {
if (item.second->Match(target_attr)) {
*first_matched_role = item.second;
return true;
}
}
return false;
}
bool MultiValueWarehouse::Search(const RoleAttributes& target_attr,
RoleAttributes* first_matched_role_attr) {
RETURN_VAL_IF_NULL(first_matched_role_attr, false);
RolePtr role;
if (!Search(target_attr, &role)) {
return false;
}
first_matched_role_attr->CopyFrom(role->attributes());
return true;
}
bool MultiValueWarehouse::Search(const RoleAttributes& target_attr,
std::vector<RolePtr>* matched_roles) {
RETURN_VAL_IF_NULL(matched_roles, false);
bool find = false;
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
for (auto& item : roles_) {
if (item.second->Match(target_attr)) {
matched_roles->emplace_back(item.second);
find = true;
}
}
return find;
}
bool MultiValueWarehouse::Search(
const RoleAttributes& target_attr,
std::vector<RoleAttributes>* matched_roles_attr) {
RETURN_VAL_IF_NULL(matched_roles_attr, false);
bool find = false;
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
for (auto& item : roles_) {
if (item.second->Match(target_attr)) {
matched_roles_attr->emplace_back(item.second->attributes());
find = true;
}
}
return find;
}
void MultiValueWarehouse::GetAllRoles(std::vector<RolePtr>* roles) {
RETURN_IF_NULL(roles);
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
for (auto& item : roles_) {
roles->emplace_back(item.second);
}
}
void MultiValueWarehouse::GetAllRoles(std::vector<RoleAttributes>* roles_attr) {
RETURN_IF_NULL(roles_attr);
ReadLockGuard<AtomicRWLock> lock(rw_lock_);
for (auto& item : roles_) {
roles_attr->emplace_back(item.second->attributes());
}
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/container/multi_value_warehouse.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_DISCOVERY_CONTAINER_MULTI_VALUE_WAREHOUSE_H_
#define CYBER_SERVICE_DISCOVERY_CONTAINER_MULTI_VALUE_WAREHOUSE_H_
#include <cstdint>
#include <unordered_map>
#include <vector>
#include "cyber/base/atomic_rw_lock.h"
#include "cyber/service_discovery/container/warehouse_base.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class MultiValueWarehouse : public WarehouseBase {
public:
using RoleMap = std::unordered_multimap<uint64_t, RolePtr>;
MultiValueWarehouse() {}
virtual ~MultiValueWarehouse() {}
bool Add(uint64_t key, const RolePtr& role,
bool ignore_if_exist = true) override;
void Clear() override;
std::size_t Size() override;
void Remove(uint64_t key) override;
void Remove(uint64_t key, const RolePtr& role) override;
void Remove(const proto::RoleAttributes& target_attr) override;
bool Search(uint64_t key) override;
bool Search(uint64_t key, RolePtr* first_matched_role) override;
bool Search(uint64_t key,
proto::RoleAttributes* first_matched_role_attr) override;
bool Search(uint64_t key, std::vector<RolePtr>* matched_roles) override;
bool Search(uint64_t key,
std::vector<proto::RoleAttributes>* matched_roles_attr) override;
bool Search(const proto::RoleAttributes& target_attr) override;
bool Search(const proto::RoleAttributes& target_attr,
RolePtr* first_matched) override;
bool Search(const proto::RoleAttributes& target_attr,
proto::RoleAttributes* first_matched_role_attr) override;
bool Search(const proto::RoleAttributes& target_attr,
std::vector<RolePtr>* matched_roles) override;
bool Search(const proto::RoleAttributes& target_attr,
std::vector<proto::RoleAttributes>* matched_roles_attr) override;
void GetAllRoles(std::vector<RolePtr>* roles) override;
void GetAllRoles(std::vector<proto::RoleAttributes>* roles_attr) override;
private:
RoleMap roles_;
base::AtomicRWLock rw_lock_;
};
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_DISCOVERY_CONTAINER_MULTI_VALUE_WAREHOUSE_H_
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/container/multi_value_warehouse_test.cc
|
/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/container/multi_value_warehouse.h"
#include <memory>
#include <utility>
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
using proto::RoleAttributes;
TEST(MultiValueWarehouseTest, test1) {
{ MultiValueWarehouse wh; }
{
MultiValueWarehouse wh;
EXPECT_EQ(wh.Size(), 0);
RoleAttributes attr;
attr.set_host_name("caros");
attr.set_process_id(12345);
int index = 0;
{ // 0
attr.set_node_id(index);
attr.set_channel_id(index);
{
attr.set_id(2 * index);
auto rolePtr = std::make_shared<RoleBase>(attr, 54321);
EXPECT_TRUE(wh.Add(index, rolePtr));
rolePtr = std::make_shared<RoleBase>(attr, 54321);
EXPECT_TRUE(wh.Add(index + 1, rolePtr));
rolePtr = std::make_shared<RoleBase>(attr, 54321);
EXPECT_TRUE(wh.Add(index + 2, rolePtr));
rolePtr = std::make_shared<RoleBase>(attr, 54321);
EXPECT_TRUE(wh.Add(index + 3, rolePtr));
}
{
attr.set_id(2 * index + 1);
auto rolePtr = std::make_shared<RoleBase>(attr, 54321);
EXPECT_FALSE(wh.Add(index, rolePtr, false));
}
{
attr.set_id(2 * index + 2);
auto rolePtr = std::make_shared<RoleBase>(attr, 54321);
EXPECT_TRUE(wh.Add(index, rolePtr));
}
{
attr.set_id(2 * index + 3);
auto rolePtr = std::make_shared<RoleBase>(attr, 54321);
EXPECT_TRUE(wh.Add(index++, rolePtr));
}
}
{ // 1
attr.set_node_id(index);
attr.set_channel_id(index);
{
attr.set_id(2 * index);
auto rolePtr = std::make_shared<RoleWriter>();
rolePtr->set_attributes(attr);
EXPECT_TRUE(wh.Add(index, rolePtr));
EXPECT_FALSE(wh.Add(index, rolePtr, false));
}
{
attr.set_id(2 * index + 1);
auto rolePtr = std::make_shared<RoleWriter>();
rolePtr->set_attributes(attr);
EXPECT_TRUE(wh.Add(index++, rolePtr));
}
EXPECT_EQ(wh.Size(), 8);
}
{ // 2
attr.set_node_id(index);
attr.set_channel_id(index);
attr.set_id(2 * index);
auto rolePtr = std::make_shared<RoleWriter>();
rolePtr->set_attributes(attr);
EXPECT_TRUE(wh.Add(index, rolePtr));
attr.set_id(2 * index + 1);
auto rolePtr2 = std::make_shared<RoleWriter>();
rolePtr2->set_attributes(attr);
EXPECT_TRUE(wh.Add(index++, rolePtr2));
EXPECT_EQ(wh.Size(), 10);
}
{ // 3
attr.set_node_id(index);
attr.set_channel_id(index);
{
attr.set_id(2 * index);
auto rolePtr = std::make_shared<RoleWriter>();
rolePtr->set_attributes(attr);
EXPECT_TRUE(wh.Add(index, rolePtr));
}
{
attr.set_id(2 * index + 1);
auto rolePtr = std::make_shared<RoleWriter>();
rolePtr->set_attributes(attr);
EXPECT_TRUE(wh.Add(index, rolePtr));
}
{
attr.set_id(2 * index + 2);
auto rolePtr = std::make_shared<RoleWriter>();
rolePtr->set_attributes(attr);
EXPECT_TRUE(wh.Add(index++, rolePtr));
}
EXPECT_EQ(wh.Size(), 13);
EXPECT_TRUE(wh.Search(attr));
EXPECT_TRUE(wh.Search(3));
std::vector<RolePtr> roles;
wh.GetAllRoles(&roles);
EXPECT_EQ(roles.size(), wh.Size());
std::vector<RoleAttributes> roles_attr;
wh.GetAllRoles(&roles_attr);
EXPECT_EQ(roles.size(), roles_attr.size());
attr.set_node_id(0);
attr.set_channel_id(0);
attr.set_id(0);
roles.clear();
EXPECT_TRUE(wh.Search(attr, &roles));
EXPECT_EQ(roles.size(), 6);
roles_attr.clear();
EXPECT_TRUE(wh.Search(attr, &roles_attr));
EXPECT_EQ(roles_attr.size(), 6);
attr.set_id(100);
roles.clear();
EXPECT_TRUE(wh.Search(attr, &roles));
EXPECT_EQ(roles.size(), 6);
roles_attr.clear();
EXPECT_TRUE(wh.Search(attr, &roles_attr));
EXPECT_EQ(roles_attr.size(), 6);
EXPECT_TRUE(wh.Search(attr));
EXPECT_FALSE(wh.Search(50));
wh.Remove(0);
EXPECT_EQ(wh.Size(), 10);
roles.clear();
EXPECT_TRUE(wh.Search(attr, &roles));
EXPECT_EQ(roles.size(), 3);
roles_attr.clear();
EXPECT_TRUE(wh.Search(attr, &roles_attr));
EXPECT_EQ(roles_attr.size(), 3);
EXPECT_TRUE(wh.Search(attr));
wh.Remove(attr);
EXPECT_EQ(wh.Size(), 7);
roles.clear();
EXPECT_FALSE(wh.Search(attr, &roles));
EXPECT_EQ(roles.size(), 0);
roles_attr.clear();
EXPECT_FALSE(wh.Search(attr, &roles_attr));
EXPECT_EQ(roles_attr.size(), 0);
EXPECT_FALSE(wh.Search(attr));
roles_attr.clear();
EXPECT_TRUE(wh.Search(3, &roles_attr));
EXPECT_EQ(roles_attr.size(), 3);
roles_attr.clear();
EXPECT_FALSE(wh.Search(10, &roles_attr));
EXPECT_EQ(roles_attr.size(), 0);
roles.clear();
EXPECT_TRUE(wh.Search(3, &roles));
EXPECT_EQ(roles.size(), 3);
roles.clear();
EXPECT_FALSE(wh.Search(10, &roles));
EXPECT_EQ(roles.size(), 0);
RolePtr role;
EXPECT_TRUE(wh.Search(2, &role));
EXPECT_TRUE(wh.Search(3, &attr));
EXPECT_FALSE(wh.Search(10, &role));
EXPECT_FALSE(wh.Search(10, &attr));
attr.set_id(0);
wh.Remove(attr);
EXPECT_TRUE(wh.Search(1, &role));
wh.Remove(2, role);
wh.Remove(100);
wh.Remove(3);
wh.Clear();
EXPECT_EQ(wh.Size(), 0);
}
}
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/container/single_value_warehouse.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_DISCOVERY_CONTAINER_SINGLE_VALUE_WAREHOUSE_H_
#define CYBER_SERVICE_DISCOVERY_CONTAINER_SINGLE_VALUE_WAREHOUSE_H_
#include <cstdint>
#include <unordered_map>
#include <vector>
#include "cyber/base/atomic_rw_lock.h"
#include "cyber/service_discovery/container/warehouse_base.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class SingleValueWarehouse : public WarehouseBase {
public:
using RoleMap = std::unordered_map<uint64_t, RolePtr>;
SingleValueWarehouse() {}
virtual ~SingleValueWarehouse() {}
bool Add(uint64_t key, const RolePtr& role,
bool ignore_if_exist = true) override;
void Clear() override;
std::size_t Size() override;
void Remove(uint64_t key) override;
void Remove(uint64_t key, const RolePtr& role) override;
void Remove(const proto::RoleAttributes& target_attr) override;
bool Search(uint64_t key) override;
bool Search(uint64_t key, RolePtr* first_matched_role) override;
bool Search(uint64_t key,
proto::RoleAttributes* first_matched_role_attr) override;
bool Search(uint64_t key, std::vector<RolePtr>* matched_roles) override;
bool Search(uint64_t key,
std::vector<proto::RoleAttributes>* matched_roles_attr) override;
bool Search(const proto::RoleAttributes& target_attr) override;
bool Search(const proto::RoleAttributes& target_attr,
RolePtr* first_matched) override;
bool Search(const proto::RoleAttributes& target_attr,
proto::RoleAttributes* first_matched_role_attr) override;
bool Search(const proto::RoleAttributes& target_attr,
std::vector<RolePtr>* matched_roles) override;
bool Search(const proto::RoleAttributes& target_attr,
std::vector<proto::RoleAttributes>* matched_roles_attr) override;
void GetAllRoles(std::vector<RolePtr>* roles) override;
void GetAllRoles(std::vector<proto::RoleAttributes>* roles_attr) override;
private:
RoleMap roles_;
base::AtomicRWLock rw_lock_;
};
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_DISCOVERY_CONTAINER_SINGLE_VALUE_WAREHOUSE_H_
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/communication/subscriber_listener.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_DISCOVERY_COMMUNICATION_SUBSCRIBER_LISTENER_H_
#define CYBER_SERVICE_DISCOVERY_COMMUNICATION_SUBSCRIBER_LISTENER_H_
#include <functional>
#include <mutex>
#include <string>
#include "fastrtps/Domain.h"
#include "fastrtps/subscriber/SampleInfo.h"
#include "fastrtps/subscriber/Subscriber.h"
#include "fastrtps/subscriber/SubscriberListener.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class SubscriberListener : public eprosima::fastrtps::SubscriberListener {
public:
using NewMsgCallback = std::function<void(const std::string&)>;
explicit SubscriberListener(const NewMsgCallback& callback);
virtual ~SubscriberListener();
void onNewDataMessage(eprosima::fastrtps::Subscriber* sub);
void onSubscriptionMatched(eprosima::fastrtps::Subscriber* sub,
eprosima::fastrtps::MatchingInfo& info); // NOLINT
private:
NewMsgCallback callback_;
std::mutex mutex_;
};
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_DISCOVERY_COMMUNICATION_SUBSCRIBER_LISTENER_H_
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/communication/participant_listener.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/communication/participant_listener.h"
#include "cyber/common/log.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
ParticipantListener::ParticipantListener(const ChangeFunc& callback)
: callback_(callback) {}
ParticipantListener::~ParticipantListener() {
std::lock_guard<std::mutex> lck(mutex_);
callback_ = nullptr;
}
void ParticipantListener::onParticipantDiscovery(
eprosima::fastrtps::Participant* p,
eprosima::fastrtps::ParticipantDiscoveryInfo info) {
RETURN_IF_NULL(callback_);
(void)p;
std::lock_guard<std::mutex> lock(mutex_);
callback_(info);
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/communication/subscriber_listener.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/service_discovery/communication/subscriber_listener.h"
#include "cyber/common/log.h"
#include "cyber/transport/rtps/underlay_message.h"
#include "cyber/transport/rtps/underlay_message_type.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
SubscriberListener::SubscriberListener(const NewMsgCallback& callback)
: callback_(callback) {}
SubscriberListener::~SubscriberListener() {
std::lock_guard<std::mutex> lck(mutex_);
callback_ = nullptr;
}
void SubscriberListener::onNewDataMessage(eprosima::fastrtps::Subscriber* sub) {
RETURN_IF_NULL(callback_);
std::lock_guard<std::mutex> lock(mutex_);
eprosima::fastrtps::SampleInfo_t m_info;
cyber::transport::UnderlayMessage m;
RETURN_IF(!sub->takeNextData(reinterpret_cast<void*>(&m), &m_info));
RETURN_IF(m_info.sampleKind != eprosima::fastrtps::ALIVE);
callback_(m.data());
}
void SubscriberListener::onSubscriptionMatched(
eprosima::fastrtps::Subscriber* sub,
eprosima::fastrtps::MatchingInfo& info) {
(void)sub;
(void)info;
}
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/communication/participant_listener.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_SERVICE_DISCOVERY_COMMUNICATION_PARTICIPANT_LISTENER_H_
#define CYBER_SERVICE_DISCOVERY_COMMUNICATION_PARTICIPANT_LISTENER_H_
#include <functional>
#include <mutex>
#include "fastrtps/Domain.h"
#include "fastrtps/participant/Participant.h"
#include "fastrtps/participant/ParticipantListener.h"
namespace apollo {
namespace cyber {
namespace service_discovery {
class ParticipantListener : public eprosima::fastrtps::ParticipantListener {
public:
using ChangeFunc = std::function<void(
const eprosima::fastrtps::ParticipantDiscoveryInfo& info)>;
explicit ParticipantListener(const ChangeFunc& callback);
virtual ~ParticipantListener();
virtual void onParticipantDiscovery(
eprosima::fastrtps::Participant* p,
eprosima::fastrtps::ParticipantDiscoveryInfo info);
private:
ChangeFunc callback_;
std::mutex mutex_;
};
} // namespace service_discovery
} // namespace cyber
} // namespace apollo
#endif // CYBER_SERVICE_DISCOVERY_COMMUNICATION_PARTICIPANT_LISTENER_H_
| 0
|
apollo_public_repos/apollo/cyber/service_discovery
|
apollo_public_repos/apollo/cyber/service_discovery/communication/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "cyber_service_discovery_communication_hdrs",
srcs = glob([
"*.h",
]),
)
cc_library(
name = "participant_listener",
srcs = ["participant_listener.cc"],
hdrs = ["participant_listener.h"],
deps = [
"//cyber/common:log",
"@fastrtps",
],
)
cc_library(
name = "subscriber_listener",
srcs = ["subscriber_listener.cc"],
hdrs = ["subscriber_listener.h"],
deps = [
"//cyber/common:log",
"//cyber/transport/rtps:underlay_message",
"//cyber/transport/rtps:underlay_message_type",
"@fastrtps",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/conf/compute_sched_choreography.conf
|
scheduler_conf {
policy: "choreography"
choreography_conf {
choreography_processor_num: 8
choreography_affinity: "range"
choreography_cpuset: "0-7"
pool_processor_num: 12
pool_affinity: "range"
pool_cpuset: "8-11,16-23"
tasks: [
{
name: "velodyne_128_convert"
processor: 0
prio: 11
},
{
name: "velodyne128_compensator"
processor: 1
prio: 12
},
{
name: "velodyne_16_front_center_convert"
processor: 2
},
{
name: "velodyne_fusion"
processor: 2
prio: 2
},
{
name: "velodyne16_fusion_compensator"
processor: 2
prio: 3
},
{
name: "velodyne_16_rear_left_convert"
prio: 10
},
{
name: "velodyne_16_rear_right_convert"
prio: 10
},
{
name: "Velodyne128Detection"
processor: 3
prio: 13
},
{
name: "Velodyne16Detection"
processor: 3
prio: 10
},
{
name: "RecognitionComponent"
processor: 3
prio: 14
},
{
name: "SensorFusion"
processor: 4
prio: 15
},
{
name: "prediction"
processor: 5
prio: 16
},
{
name: "planning"
processor: 6
prio: 17
},
{
name: "routing"
processor: 6
},
{
name: "planning_/apollo/routing_response"
processor: 6
},
{
name: "planning_/apollo/perception/traffic_light"
processor: 7
prio: 17
},
{
name: "msf_localization"
processor: 7
},
{
name: "rtk_localization"
processor: 7
},
{
name: "msf_localization_/apollo/sensor/lidar64/compensator/PointCloud2"
prio: 4
},
{
name: "camera_front_6mm_compress"
prio: 3
},
{
name: "camera_front_12mm_compress"
prio: 3
},
{
name: "camera_left_fisheye_compress"
prio: 3
},
{
name: "camera_right_fisheye_compress"
prio: 3
},
{
name: "camera_rear_6mm_compress"
prio: 3
}
]
}
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/conf/compute_sched_classic.conf
|
scheduler_conf {
policy: "classic"
classic_conf {
groups: [
{
name: "compute"
processor_num: 16
affinity: "range"
cpuset: "0-7,16-23"
processor_policy: "SCHED_OTHER"
processor_prio: 0
tasks: [
{
name: "velodyne_16_front_center_convert"
prio: 10
},
{
name: "velodyne_16_rear_left_convert"
prio: 10
},
{
name: "velodyne_16_rear_right_convert"
prio: 10
},
{
name: "velodyne_fusion"
prio: 11
},
{
name: "velodyne16_fusion_compensator"
prio: 11
},
{
name: "Velodyne16Detection"
prio: 11
},
{
name: "velodyne_128_convert"
prio: 11
},
{
name: "velodyne128_compensator"
prio: 12
},
{
name: "Velodyne128Detection"
prio: 13
},
{
name: "RecognitionComponent"
prio: 14
},
{
name: "SensorFusion"
prio: 15
},
{
name: "prediction"
prio: 16
},
{
name: "planning"
prio: 17
},
{
name: "planning_/apollo/perception/traffic_light"
prio: 17
},
{
name: "routing"
prio: 19
},
{
name: "planning_/apollo/routing_response"
prio: 19
},
{
name: "msf_localization"
prio: 20
},
{
name: "rtk_localization"
prio: 20
},
{
name: "msf_localization_/apollo/sensor/lidar64/compensator/PointCloud2"
prio: 20
}
]
},
{
name: "compute_camera"
processor_num: 16
affinity: "range"
cpuset: "8-15,24-31"
processor_policy: "SCHED_OTHER"
processor_prio: 0
tasks: [
{
name: "camera_front_6mm_compress"
prio: 0
},
{
name: "camera_front_12mm_compress"
prio: 0
},
{
name: "camera_left_fisheye_compress"
prio: 0
},
{
name: "camera_right_fisheye_compress"
prio: 0
},
{
name: "camera_rear_6mm_compress"
prio: 0
}
]
}
]
}
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/conf/control_sched.conf
|
scheduler_conf {
policy: "classic"
classic_conf {
groups: [
{
name: "control"
processor_num: 8
affinity: "range"
cpuset: "8-15"
processor_policy: "SCHED_OTHER"
processor_prio: 0
tasks: [
{
name: "control_/apollo/planning"
prio: 10
},
{
name: "canbus_/apollo/control"
prio: 11
}
]
}
]
}
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/conf/control_sched_classic.conf
|
scheduler_conf {
policy: "classic"
classic_conf {
groups: [
{
name: "control"
processor_num: 8
affinity: "range"
cpuset: "8-15"
processor_policy: "SCHED_OTHER"
processor_prio: 0
tasks: [
{
name: "control_/apollo/planning"
prio: 10
},
{
name: "canbus_/apollo/control"
prio: 11
}
]
}
]
}
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/conf/control_sched_choreography.conf
|
scheduler_conf {
policy: "choreography"
choreography_conf {
processor_num: 2
pool_processor_num: 2
pool_affinity: "range"
pool_cpuset: "12-15"
tasks: [
{
name: "control_/apollo/planning"
processor: 0
},
{
name: "canbus_/apollo/control"
processor: 0
prio: 2
}
]
}
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/conf/compute_sched.conf
|
scheduler_conf {
policy: "classic"
classic_conf {
groups: [
{
name: "compute"
processor_num: 16
affinity: "range"
cpuset: "0-7,16-23"
processor_policy: "SCHED_OTHER"
processor_prio: 0
tasks: [
{
name: "velodyne_16_front_center_convert"
prio: 10
},
{
name: "velodyne_16_rear_left_convert"
prio: 10
},
{
name: "velodyne_16_rear_right_convert"
prio: 10
},
{
name: "velodyne_fusion"
prio: 11
},
{
name: "velodyne16_fusion_compensator"
prio: 11
},
{
name: "Velodyne16Detection"
prio: 11
},
{
name: "velodyne_128_convert"
prio: 11
},
{
name: "velodyne128_compensator"
prio: 12
},
{
name: "Velodyne128Detection"
prio: 13
},
{
name: "RecognitionComponent"
prio: 14
},
{
name: "SensorFusion"
prio: 15
},
{
name: "prediction"
prio: 16
},
{
name: "planning"
prio: 17
},
{
name: "planning_/apollo/perception/traffic_light"
prio: 17
},
{
name: "routing"
prio: 19
},
{
name: "planning_/apollo/routing_response"
prio: 19
},
{
name: "msf_localization"
prio: 20
},
{
name: "rtk_localization"
prio: 20
},
{
name: "msf_localization_/apollo/sensor/lidar64/compensator/PointCloud2"
prio: 20
}
]
},
{
name: "compute_camera"
processor_num: 16
affinity: "range"
cpuset: "8-15,24-31"
processor_policy: "SCHED_OTHER"
processor_prio: 0
tasks: [
{
name: "camera_front_6mm_compress"
prio: 0
},
{
name: "camera_front_12mm_compress"
prio: 0
},
{
name: "camera_left_fisheye_compress"
prio: 0
},
{
name: "camera_right_fisheye_compress"
prio: 0
},
{
name: "camera_rear_6mm_compress"
prio: 0
}
]
}
]
}
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/conf/example_sched_classic.conf
|
scheduler_conf {
policy: "classic"
process_level_cpuset: "0-7,16-23" # all threads in the process are on the cpuset
threads: [
{
name: "async_log"
cpuset: "1"
policy: "SCHED_OTHER" # policy: SCHED_OTHER,SCHED_RR,SCHED_FIFO
prio: 0
}, {
name: "shm"
cpuset: "2"
policy: "SCHED_FIFO"
prio: 10
}
]
classic_conf {
groups: [
{
name: "group1"
processor_num: 16
affinity: "range"
cpuset: "0-7,16-23"
processor_policy: "SCHED_OTHER" # policy: SCHED_OTHER,SCHED_RR,SCHED_FIFO
processor_prio: 0
tasks: [
{
name: "E"
prio: 0
}
]
},{
name: "group2"
processor_num: 16
affinity: "1to1"
cpuset: "8-15,24-31"
processor_policy: "SCHED_OTHER"
processor_prio: 0
tasks: [
{
name: "A"
prio: 0
},{
name: "B"
prio: 1
},{
name: "C"
prio: 2
},{
name: "D"
prio: 3
}
]
}
]
}
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/conf/dreamview_sched.conf
|
scheduler_conf {
policy: "classic"
classic_conf {
groups: [
{
name: "dv"
processor_num: 4
affinity: "range"
cpuset: "28-31"
}
]
}
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/conf/cyber.pb.conf
|
# transport_conf {
# shm_conf {
# # "multicast" "condition"
# notifier_type: "condition"
# # "posix" "xsi"
# shm_type: "xsi"
# shm_locator {
# ip: "239.255.0.100"
# port: 8888
# }
# }
# participant_attr {
# lease_duration: 12
# announcement_period: 3
# domain_id_gain: 200
# port_base: 10000
# }
# communication_mode {
# same_proc: INTRA
# diff_proc: SHM
# diff_host: RTPS
# }
# resource_limit {
# max_history_depth: 1000
# }
# }
run_mode_conf {
run_mode: MODE_REALITY
clock_mode: MODE_CYBER
}
scheduler_conf {
routine_num: 100
default_proc_num: 16
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/conf/example_sched_choreography.conf
|
scheduler_conf {
policy: "choreography"
process_level_cpuset: "0-7,16-23" # all threads in the process are on the cpuset
threads: [
{
name: "lidar"
cpuset: "1"
policy: "SCHED_RR" # policy: SCHED_OTHER,SCHED_RR,SCHED_FIFO
prio: 10
}, {
name: "shm"
cpuset: "2"
policy: "SCHED_FIFO"
prio: 10
}
]
choreography_conf {
choreography_processor_num: 8
choreography_affinity: "range"
choreography_cpuset: "0-7"
choreography_processor_policy: "SCHED_FIFO" # policy: SCHED_OTHER,SCHED_RR,SCHED_FIFO
choreography_processor_prio: 10
pool_processor_num: 8
pool_affinity: "range"
pool_cpuset: "16-23"
pool_processor_policy: "SCHED_OTHER"
pool_processor_prio: 0
tasks: [
{
name: "A"
processor: 0
prio: 1
},
{
name: "B"
processor: 0
prio: 2
},
{
name: "C"
processor: 1
prio: 1
},
{
name: "D"
processor: 1
prio: 2
},
{
name: "E"
}
]
}
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/event/perf_event.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_EVENT_PERF_EVENT_H_
#define CYBER_EVENT_PERF_EVENT_H_
#include <cstdint>
#include <limits>
#include <sstream>
#include <string>
#include "cyber/common/global_data.h"
#include "cyber/common/macros.h"
namespace apollo {
namespace cyber {
namespace event {
enum class EventType { SCHED_EVENT = 0, TRANS_EVENT = 1, TRY_FETCH_EVENT = 3 };
enum class TransPerf {
TRANSMIT_BEGIN = 0,
SERIALIZE = 1,
SEND = 2,
MESSAGE_ARRIVE = 3,
OBTAIN = 4, // only for shm
DESERIALIZE = 5,
DISPATCH = 6,
NOTIFY = 7,
FETCH = 8,
CALLBACK = 9,
TRANS_END
};
enum class SchedPerf {
SWAP_IN = 1,
SWAP_OUT = 2,
NOTIFY_IN = 3,
NEXT_RT = 4,
RT_CREATE = 5,
};
class EventBase {
public:
virtual std::string SerializeToString() = 0;
void set_eid(int eid) { eid_ = eid; }
void set_etype(int etype) { etype_ = etype; }
void set_stamp(uint64_t stamp) { stamp_ = stamp; }
virtual void set_cr_id(uint64_t cr_id) { UNUSED(cr_id); }
virtual void set_cr_state(int cr_state) { UNUSED(cr_state); }
virtual void set_proc_id(int proc_id) { UNUSED(proc_id); }
virtual void set_fetch_res(int fetch_res) { UNUSED(fetch_res); }
virtual void set_msg_seq(uint64_t msg_seq) { UNUSED(msg_seq); }
virtual void set_channel_id(uint64_t channel_id) { UNUSED(channel_id); }
virtual void set_adder(const std::string& adder) { UNUSED(adder); }
protected:
int etype_;
int eid_;
uint64_t stamp_;
};
// event_id
// 1 swap_in
// 2 swap_out
// 3 notify_in
// 4 next_routine
class SchedEvent : public EventBase {
public:
SchedEvent() { etype_ = static_cast<int>(EventType::SCHED_EVENT); }
std::string SerializeToString() override {
std::stringstream ss;
ss << etype_ << "\t";
ss << eid_ << "\t";
ss << common::GlobalData::GetTaskNameById(cr_id_) << "\t";
ss << proc_id_ << "\t";
ss << cr_state_ << "\t";
ss << stamp_;
return ss.str();
}
void set_cr_id(uint64_t cr_id) override { cr_id_ = cr_id; }
void set_cr_state(int cr_state) override { cr_state_ = cr_state; }
void set_proc_id(int proc_id) override { proc_id_ = proc_id; }
private:
int cr_state_ = 1;
int proc_id_ = 0;
uint64_t cr_id_ = 0;
};
// event_id = 1 transport
// 1 transport time
// 2 write_data_cache & notify listener
class TransportEvent : public EventBase {
public:
TransportEvent() { etype_ = static_cast<int>(EventType::TRANS_EVENT); }
std::string SerializeToString() override {
std::stringstream ss;
ss << etype_ << "\t";
ss << eid_ << "\t";
ss << common::GlobalData::GetChannelById(channel_id_) << "\t";
ss << msg_seq_ << "\t";
ss << stamp_ << "\t";
ss << adder_;
return ss.str();
}
void set_msg_seq(uint64_t msg_seq) override { msg_seq_ = msg_seq; }
void set_channel_id(uint64_t channel_id) override {
channel_id_ = channel_id;
}
void set_adder(const std::string& adder) override { adder_ = adder; }
static std::string ShowTransPerf(TransPerf type) {
if (type == TransPerf::TRANSMIT_BEGIN) {
return "TRANSMIT_BEGIN";
} else if (type == TransPerf::SERIALIZE) {
return "SERIALIZE";
} else if (type == TransPerf::SEND) {
return "SEND";
} else if (type == TransPerf::MESSAGE_ARRIVE) {
return "MESSAGE_ARRIVE";
} else if (type == TransPerf::OBTAIN) {
return "OBTAIN";
} else if (type == TransPerf::DESERIALIZE) {
return "DESERIALIZE";
} else if (type == TransPerf::DISPATCH) {
return "DISPATCH";
} else if (type == TransPerf::NOTIFY) {
return "NOTIFY";
} else if (type == TransPerf::FETCH) {
return "FETCH";
} else if (type == TransPerf::CALLBACK) {
return "CALLBACK";
}
return "";
}
private:
std::string adder_ = "";
uint64_t msg_seq_ = 0;
uint64_t channel_id_ = std::numeric_limits<uint64_t>::max();
};
} // namespace event
} // namespace cyber
} // namespace apollo
#endif // CYBER_EVENT_PERF_EVENT_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/event/perf_event_cache.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_EVENT_PERF_EVENT_CACHE_H_
#define CYBER_EVENT_PERF_EVENT_CACHE_H_
#include <chrono>
#include <fstream>
#include <memory>
#include <string>
#include <thread>
#include "cyber/proto/perf_conf.pb.h"
#include "cyber/base/bounded_queue.h"
#include "cyber/common/macros.h"
#include "cyber/event/perf_event.h"
namespace apollo {
namespace cyber {
namespace event {
class PerfEventCache {
public:
using EventBasePtr = std::shared_ptr<EventBase>;
~PerfEventCache();
void AddSchedEvent(const SchedPerf event_id, const uint64_t cr_id,
const int proc_id, const int cr_state = -1);
void AddTransportEvent(const TransPerf event_id, const uint64_t channel_id,
const uint64_t msg_seq, const uint64_t stamp = 0,
const std::string& adder = "-");
std::string PerfFile() { return perf_file_; }
void Shutdown();
private:
void Start();
void Run();
std::thread io_thread_;
std::ofstream of_;
bool enable_ = false;
bool shutdown_ = false;
proto::PerfConf perf_conf_;
std::string perf_file_ = "";
base::BoundedQueue<EventBasePtr> event_queue_;
const int kFlushSize = 512;
const uint64_t kEventQueueSize = 8192;
DECLARE_SINGLETON(PerfEventCache)
};
} // namespace event
} // namespace cyber
} // namespace apollo
#endif // CYBER_EVENT_PERF_EVENT_CACHE_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/event/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "cyber_event_hdrs",
srcs = glob([
"*.h",
]),
)
cc_library(
name = "perf_event_cache",
srcs = ["perf_event_cache.cc"],
hdrs = ["perf_event_cache.h"],
deps = [
":perf_event",
"//cyber:state",
"//cyber/base:bounded_queue",
"//cyber/common:global_data",
"//cyber/common:log",
"//cyber/common:macros",
"//cyber/time",
],
)
cc_library(
name = "perf_event",
hdrs = ["perf_event.h"],
deps = [
"//cyber/common:global_data",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/event/perf_event_cache.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/event/perf_event_cache.h"
#include <string>
#include "cyber/common/global_data.h"
#include "cyber/common/log.h"
#include "cyber/state.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
namespace event {
using common::GlobalData;
using proto::PerfConf;
using proto::PerfType;
PerfEventCache::PerfEventCache() {
auto& global_conf = GlobalData::Instance()->Config();
if (global_conf.has_perf_conf()) {
perf_conf_.CopyFrom(global_conf.perf_conf());
enable_ = perf_conf_.enable();
}
if (enable_) {
if (!event_queue_.Init(kEventQueueSize)) {
AERROR << "Event queue init failed.";
throw std::runtime_error("Event queue init failed.");
}
Start();
}
}
PerfEventCache::~PerfEventCache() { Shutdown(); }
void PerfEventCache::Shutdown() {
if (!enable_) {
return;
}
shutdown_ = true;
event_queue_.BreakAllWait();
if (io_thread_.joinable()) {
io_thread_.join();
}
of_ << cyber::Time::Now().ToNanosecond() << std::endl;
of_.flush();
of_.close();
}
void PerfEventCache::AddSchedEvent(const SchedPerf event_id,
const uint64_t cr_id, const int proc_id,
const int cr_state) {
if (!enable_) {
return;
}
if (perf_conf_.type() != PerfType::SCHED &&
perf_conf_.type() != PerfType::ALL) {
return;
}
EventBasePtr e = std::make_shared<SchedEvent>();
e->set_eid(static_cast<int>(event_id));
e->set_stamp(Time::Now().ToNanosecond());
e->set_cr_state(cr_state);
e->set_cr_id(cr_id);
e->set_proc_id(proc_id);
event_queue_.Enqueue(e);
}
void PerfEventCache::AddTransportEvent(const TransPerf event_id,
const uint64_t channel_id,
const uint64_t msg_seq,
const uint64_t stamp,
const std::string& adder) {
if (!enable_) {
return;
}
if (perf_conf_.type() != PerfType::TRANSPORT &&
perf_conf_.type() != PerfType::ALL) {
return;
}
EventBasePtr e = std::make_shared<TransportEvent>();
e->set_eid(static_cast<int>(event_id));
e->set_channel_id(channel_id);
e->set_msg_seq(msg_seq);
e->set_adder(adder);
auto t = stamp;
if (stamp == 0) {
t = Time::Now().ToNanosecond();
}
e->set_stamp(t);
event_queue_.Enqueue(e);
}
void PerfEventCache::Run() {
EventBasePtr event;
int buf_size = 0;
while (!shutdown_ && !apollo::cyber::IsShutdown()) {
if (event_queue_.WaitDequeue(&event)) {
of_ << event->SerializeToString() << std::endl;
buf_size++;
if (buf_size >= kFlushSize) {
of_.flush();
buf_size = 0;
}
}
}
}
void PerfEventCache::Start() {
auto now = Time::Now();
std::string perf_file = "cyber_perf_" + now.ToString() + ".data";
std::replace(perf_file.begin(), perf_file.end(), ' ', '_');
std::replace(perf_file.begin(), perf_file.end(), ':', '-');
of_.open(perf_file, std::ios::trunc);
perf_file_ = perf_file;
of_ << Time::Now().ToNanosecond() << std::endl;
io_thread_ = std::thread(&PerfEventCache::Run, this);
}
} // namespace event
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/for_each_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/base/for_each.h"
#include <memory>
#include <vector>
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace base {
TEST(ForEachTest, base) {
std::vector<int> vec;
FOR_EACH(i, 0, 100) { vec.push_back(i); }
EXPECT_EQ(100, vec.size());
int index = 0;
FOR_EACH(it, vec.begin(), vec.end()) { EXPECT_EQ(index++, *it); }
FOR_EACH(i, 0, 'a') { EXPECT_GT('a', i); }
}
} // namespace base
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/for_each.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_FOR_EACH_H_
#define CYBER_BASE_FOR_EACH_H_
#include <type_traits>
#include "cyber/base/macros.h"
namespace apollo {
namespace cyber {
namespace base {
DEFINE_TYPE_TRAIT(HasLess, operator<) // NOLINT
template <class Value, class End>
typename std::enable_if<HasLess<Value>::value && HasLess<End>::value,
bool>::type
LessThan(const Value& val, const End& end) {
return val < end;
}
template <class Value, class End>
typename std::enable_if<!HasLess<Value>::value || !HasLess<End>::value,
bool>::type
LessThan(const Value& val, const End& end) {
return val != end;
}
#define FOR_EACH(i, begin, end) \
for (auto i = (true ? (begin) : (end)); \
apollo::cyber::base::LessThan(i, (end)); ++i)
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_FOR_EACH_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/signal_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/base/signal.h"
#include <memory>
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace base {
TEST(SlotTest, zero_input_param) {
char ch = '0';
Slot<> slot_a([&ch]() { ch = 'a'; });
EXPECT_TRUE(slot_a.connected());
slot_a();
EXPECT_EQ(ch, 'a');
slot_a.Disconnect();
EXPECT_FALSE(slot_a.connected());
ch = '0';
slot_a();
EXPECT_NE(ch, 'a');
Slot<> slot_b([&ch]() { ch = 'b'; }, false);
EXPECT_FALSE(slot_b.connected());
ch = '0';
slot_b();
EXPECT_NE(ch, 'b');
Slot<> slot_c(nullptr);
EXPECT_NO_FATAL_FAILURE(slot_c());
}
TEST(SlotTest, two_input_params) {
int sum = 0;
Slot<int, int> slot_a([&sum](int lhs, int rhs) { sum = lhs + rhs; });
EXPECT_TRUE(slot_a.connected());
int lhs = 1, rhs = 2;
slot_a(lhs, rhs);
EXPECT_EQ(sum, lhs + rhs);
Slot<int, int> slot_b(slot_a);
lhs = 3;
rhs = 4;
slot_b(lhs, rhs);
EXPECT_EQ(sum, lhs + rhs);
slot_b.Disconnect();
EXPECT_FALSE(slot_b.connected());
sum = 0;
lhs = 5;
rhs = 6;
slot_b(lhs, rhs);
EXPECT_EQ(sum, 0);
}
TEST(ConnectionTest, null_signal) {
Connection<> conn_a;
EXPECT_FALSE(conn_a.IsConnected());
EXPECT_FALSE(conn_a.Disconnect());
EXPECT_FALSE(conn_a.HasSlot(nullptr));
auto slot = std::make_shared<Slot<>>([]() {});
Connection<> conn_b(slot, nullptr);
EXPECT_TRUE(conn_b.IsConnected());
EXPECT_FALSE(conn_b.Disconnect());
EXPECT_TRUE(conn_b.HasSlot(slot));
EXPECT_FALSE(conn_a.HasSlot(slot));
conn_b = conn_b;
conn_a = conn_b;
EXPECT_TRUE(conn_a.IsConnected());
EXPECT_FALSE(conn_a.Disconnect());
EXPECT_TRUE(conn_a.HasSlot(slot));
Signal<> sig;
Connection<> conn_c(nullptr, &sig);
EXPECT_FALSE(conn_c.Disconnect());
}
TEST(SignalTest, module) {
Signal<int, int> sig;
int sum_a = 0;
auto conn_a = sig.Connect([&sum_a](int lhs, int rhs) { sum_a = lhs + rhs; });
int sum_b = 0;
auto conn_b = sig.Connect([&sum_b](int lhs, int rhs) { sum_b = lhs + rhs; });
int lhs = 1, rhs = 2;
sig(lhs, rhs);
EXPECT_EQ(sum_a, lhs + rhs);
EXPECT_EQ(sum_b, lhs + rhs);
Connection<int, int> conn_c;
EXPECT_FALSE(sig.Disconnect(conn_c));
EXPECT_TRUE(sig.Disconnect(conn_b));
sum_a = 0;
sum_b = 0;
lhs = 3;
rhs = 4;
sig(lhs, rhs);
EXPECT_EQ(sum_a, lhs + rhs);
EXPECT_NE(sum_b, lhs + rhs);
sig.DisconnectAllSlots();
sum_a = 0;
sum_b = 0;
lhs = 5;
rhs = 6;
sig(lhs, rhs);
EXPECT_NE(sum_a, lhs + rhs);
EXPECT_NE(sum_b, lhs + rhs);
}
} // namespace base
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/signal.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_SIGNAL_H_
#define CYBER_BASE_SIGNAL_H_
#include <algorithm>
#include <functional>
#include <list>
#include <memory>
#include <mutex>
namespace apollo {
namespace cyber {
namespace base {
template <typename... Args>
class Slot;
template <typename... Args>
class Connection;
template <typename... Args>
class Signal {
public:
using Callback = std::function<void(Args...)>;
using SlotPtr = std::shared_ptr<Slot<Args...>>;
using SlotList = std::list<SlotPtr>;
using ConnectionType = Connection<Args...>;
Signal() {}
virtual ~Signal() { DisconnectAllSlots(); }
void operator()(Args... args) {
SlotList local;
{
std::lock_guard<std::mutex> lock(mutex_);
for (auto& slot : slots_) {
local.emplace_back(slot);
}
}
if (!local.empty()) {
for (auto& slot : local) {
(*slot)(args...);
}
}
ClearDisconnectedSlots();
}
ConnectionType Connect(const Callback& cb) {
auto slot = std::make_shared<Slot<Args...>>(cb);
{
std::lock_guard<std::mutex> lock(mutex_);
slots_.emplace_back(slot);
}
return ConnectionType(slot, this);
}
bool Disconnect(const ConnectionType& conn) {
bool find = false;
{
std::lock_guard<std::mutex> lock(mutex_);
for (auto& slot : slots_) {
if (conn.HasSlot(slot)) {
find = true;
slot->Disconnect();
}
}
}
if (find) {
ClearDisconnectedSlots();
}
return find;
}
void DisconnectAllSlots() {
std::lock_guard<std::mutex> lock(mutex_);
for (auto& slot : slots_) {
slot->Disconnect();
}
slots_.clear();
}
private:
Signal(const Signal&) = delete;
Signal& operator=(const Signal&) = delete;
void ClearDisconnectedSlots() {
std::lock_guard<std::mutex> lock(mutex_);
slots_.erase(
std::remove_if(slots_.begin(), slots_.end(),
[](const SlotPtr& slot) { return !slot->connected(); }),
slots_.end());
}
SlotList slots_;
std::mutex mutex_;
};
template <typename... Args>
class Connection {
public:
using SlotPtr = std::shared_ptr<Slot<Args...>>;
using SignalPtr = Signal<Args...>*;
Connection() : slot_(nullptr), signal_(nullptr) {}
Connection(const SlotPtr& slot, const SignalPtr& signal)
: slot_(slot), signal_(signal) {}
virtual ~Connection() {
slot_ = nullptr;
signal_ = nullptr;
}
Connection& operator=(const Connection& another) {
if (this != &another) {
this->slot_ = another.slot_;
this->signal_ = another.signal_;
}
return *this;
}
bool HasSlot(const SlotPtr& slot) const {
if (slot != nullptr && slot_ != nullptr) {
return slot_.get() == slot.get();
}
return false;
}
bool IsConnected() const {
if (slot_) {
return slot_->connected();
}
return false;
}
bool Disconnect() {
if (signal_ && slot_) {
return signal_->Disconnect(*this);
}
return false;
}
private:
SlotPtr slot_;
SignalPtr signal_;
};
template <typename... Args>
class Slot {
public:
using Callback = std::function<void(Args...)>;
Slot(const Slot& another)
: cb_(another.cb_), connected_(another.connected_) {}
explicit Slot(const Callback& cb, bool connected = true)
: cb_(cb), connected_(connected) {}
virtual ~Slot() {}
void operator()(Args... args) {
if (connected_ && cb_) {
cb_(args...);
}
}
void Disconnect() { connected_ = false; }
bool connected() const { return connected_; }
private:
Callback cb_;
bool connected_ = true;
};
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_SIGNAL_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/thread_pool.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_THREAD_POOL_H_
#define CYBER_BASE_THREAD_POOL_H_
#include <atomic>
#include <functional>
#include <future>
#include <memory>
#include <queue>
#include <stdexcept>
#include <thread>
#include <utility>
#include <vector>
#include "cyber/base/bounded_queue.h"
namespace apollo {
namespace cyber {
namespace base {
class ThreadPool {
public:
explicit ThreadPool(std::size_t thread_num, std::size_t max_task_num = 1000);
template <typename F, typename... Args>
auto Enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>;
~ThreadPool();
private:
std::vector<std::thread> workers_;
BoundedQueue<std::function<void()>> task_queue_;
std::atomic_bool stop_;
};
inline ThreadPool::ThreadPool(std::size_t threads, std::size_t max_task_num)
: stop_(false) {
if (!task_queue_.Init(max_task_num, new BlockWaitStrategy())) {
throw std::runtime_error("Task queue init failed.");
}
workers_.reserve(threads);
for (size_t i = 0; i < threads; ++i) {
workers_.emplace_back([this] {
while (!stop_) {
std::function<void()> task;
if (task_queue_.WaitDequeue(&task)) {
task();
}
}
});
}
}
// before using the return value, you should check value.valid()
template <typename F, typename... Args>
auto ThreadPool::Enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type> {
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared<std::packaged_task<return_type()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...));
std::future<return_type> res = task->get_future();
// don't allow enqueueing after stopping the pool
if (stop_) {
return std::future<return_type>();
}
task_queue_.Enqueue([task]() { (*task)(); });
return res;
};
// the destructor joins all threads
inline ThreadPool::~ThreadPool() {
if (stop_.exchange(true)) {
return;
}
task_queue_.BreakAllWait();
for (std::thread& worker : workers_) {
worker.join();
}
}
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_THREAD_POOL_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/atomic_rw_lock_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/base/atomic_rw_lock.h"
#include <thread>
#include "gtest/gtest.h"
#include "cyber/base/reentrant_rw_lock.h"
namespace apollo {
namespace cyber {
namespace base {
TEST(ReentrantRWLockTest, read_lock) {
int count = 0;
int thread_init = 0;
bool flag = true;
ReentrantRWLock lock;
auto f = [&]() {
ReadLockGuard<ReentrantRWLock> lg(lock);
count++;
thread_init++;
while (flag) {
std::this_thread::yield();
}
};
std::thread t1(f);
std::thread t2(f);
while (thread_init != 2) {
std::this_thread::yield();
}
EXPECT_EQ(2, count);
flag = false;
t1.join();
t2.join();
{
ReadLockGuard<ReentrantRWLock> lg1(lock);
{
ReadLockGuard<ReentrantRWLock> lg2(lock);
{
ReadLockGuard<ReentrantRWLock> lg3(lock);
{ ReadLockGuard<ReentrantRWLock> lg4(lock); }
}
}
}
}
TEST(ReentrantRWLockTest, write_lock) {
int count = 0;
int thread_run = 0;
bool flag = true;
ReentrantRWLock lock(false);
auto f = [&]() {
thread_run++;
WriteLockGuard<ReentrantRWLock> lg(lock);
count++;
while (flag) {
std::this_thread::yield();
}
};
std::thread t1(f);
std::thread t2(f);
while (thread_run != 2) {
std::this_thread::yield();
}
EXPECT_EQ(1, count);
flag = false;
t1.join();
t2.join();
{
WriteLockGuard<ReentrantRWLock> lg1(lock);
{
WriteLockGuard<ReentrantRWLock> lg2(lock);
{ ReadLockGuard<ReentrantRWLock> lg3(lock); }
}
}
}
} // namespace base
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/concurrent_object_pool.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_CONCURRENT_OBJECT_POOL_H_
#define CYBER_BASE_CONCURRENT_OBJECT_POOL_H_
#include <atomic>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <utility>
#include "cyber/base/for_each.h"
#include "cyber/base/macros.h"
namespace apollo {
namespace cyber {
namespace base {
template <typename T>
class CCObjectPool : public std::enable_shared_from_this<CCObjectPool<T>> {
public:
explicit CCObjectPool(uint32_t size);
virtual ~CCObjectPool();
template <typename... Args>
void ConstructAll(Args &&... args);
template <typename... Args>
std::shared_ptr<T> ConstructObject(Args &&... args);
std::shared_ptr<T> GetObject();
void ReleaseObject(T *);
uint32_t size() const;
private:
struct Node {
T object;
Node *next;
};
struct alignas(2 * sizeof(Node *)) Head {
uintptr_t count;
Node *node;
};
private:
CCObjectPool(CCObjectPool &) = delete;
CCObjectPool &operator=(CCObjectPool &) = delete;
bool FindFreeHead(Head *head);
std::atomic<Head> free_head_;
Node *node_arena_ = nullptr;
uint32_t capacity_ = 0;
};
template <typename T>
CCObjectPool<T>::CCObjectPool(uint32_t size) : capacity_(size) {
node_arena_ = static_cast<Node *>(CheckedCalloc(capacity_, sizeof(Node)));
FOR_EACH(i, 0, capacity_ - 1) { node_arena_[i].next = node_arena_ + 1 + i; }
node_arena_[capacity_ - 1].next = nullptr;
free_head_.store({0, node_arena_}, std::memory_order_relaxed);
}
template <typename T>
template <typename... Args>
void CCObjectPool<T>::ConstructAll(Args &&... args) {
FOR_EACH(i, 0, capacity_) {
new (node_arena_ + i) T(std::forward<Args>(args)...);
}
}
template <typename T>
CCObjectPool<T>::~CCObjectPool() {
std::free(node_arena_);
}
template <typename T>
bool CCObjectPool<T>::FindFreeHead(Head *head) {
Head new_head;
Head old_head = free_head_.load(std::memory_order_acquire);
do {
if (cyber_unlikely(old_head.node == nullptr)) {
return false;
}
new_head.node = old_head.node->next;
new_head.count = old_head.count + 1;
} while (!free_head_.compare_exchange_weak(old_head, new_head,
std::memory_order_acq_rel,
std::memory_order_acquire));
*head = old_head;
return true;
}
template <typename T>
std::shared_ptr<T> CCObjectPool<T>::GetObject() {
Head free_head;
if (cyber_unlikely(!FindFreeHead(&free_head))) {
return nullptr;
}
auto self = this->shared_from_this();
return std::shared_ptr<T>(reinterpret_cast<T *>(free_head.node),
[self](T *object) { self->ReleaseObject(object); });
}
template <typename T>
template <typename... Args>
std::shared_ptr<T> CCObjectPool<T>::ConstructObject(Args &&... args) {
Head free_head;
if (cyber_unlikely(!FindFreeHead(&free_head))) {
return nullptr;
}
auto self = this->shared_from_this();
T *ptr = new (free_head.node) T(std::forward<Args>(args)...);
return std::shared_ptr<T>(ptr, [self](T *object) {
object->~T();
self->ReleaseObject(object);
});
}
template <typename T>
void CCObjectPool<T>::ReleaseObject(T *object) {
Head new_head;
Node *node = reinterpret_cast<Node *>(object);
Head old_head = free_head_.load(std::memory_order_acquire);
do {
node->next = old_head.node;
new_head.node = node;
new_head.count = old_head.count + 1;
} while (!free_head_.compare_exchange_weak(old_head, new_head,
std::memory_order_acq_rel,
std::memory_order_acquire));
}
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_CONCURRENT_OBJECT_POOL_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/object_pool.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_OBJECT_POOL_H_
#define CYBER_BASE_OBJECT_POOL_H_
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iostream>
#include <memory>
#include <new>
#include <utility>
#include "cyber/base/for_each.h"
#include "cyber/base/macros.h"
namespace apollo {
namespace cyber {
namespace base {
template <typename T>
class ObjectPool : public std::enable_shared_from_this<ObjectPool<T>> {
public:
using InitFunc = std::function<void(T *)>;
using ObjectPoolPtr = std::shared_ptr<ObjectPool<T>>;
template <typename... Args>
explicit ObjectPool(uint32_t num_objects, Args &&... args);
template <typename... Args>
ObjectPool(uint32_t num_objects, InitFunc f, Args &&... args);
virtual ~ObjectPool();
std::shared_ptr<T> GetObject();
private:
struct Node {
T object;
Node *next;
};
ObjectPool(ObjectPool &) = delete;
ObjectPool &operator=(ObjectPool &) = delete;
void ReleaseObject(T *);
uint32_t num_objects_ = 0;
char *object_arena_ = nullptr;
Node *free_head_ = nullptr;
};
template <typename T>
template <typename... Args>
ObjectPool<T>::ObjectPool(uint32_t num_objects, Args &&... args)
: num_objects_(num_objects) {
const size_t size = sizeof(Node);
object_arena_ = static_cast<char *>(std::calloc(num_objects_, size));
if (object_arena_ == nullptr) {
throw std::bad_alloc();
}
FOR_EACH(i, 0, num_objects_) {
T *obj = new (object_arena_ + i * size) T(std::forward<Args>(args)...);
reinterpret_cast<Node *>(obj)->next = free_head_;
free_head_ = reinterpret_cast<Node *>(obj);
}
}
template <typename T>
template <typename... Args>
ObjectPool<T>::ObjectPool(uint32_t num_objects, InitFunc f, Args &&... args)
: num_objects_(num_objects) {
const size_t size = sizeof(Node);
object_arena_ = static_cast<char *>(std::calloc(num_objects_, size));
if (object_arena_ == nullptr) {
throw std::bad_alloc();
}
FOR_EACH(i, 0, num_objects_) {
T *obj = new (object_arena_ + i * size) T(std::forward<Args>(args)...);
f(obj);
reinterpret_cast<Node *>(obj)->next = free_head_;
free_head_ = reinterpret_cast<Node *>(obj);
}
}
template <typename T>
ObjectPool<T>::~ObjectPool() {
if (object_arena_ != nullptr) {
const size_t size = sizeof(Node);
FOR_EACH(i, 0, num_objects_) {
reinterpret_cast<Node *>(object_arena_ + i * size)->object.~T();
}
std::free(object_arena_);
}
}
template <typename T>
void ObjectPool<T>::ReleaseObject(T *object) {
if (cyber_unlikely(object == nullptr)) {
return;
}
reinterpret_cast<Node *>(object)->next = free_head_;
free_head_ = reinterpret_cast<Node *>(object);
}
template <typename T>
std::shared_ptr<T> ObjectPool<T>::GetObject() {
if (cyber_unlikely(free_head_ == nullptr)) {
return nullptr;
}
auto self = this->shared_from_this();
auto obj =
std::shared_ptr<T>(reinterpret_cast<T *>(free_head_),
[self](T *object) { self->ReleaseObject(object); });
free_head_ = free_head_->next;
return obj;
}
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_OBJECT_POOL_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/macros.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_MACROS_H_
#define CYBER_BASE_MACROS_H_
#include <cstdlib>
#include <new>
#if __GNUC__ >= 3
#define cyber_likely(x) (__builtin_expect((x), 1))
#define cyber_unlikely(x) (__builtin_expect((x), 0))
#else
#define cyber_likely(x) (x)
#define cyber_unlikely(x) (x)
#endif
#define CACHELINE_SIZE 64
#define DEFINE_TYPE_TRAIT(name, func) \
template <typename T> \
struct name { \
template <typename Class> \
static constexpr bool Test(decltype(&Class::func)*) { \
return true; \
} \
template <typename> \
static constexpr bool Test(...) { \
return false; \
} \
\
static constexpr bool value = Test<T>(nullptr); \
}; \
\
template <typename T> \
constexpr bool name<T>::value;
inline void cpu_relax() {
#if defined(__aarch64__)
asm volatile("yield" ::: "memory");
#else
asm volatile("rep; nop" ::: "memory");
#endif
}
inline void* CheckedMalloc(size_t size) {
void* ptr = std::malloc(size);
if (!ptr) {
throw std::bad_alloc();
}
return ptr;
}
inline void* CheckedCalloc(size_t num, size_t size) {
void* ptr = std::calloc(num, size);
if (!ptr) {
throw std::bad_alloc();
}
return ptr;
}
#endif // CYBER_BASE_MACROS_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/thread_safe_queue.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_THREAD_SAFE_QUEUE_H_
#define CYBER_BASE_THREAD_SAFE_QUEUE_H_
#include <condition_variable>
#include <mutex>
#include <queue>
#include <thread>
#include <utility>
namespace apollo {
namespace cyber {
namespace base {
template <typename T>
class ThreadSafeQueue {
public:
ThreadSafeQueue() {}
ThreadSafeQueue& operator=(const ThreadSafeQueue& other) = delete;
ThreadSafeQueue(const ThreadSafeQueue& other) = delete;
~ThreadSafeQueue() { BreakAllWait(); }
void Enqueue(const T& element) {
std::lock_guard<std::mutex> lock(mutex_);
queue_.emplace(element);
cv_.notify_one();
}
bool Dequeue(T* element) {
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.empty()) {
return false;
}
*element = std::move(queue_.front());
queue_.pop();
return true;
}
bool WaitDequeue(T* element) {
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this]() { return break_all_wait_ || !queue_.empty(); });
if (break_all_wait_) {
return false;
}
*element = std::move(queue_.front());
queue_.pop();
return true;
}
typename std::queue<T>::size_type Size() {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.size();
}
bool Empty() {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.empty();
}
void BreakAllWait() {
break_all_wait_ = true;
cv_.notify_all();
}
private:
volatile bool break_all_wait_ = false;
std::mutex mutex_;
std::queue<T> queue_;
std::condition_variable cv_;
};
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_THREAD_SAFE_QUEUE_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/atomic_rw_lock.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_ATOMIC_RW_LOCK_H_
#define CYBER_BASE_ATOMIC_RW_LOCK_H_
#include <unistd.h>
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <mutex>
#include <thread>
#include "cyber/base/rw_lock_guard.h"
namespace apollo {
namespace cyber {
namespace base {
class AtomicRWLock {
friend class ReadLockGuard<AtomicRWLock>;
friend class WriteLockGuard<AtomicRWLock>;
public:
static const int32_t RW_LOCK_FREE = 0;
static const int32_t WRITE_EXCLUSIVE = -1;
static const uint32_t MAX_RETRY_TIMES = 5;
AtomicRWLock() {}
explicit AtomicRWLock(bool write_first) : write_first_(write_first) {}
private:
// all these function only can used by ReadLockGuard/WriteLockGuard;
void ReadLock();
void WriteLock();
void ReadUnlock();
void WriteUnlock();
AtomicRWLock(const AtomicRWLock&) = delete;
AtomicRWLock& operator=(const AtomicRWLock&) = delete;
std::atomic<uint32_t> write_lock_wait_num_ = {0};
std::atomic<int32_t> lock_num_ = {0};
bool write_first_ = true;
};
inline void AtomicRWLock::ReadLock() {
uint32_t retry_times = 0;
int32_t lock_num = lock_num_.load();
if (write_first_) {
do {
while (lock_num < RW_LOCK_FREE || write_lock_wait_num_.load() > 0) {
if (++retry_times == MAX_RETRY_TIMES) {
// saving cpu
std::this_thread::yield();
retry_times = 0;
}
lock_num = lock_num_.load();
}
} while (!lock_num_.compare_exchange_weak(lock_num, lock_num + 1,
std::memory_order_acq_rel,
std::memory_order_relaxed));
} else {
do {
while (lock_num < RW_LOCK_FREE) {
if (++retry_times == MAX_RETRY_TIMES) {
// saving cpu
std::this_thread::yield();
retry_times = 0;
}
lock_num = lock_num_.load();
}
} while (!lock_num_.compare_exchange_weak(lock_num, lock_num + 1,
std::memory_order_acq_rel,
std::memory_order_relaxed));
}
}
inline void AtomicRWLock::WriteLock() {
int32_t rw_lock_free = RW_LOCK_FREE;
uint32_t retry_times = 0;
write_lock_wait_num_.fetch_add(1);
while (!lock_num_.compare_exchange_weak(rw_lock_free, WRITE_EXCLUSIVE,
std::memory_order_acq_rel,
std::memory_order_relaxed)) {
// rw_lock_free will change after CAS fail, so init agin
rw_lock_free = RW_LOCK_FREE;
if (++retry_times == MAX_RETRY_TIMES) {
// saving cpu
std::this_thread::yield();
retry_times = 0;
}
}
write_lock_wait_num_.fetch_sub(1);
}
inline void AtomicRWLock::ReadUnlock() { lock_num_.fetch_sub(1); }
inline void AtomicRWLock::WriteUnlock() { lock_num_.fetch_add(1); }
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_ATOMIC_RW_LOCK_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "cyber_base_hdrs",
srcs = glob([
"*.h",
]),
)
cc_library(
name = "base",
deps = [
"//cyber/base:atomic_hash_map",
"//cyber/base:atomic_rw_lock",
"//cyber/base:bounded_queue",
"//cyber/base:concurrent_object_pool",
"//cyber/base:for_each",
"//cyber/base:macros",
"//cyber/base:object_pool",
"//cyber/base:reentrant_rw_lock",
"//cyber/base:rw_lock_guard",
"//cyber/base:signal",
"//cyber/base:thread_pool",
"//cyber/base:thread_safe_queue",
"//cyber/base:unbounded_queue",
"//cyber/base:wait_strategy",
],
)
cc_library(
name = "atomic_hash_map",
hdrs = ["atomic_hash_map.h"],
)
cc_test(
name = "atomic_hash_map_test",
size = "small",
srcs = ["atomic_hash_map_test.cc"],
deps = [
"//cyber/base:atomic_hash_map",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "atomic_rw_lock",
hdrs = ["atomic_rw_lock.h"],
deps = [
"//cyber/base:rw_lock_guard",
],
)
cc_test(
name = "atomic_rw_lock_test",
size = "small",
srcs = ["atomic_rw_lock_test.cc"],
deps = [
"//cyber/base:atomic_rw_lock",
"//cyber/base:reentrant_rw_lock",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "bounded_queue",
hdrs = ["bounded_queue.h"],
deps = [
"//cyber/base:macros",
"//cyber/base:wait_strategy",
],
)
cc_test(
name = "bounded_queue_test",
size = "small",
srcs = ["bounded_queue_test.cc"],
deps = [
"//cyber/base:bounded_queue",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "concurrent_object_pool",
hdrs = ["concurrent_object_pool.h"],
deps = [
"//cyber/base:for_each",
],
)
cc_library(
name = "for_each",
hdrs = ["for_each.h"],
deps = [
"//cyber/base:macros",
],
)
cc_test(
name = "for_each_test",
size = "small",
srcs = ["for_each_test.cc"],
deps = [
"//cyber/base:for_each",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "macros",
hdrs = ["macros.h"],
)
cc_library(
name = "object_pool",
hdrs = ["object_pool.h"],
deps = [
"//cyber/base:for_each",
"//cyber/base:macros",
],
)
cc_test(
name = "object_pool_test",
size = "small",
srcs = ["object_pool_test.cc"],
linkopts = [
"-latomic",
],
deps = [
"//cyber/base:concurrent_object_pool",
"//cyber/base:object_pool",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "reentrant_rw_lock",
hdrs = ["reentrant_rw_lock.h"],
)
cc_library(
name = "rw_lock_guard",
hdrs = ["rw_lock_guard.h"],
)
cc_library(
name = "signal",
hdrs = ["signal.h"],
)
cc_test(
name = "signal_test",
size = "small",
srcs = ["signal_test.cc"],
deps = [
"//cyber/base:signal",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "thread_pool",
hdrs = ["thread_pool.h"],
)
cc_library(
name = "thread_safe_queue",
hdrs = ["thread_safe_queue.h"],
)
cc_library(
name = "unbounded_queue",
hdrs = ["unbounded_queue.h"],
)
cc_test(
name = "unbounded_queue_test",
size = "small",
srcs = ["unbounded_queue_test.cc"],
deps = [
"//cyber/base:unbounded_queue",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "wait_strategy",
hdrs = ["wait_strategy.h"],
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/unbounded_queue_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/base/unbounded_queue.h"
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace base {
TEST(UnboundedQueueTest, all_in_one) {
UnboundedQueue<int> q;
EXPECT_TRUE(q.Empty());
EXPECT_EQ(q.Size(), 0);
int front = 0;
EXPECT_FALSE(q.Dequeue(&front));
q.Enqueue(1);
EXPECT_FALSE(q.Empty());
EXPECT_EQ(q.Size(), 1);
q.Enqueue(2);
EXPECT_EQ(q.Size(), 2);
EXPECT_TRUE(q.Dequeue(&front));
EXPECT_EQ(front, 1);
EXPECT_EQ(q.Size(), 1);
EXPECT_TRUE(q.Dequeue(&front));
EXPECT_EQ(front, 2);
EXPECT_TRUE(q.Empty());
EXPECT_EQ(q.Size(), 0);
EXPECT_FALSE(q.Dequeue(&front));
q.Enqueue(3);
EXPECT_FALSE(q.Empty());
EXPECT_EQ(q.Size(), 1);
q.Clear();
EXPECT_FALSE(q.Dequeue(&front));
EXPECT_TRUE(q.Empty());
EXPECT_EQ(q.Size(), 0);
q.Enqueue(4);
EXPECT_FALSE(q.Empty());
EXPECT_EQ(q.Size(), 1);
EXPECT_TRUE(q.Dequeue(&front));
EXPECT_EQ(front, 4);
EXPECT_TRUE(q.Empty());
EXPECT_EQ(q.Size(), 0);
}
} // namespace base
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/rw_lock_guard.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_RW_LOCK_GUARD_H_
#define CYBER_BASE_RW_LOCK_GUARD_H_
#include <unistd.h>
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <mutex>
#include <thread>
namespace apollo {
namespace cyber {
namespace base {
template <typename RWLock>
class ReadLockGuard {
public:
explicit ReadLockGuard(RWLock& lock) : rw_lock_(lock) { rw_lock_.ReadLock(); }
~ReadLockGuard() { rw_lock_.ReadUnlock(); }
private:
ReadLockGuard(const ReadLockGuard& other) = delete;
ReadLockGuard& operator=(const ReadLockGuard& other) = delete;
RWLock& rw_lock_;
};
template <typename RWLock>
class WriteLockGuard {
public:
explicit WriteLockGuard(RWLock& lock) : rw_lock_(lock) {
rw_lock_.WriteLock();
}
~WriteLockGuard() { rw_lock_.WriteUnlock(); }
private:
WriteLockGuard(const WriteLockGuard& other) = delete;
WriteLockGuard& operator=(const WriteLockGuard& other) = delete;
RWLock& rw_lock_;
};
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_RW_LOCK_GUARD_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/reentrant_rw_lock.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_REENTRANT_RW_LOCK_H_
#define CYBER_BASE_REENTRANT_RW_LOCK_H_
#include <unistd.h>
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <mutex>
#include <thread>
#include "cyber/base/rw_lock_guard.h"
namespace apollo {
namespace cyber {
namespace base {
static const std::thread::id NULL_THREAD_ID = std::thread::id();
class ReentrantRWLock {
friend class ReadLockGuard<ReentrantRWLock>;
friend class WriteLockGuard<ReentrantRWLock>;
public:
static const int32_t RW_LOCK_FREE = 0;
static const int32_t WRITE_EXCLUSIVE = -1;
static const uint32_t MAX_RETRY_TIMES = 5;
static const std::thread::id null_thread;
ReentrantRWLock() {}
explicit ReentrantRWLock(bool write_first) : write_first_(write_first) {}
private:
// all these function only can used by ReadLockGuard/WriteLockGuard;
void ReadLock();
void WriteLock();
void ReadUnlock();
void WriteUnlock();
ReentrantRWLock(const ReentrantRWLock&) = delete;
ReentrantRWLock& operator=(const ReentrantRWLock&) = delete;
std::thread::id write_thread_id_ = {NULL_THREAD_ID};
std::atomic<uint32_t> write_lock_wait_num_ = {0};
std::atomic<int32_t> lock_num_ = {0};
bool write_first_ = true;
};
inline void ReentrantRWLock::ReadLock() {
if (write_thread_id_ == std::this_thread::get_id()) {
return;
}
uint32_t retry_times = 0;
int32_t lock_num = lock_num_.load(std::memory_order_acquire);
if (write_first_) {
do {
while (lock_num < RW_LOCK_FREE ||
write_lock_wait_num_.load(std::memory_order_acquire) > 0) {
if (++retry_times == MAX_RETRY_TIMES) {
// saving cpu
std::this_thread::yield();
retry_times = 0;
}
lock_num = lock_num_.load(std::memory_order_acquire);
}
} while (!lock_num_.compare_exchange_weak(lock_num, lock_num + 1,
std::memory_order_acq_rel,
std::memory_order_relaxed));
} else {
do {
while (lock_num < RW_LOCK_FREE) {
if (++retry_times == MAX_RETRY_TIMES) {
// saving cpu
std::this_thread::yield();
retry_times = 0;
}
lock_num = lock_num_.load(std::memory_order_acquire);
}
} while (!lock_num_.compare_exchange_weak(lock_num, lock_num + 1,
std::memory_order_acq_rel,
std::memory_order_relaxed));
}
}
inline void ReentrantRWLock::WriteLock() {
auto this_thread_id = std::this_thread::get_id();
if (write_thread_id_ == this_thread_id) {
lock_num_.fetch_sub(1);
return;
}
int32_t rw_lock_free = RW_LOCK_FREE;
uint32_t retry_times = 0;
write_lock_wait_num_.fetch_add(1);
while (!lock_num_.compare_exchange_weak(rw_lock_free, WRITE_EXCLUSIVE,
std::memory_order_acq_rel,
std::memory_order_relaxed)) {
// rw_lock_free will change after CAS fail, so init agin
rw_lock_free = RW_LOCK_FREE;
if (++retry_times == MAX_RETRY_TIMES) {
// saving cpu
std::this_thread::yield();
retry_times = 0;
}
}
write_thread_id_ = this_thread_id;
write_lock_wait_num_.fetch_sub(1);
}
inline void ReentrantRWLock::ReadUnlock() {
if (write_thread_id_ == std::this_thread::get_id()) {
return;
}
lock_num_.fetch_sub(1);
}
inline void ReentrantRWLock::WriteUnlock() {
if (lock_num_.fetch_add(1) == WRITE_EXCLUSIVE) {
write_thread_id_ = NULL_THREAD_ID;
}
}
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_REENTRANT_RW_LOCK_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/atomic_hash_map_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/base/atomic_hash_map.h"
#include <string>
#include <thread>
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace base {
TEST(AtomicHashMapTest, int_int) {
AtomicHashMap<int, int> map;
int value = 0;
for (int i = 0; i < 1000; i++) {
map.Set(i, i);
EXPECT_TRUE(map.Has(i));
EXPECT_TRUE(map.Get(i, &value));
EXPECT_EQ(i, value);
}
for (int i = 0; i < 1000; i++) {
map.Set(1000 - i, i);
EXPECT_TRUE(map.Has(1000 - i));
EXPECT_TRUE(map.Get(1000 - i, &value));
EXPECT_EQ(i, value);
}
}
TEST(AtomicHashMapTest, int_str) {
AtomicHashMap<int, std::string> map;
std::string value("");
for (int i = 0; i < 1000; i++) {
map.Set(i, std::to_string(i));
EXPECT_TRUE(map.Has(i));
EXPECT_TRUE(map.Get(i, &value));
EXPECT_EQ(std::to_string(i), value);
}
map.Set(100);
EXPECT_TRUE(map.Get(100, &value));
EXPECT_TRUE(value.empty());
map.Set(100, std::move(std::string("test")));
EXPECT_TRUE(map.Get(100, &value));
EXPECT_EQ("test", value);
}
TEST(AtomicHashMapTest, concurrency) {
AtomicHashMap<int, std::string, 128> map;
int thread_num = 32;
std::thread t[32];
volatile bool ready = false;
for (int i = 0; i < thread_num; i++) {
t[i] = std::thread([&, i]() {
while (!ready) {
#if defined(__aarch64__)
asm volatile("yield" ::: "memory");
#else
asm volatile("rep; nop" ::: "memory");
#endif
}
for (int j = 0; j < thread_num * 1024; j++) {
auto j_str = std::to_string(j);
map.Set(j);
map.Set(j, j_str);
map.Set(j, std::move(std::to_string(j)));
}
});
}
ready = true;
for (int i = 0; i < thread_num; i++) {
t[i].join();
}
std::string value("");
for (int i = 1; i < thread_num * 1000; i++) {
EXPECT_TRUE(map.Get(i, &value));
EXPECT_EQ(std::to_string(i), value);
}
std::string* str = nullptr;
EXPECT_TRUE(map.Get(0, &str));
EXPECT_EQ("0", *str);
}
} // namespace base
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/object_pool_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/base/object_pool.h"
#include <thread>
#include "gtest/gtest.h"
#include "cyber/base/concurrent_object_pool.h"
namespace apollo {
namespace cyber {
namespace base {
struct TestNode {
TestNode() : inited(true) {}
~TestNode() {
inited = false;
value = 1;
}
explicit TestNode(int data) : value(data), inited(true) {}
int value = 0;
bool inited = false;
};
TEST(CCObjectPoolTest, base) {
const uint32_t capacity = 1024;
std::vector<std::shared_ptr<TestNode>> vec;
vec.reserve(capacity);
auto pool = std::make_shared<CCObjectPool<TestNode>>(capacity);
FOR_EACH(i, 0, capacity) {
auto obj = pool->ConstructObject(i);
vec.push_back(obj);
EXPECT_EQ(i, obj->value);
}
FOR_EACH(i, 0, 10) { EXPECT_EQ(nullptr, pool->ConstructObject(10)); }
vec.clear();
EXPECT_EQ(10, pool->ConstructObject(10)->value);
pool.reset();
}
TEST(CCObjectPoolTest, multi_thread) {
const uint32_t capacity = 1024;
std::vector<std::shared_ptr<TestNode>> vec;
std::vector<std::thread> thread_pool;
vec.reserve(capacity);
auto pool = std::make_shared<CCObjectPool<TestNode>>(capacity);
FOR_EACH(i, 0, 16) {
thread_pool.emplace_back([pool]() {
FOR_EACH(i, 0, 100000) { pool->ConstructObject(10); }
});
}
for (auto& thread : thread_pool) {
thread.join();
}
FOR_EACH(i, 0, capacity) {
auto obj = pool->ConstructObject(i);
vec.push_back(obj);
EXPECT_EQ(i, obj->value);
}
FOR_EACH(i, 0, 10) { EXPECT_EQ(nullptr, pool->ConstructObject(10)); }
vec.clear();
}
TEST(CCObjectPoolTest, construct_object) {
const uint32_t capacity = 1024;
auto pool = std::make_shared<CCObjectPool<TestNode>>(capacity);
std::vector<std::shared_ptr<TestNode>> vec;
FOR_EACH(i, 0, capacity) {
auto obj = pool->ConstructObject(i);
vec.push_back(obj);
EXPECT_TRUE(obj->inited);
EXPECT_EQ(i, obj->value);
}
vec.clear();
}
TEST(CCObjectPoolTest, construct_all) {
const uint32_t capacity = 1024;
std::vector<std::shared_ptr<TestNode>> vec;
auto pool = std::make_shared<CCObjectPool<TestNode>>(capacity);
pool->ConstructAll();
FOR_EACH(i, 0, capacity) {
auto obj = pool->GetObject();
vec.push_back(obj);
EXPECT_TRUE(obj->inited);
}
vec.clear();
}
TEST(ObjectPoolTest, get_object) {
auto pool = std::make_shared<ObjectPool<TestNode>>(100, 10);
FOR_EACH(i, 0, 10) { EXPECT_EQ(10, pool->GetObject()->value); }
EXPECT_NE(nullptr, pool->GetObject());
pool.reset();
auto pool2 = std::make_shared<ObjectPool<TestNode>>(10);
FOR_EACH(i, 0, 10) { EXPECT_EQ(0, pool2->GetObject()->value); }
EXPECT_NE(nullptr, pool2->GetObject());
pool2.reset();
}
} // namespace base
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/bounded_queue_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/base/bounded_queue.h"
#include <thread>
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace base {
TEST(BoundedQueueTest, Enqueue) {
BoundedQueue<int> queue;
queue.Init(100);
EXPECT_EQ(0, queue.Size());
EXPECT_TRUE(queue.Empty());
for (int i = 1; i <= 100; i++) {
EXPECT_TRUE(queue.Enqueue(i));
EXPECT_EQ(i, queue.Size());
}
EXPECT_FALSE(queue.Enqueue(101));
}
TEST(BoundedQueueTest, Dequeue) {
BoundedQueue<int> queue;
queue.Init(100);
int value = 0;
for (int i = 0; i < 100; i++) {
EXPECT_TRUE(queue.Enqueue(i));
EXPECT_TRUE(queue.Dequeue(&value));
EXPECT_EQ(i, value);
}
EXPECT_FALSE(queue.Dequeue(&value));
}
TEST(BoundedQueueTest, concurrency) {
BoundedQueue<int> queue;
queue.Init(10);
std::atomic_int count = {0};
std::thread threads[48];
for (int i = 0; i < 48; ++i) {
if (i % 4 == 0) {
threads[i] = std::thread([&]() {
for (int j = 0; j < 10000; ++j) {
if (queue.Enqueue(j)) {
count++;
}
}
});
} else if (i % 4 == 1) {
threads[i] = std::thread([&]() {
for (int j = 0; j < 10000; ++j) {
if (queue.WaitEnqueue(j)) {
count++;
}
}
});
} else if (i % 4 == 2) {
threads[i] = std::thread([&]() {
for (int j = 0; j < 10000; ++j) {
int value = 0;
if (queue.Dequeue(&value)) {
count--;
}
}
});
} else {
threads[i] = std::thread([&]() {
for (int j = 0; j < 10000; ++j) {
int value = 0;
if (queue.WaitDequeue(&value)) {
count--;
}
}
});
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(200));
queue.BreakAllWait();
for (int i = 0; i < 48; ++i) {
threads[i].join();
}
EXPECT_EQ(count.load(), queue.Size());
}
TEST(BoundedQueueTest, WaitDequeue) {
BoundedQueue<int> queue;
queue.Init(100);
queue.Enqueue(10);
std::thread t([&]() {
int value = 0;
queue.WaitDequeue(&value);
EXPECT_EQ(10, value);
queue.WaitDequeue(&value);
EXPECT_EQ(100, value);
});
queue.Enqueue(100);
t.join();
}
TEST(BoundedQueueTest, block_wait) {
BoundedQueue<int> queue;
queue.Init(100, new BlockWaitStrategy());
std::thread t([&]() {
int value = 0;
queue.WaitDequeue(&value);
EXPECT_EQ(100, value);
});
queue.Enqueue(100);
t.join();
}
TEST(BoundedQueueTest, yield_wait) {
BoundedQueue<int> queue;
queue.Init(100, new YieldWaitStrategy());
std::thread t([&]() {
int value = 0;
queue.WaitDequeue(&value);
EXPECT_EQ(100, value);
});
queue.Enqueue(100);
t.join();
}
TEST(BoundedQueueTest, spin_wait) {
BoundedQueue<int> queue;
queue.Init(100, new BusySpinWaitStrategy());
std::thread t([&]() {
int value = 0;
queue.WaitDequeue(&value);
EXPECT_EQ(100, value);
});
queue.Enqueue(100);
t.join();
}
TEST(BoundedQueueTest, busy_wait) {
BoundedQueue<int> queue;
queue.Init(100, new BusySpinWaitStrategy());
std::thread t([&]() {
int value = 0;
queue.WaitDequeue(&value);
EXPECT_EQ(100, value);
});
queue.Enqueue(100);
t.join();
}
} // namespace base
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/atomic_hash_map.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_ATOMIC_HASH_MAP_H_
#define CYBER_BASE_ATOMIC_HASH_MAP_H_
#include <atomic>
#include <cstdint>
#include <type_traits>
#include <utility>
namespace apollo {
namespace cyber {
namespace base {
/**
* @brief A implementation of lock-free fixed size hash map
*
* @tparam K Type of key, must be integral
* @tparam V Type of value
* @tparam 128 Size of hash table
* @tparam 0 Type traits, use for checking types of key & value
*/
template <typename K, typename V, std::size_t TableSize = 128,
typename std::enable_if<std::is_integral<K>::value &&
(TableSize & (TableSize - 1)) == 0,
int>::type = 0>
class AtomicHashMap {
public:
AtomicHashMap() : capacity_(TableSize), mode_num_(capacity_ - 1) {}
AtomicHashMap(const AtomicHashMap &other) = delete;
AtomicHashMap &operator=(const AtomicHashMap &other) = delete;
bool Has(K key) {
uint64_t index = key & mode_num_;
return table_[index].Has(key);
}
bool Get(K key, V **value) {
uint64_t index = key & mode_num_;
return table_[index].Get(key, value);
}
bool Get(K key, V *value) {
uint64_t index = key & mode_num_;
V *val = nullptr;
bool res = table_[index].Get(key, &val);
if (res) {
*value = *val;
}
return res;
}
void Set(K key) {
uint64_t index = key & mode_num_;
table_[index].Insert(key);
}
void Set(K key, const V &value) {
uint64_t index = key & mode_num_;
table_[index].Insert(key, value);
}
void Set(K key, V &&value) {
uint64_t index = key & mode_num_;
table_[index].Insert(key, std::forward<V>(value));
}
private:
struct Entry {
Entry() {}
explicit Entry(K key) : key(key) {
value_ptr.store(new V(), std::memory_order_release);
}
Entry(K key, const V &value) : key(key) {
value_ptr.store(new V(value), std::memory_order_release);
}
Entry(K key, V &&value) : key(key) {
value_ptr.store(new V(std::forward<V>(value)), std::memory_order_release);
}
~Entry() { delete value_ptr.load(std::memory_order_acquire); }
K key = 0;
std::atomic<V *> value_ptr = {nullptr};
std::atomic<Entry *> next = {nullptr};
};
class Bucket {
public:
Bucket() : head_(new Entry()) {}
~Bucket() {
Entry *ite = head_;
while (ite) {
auto tmp = ite->next.load(std::memory_order_acquire);
delete ite;
ite = tmp;
}
}
bool Has(K key) {
Entry *m_target = head_->next.load(std::memory_order_acquire);
while (Entry *target = m_target) {
if (target->key < key) {
m_target = target->next.load(std::memory_order_acquire);
continue;
} else {
return target->key == key;
}
}
return false;
}
bool Find(K key, Entry **prev_ptr, Entry **target_ptr) {
Entry *prev = head_;
Entry *m_target = head_->next.load(std::memory_order_acquire);
while (Entry *target = m_target) {
if (target->key == key) {
*prev_ptr = prev;
*target_ptr = target;
return true;
} else if (target->key > key) {
*prev_ptr = prev;
*target_ptr = target;
return false;
} else {
prev = target;
m_target = target->next.load(std::memory_order_acquire);
}
}
*prev_ptr = prev;
*target_ptr = nullptr;
return false;
}
void Insert(K key, const V &value) {
Entry *prev = nullptr;
Entry *target = nullptr;
Entry *new_entry = nullptr;
V *new_value = nullptr;
while (true) {
if (Find(key, &prev, &target)) {
// key exists, update value
if (!new_value) {
new_value = new V(value);
}
auto old_val_ptr = target->value_ptr.load(std::memory_order_acquire);
if (target->value_ptr.compare_exchange_strong(
old_val_ptr, new_value, std::memory_order_acq_rel,
std::memory_order_relaxed)) {
delete old_val_ptr;
if (new_entry) {
delete new_entry;
new_entry = nullptr;
}
return;
}
continue;
} else {
if (!new_entry) {
new_entry = new Entry(key, value);
}
new_entry->next.store(target, std::memory_order_release);
if (prev->next.compare_exchange_strong(target, new_entry,
std::memory_order_acq_rel,
std::memory_order_relaxed)) {
// Insert success
if (new_value) {
delete new_value;
new_value = nullptr;
}
return;
}
// another entry has been inserted, retry
}
}
}
void Insert(K key, V &&value) {
Entry *prev = nullptr;
Entry *target = nullptr;
Entry *new_entry = nullptr;
V *new_value = nullptr;
while (true) {
if (Find(key, &prev, &target)) {
// key exists, update value
if (!new_value) {
new_value = new V(std::forward<V>(value));
}
auto old_val_ptr = target->value_ptr.load(std::memory_order_acquire);
if (target->value_ptr.compare_exchange_strong(
old_val_ptr, new_value, std::memory_order_acq_rel,
std::memory_order_relaxed)) {
delete old_val_ptr;
if (new_entry) {
delete new_entry;
new_entry = nullptr;
}
return;
}
continue;
} else {
if (!new_entry) {
new_entry = new Entry(key, value);
}
new_entry->next.store(target, std::memory_order_release);
if (prev->next.compare_exchange_strong(target, new_entry,
std::memory_order_acq_rel,
std::memory_order_relaxed)) {
// Insert success
if (new_value) {
delete new_value;
new_value = nullptr;
}
return;
}
// another entry has been inserted, retry
}
}
}
void Insert(K key) {
Entry *prev = nullptr;
Entry *target = nullptr;
Entry *new_entry = nullptr;
V *new_value = nullptr;
while (true) {
if (Find(key, &prev, &target)) {
// key exists, update value
if (!new_value) {
new_value = new V();
}
auto old_val_ptr = target->value_ptr.load(std::memory_order_acquire);
if (target->value_ptr.compare_exchange_strong(
old_val_ptr, new_value, std::memory_order_acq_rel,
std::memory_order_relaxed)) {
delete old_val_ptr;
if (new_entry) {
delete new_entry;
new_entry = nullptr;
}
return;
}
continue;
} else {
if (!new_entry) {
new_entry = new Entry(key);
}
new_entry->next.store(target, std::memory_order_release);
if (prev->next.compare_exchange_strong(target, new_entry,
std::memory_order_acq_rel,
std::memory_order_relaxed)) {
// Insert success
if (new_value) {
delete new_value;
new_value = nullptr;
}
return;
}
// another entry has been inserted, retry
}
}
}
bool Get(K key, V **value) {
Entry *prev = nullptr;
Entry *target = nullptr;
if (Find(key, &prev, &target)) {
*value = target->value_ptr.load(std::memory_order_acquire);
return true;
}
return false;
}
Entry *head_;
};
private:
Bucket table_[TableSize];
uint64_t capacity_;
uint64_t mode_num_;
};
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_ATOMIC_HASH_MAP_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/unbounded_queue.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_UNBOUNDED_QUEUE_H_
#define CYBER_BASE_UNBOUNDED_QUEUE_H_
#include <unistd.h>
#include <atomic>
#include <cstdint>
#include <memory>
namespace apollo {
namespace cyber {
namespace base {
template <typename T>
class UnboundedQueue {
public:
UnboundedQueue() { Reset(); }
UnboundedQueue& operator=(const UnboundedQueue& other) = delete;
UnboundedQueue(const UnboundedQueue& other) = delete;
~UnboundedQueue() { Destroy(); }
void Clear() {
Destroy();
Reset();
}
void Enqueue(const T& element) {
auto node = new Node();
node->data = element;
Node* old_tail = tail_.load();
while (true) {
if (tail_.compare_exchange_strong(old_tail, node)) {
old_tail->next = node;
old_tail->release();
size_.fetch_add(1);
break;
}
}
}
bool Dequeue(T* element) {
Node* old_head = head_.load();
Node* head_next = nullptr;
do {
head_next = old_head->next;
if (head_next == nullptr) {
return false;
}
} while (!head_.compare_exchange_strong(old_head, head_next));
*element = head_next->data;
size_.fetch_sub(1);
old_head->release();
return true;
}
size_t Size() { return size_.load(); }
bool Empty() { return size_.load() == 0; }
private:
struct Node {
T data;
std::atomic<uint32_t> ref_count;
Node* next = nullptr;
Node() { ref_count.store(2); }
void release() {
ref_count.fetch_sub(1);
if (ref_count.load() == 0) {
delete this;
}
}
};
void Reset() {
auto node = new Node();
head_.store(node);
tail_.store(node);
size_.store(0);
}
void Destroy() {
auto ite = head_.load();
Node* tmp = nullptr;
while (ite != nullptr) {
tmp = ite->next;
delete ite;
ite = tmp;
}
}
std::atomic<Node*> head_;
std::atomic<Node*> tail_;
std::atomic<size_t> size_;
};
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_UNBOUNDED_QUEUE_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/wait_strategy.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_WAIT_STRATEGY_H_
#define CYBER_BASE_WAIT_STRATEGY_H_
#include <chrono>
#include <condition_variable>
#include <cstdlib>
#include <mutex>
#include <thread>
namespace apollo {
namespace cyber {
namespace base {
class WaitStrategy {
public:
virtual void NotifyOne() {}
virtual void BreakAllWait() {}
virtual bool EmptyWait() = 0;
virtual ~WaitStrategy() {}
};
class BlockWaitStrategy : public WaitStrategy {
public:
BlockWaitStrategy() {}
void NotifyOne() override { cv_.notify_one(); }
bool EmptyWait() override {
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock);
return true;
}
void BreakAllWait() override { cv_.notify_all(); }
private:
std::mutex mutex_;
std::condition_variable cv_;
};
class SleepWaitStrategy : public WaitStrategy {
public:
SleepWaitStrategy() {}
explicit SleepWaitStrategy(uint64_t sleep_time_us)
: sleep_time_us_(sleep_time_us) {}
bool EmptyWait() override {
std::this_thread::sleep_for(std::chrono::microseconds(sleep_time_us_));
return true;
}
void SetSleepTimeMicroSeconds(uint64_t sleep_time_us) {
sleep_time_us_ = sleep_time_us;
}
private:
uint64_t sleep_time_us_ = 10000;
};
class YieldWaitStrategy : public WaitStrategy {
public:
YieldWaitStrategy() {}
bool EmptyWait() override {
std::this_thread::yield();
return true;
}
};
class BusySpinWaitStrategy : public WaitStrategy {
public:
BusySpinWaitStrategy() {}
bool EmptyWait() override { return true; }
};
class TimeoutBlockWaitStrategy : public WaitStrategy {
public:
TimeoutBlockWaitStrategy() {}
explicit TimeoutBlockWaitStrategy(uint64_t timeout)
: time_out_(std::chrono::milliseconds(timeout)) {}
void NotifyOne() override { cv_.notify_one(); }
bool EmptyWait() override {
std::unique_lock<std::mutex> lock(mutex_);
if (cv_.wait_for(lock, time_out_) == std::cv_status::timeout) {
return false;
}
return true;
}
void BreakAllWait() override { cv_.notify_all(); }
void SetTimeout(uint64_t timeout) {
time_out_ = std::chrono::milliseconds(timeout);
}
private:
std::mutex mutex_;
std::condition_variable cv_;
std::chrono::milliseconds time_out_;
};
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_WAIT_STRATEGY_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/base/bounded_queue.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_BASE_BOUNDED_QUEUE_H_
#define CYBER_BASE_BOUNDED_QUEUE_H_
#include <unistd.h>
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstdlib>
#include <memory>
#include <utility>
#include "cyber/base/macros.h"
#include "cyber/base/wait_strategy.h"
namespace apollo {
namespace cyber {
namespace base {
template <typename T>
class BoundedQueue {
public:
using value_type = T;
using size_type = uint64_t;
public:
BoundedQueue() {}
BoundedQueue& operator=(const BoundedQueue& other) = delete;
BoundedQueue(const BoundedQueue& other) = delete;
~BoundedQueue();
bool Init(uint64_t size);
bool Init(uint64_t size, WaitStrategy* strategy);
bool Enqueue(const T& element);
bool Enqueue(T&& element);
bool WaitEnqueue(const T& element);
bool WaitEnqueue(T&& element);
bool Dequeue(T* element);
bool WaitDequeue(T* element);
uint64_t Size();
bool Empty();
void SetWaitStrategy(WaitStrategy* WaitStrategy);
void BreakAllWait();
uint64_t Head() { return head_.load(); }
uint64_t Tail() { return tail_.load(); }
uint64_t Commit() { return commit_.load(); }
private:
uint64_t GetIndex(uint64_t num);
alignas(CACHELINE_SIZE) std::atomic<uint64_t> head_ = {0};
alignas(CACHELINE_SIZE) std::atomic<uint64_t> tail_ = {1};
alignas(CACHELINE_SIZE) std::atomic<uint64_t> commit_ = {1};
// alignas(CACHELINE_SIZE) std::atomic<uint64_t> size_ = {0};
uint64_t pool_size_ = 0;
T* pool_ = nullptr;
std::unique_ptr<WaitStrategy> wait_strategy_ = nullptr;
volatile bool break_all_wait_ = false;
};
template <typename T>
BoundedQueue<T>::~BoundedQueue() {
if (wait_strategy_) {
BreakAllWait();
}
if (pool_) {
for (uint64_t i = 0; i < pool_size_; ++i) {
pool_[i].~T();
}
std::free(pool_);
}
}
template <typename T>
inline bool BoundedQueue<T>::Init(uint64_t size) {
return Init(size, new SleepWaitStrategy());
}
template <typename T>
bool BoundedQueue<T>::Init(uint64_t size, WaitStrategy* strategy) {
// Head and tail each occupy a space
pool_size_ = size + 2;
pool_ = reinterpret_cast<T*>(std::calloc(pool_size_, sizeof(T)));
if (pool_ == nullptr) {
return false;
}
for (uint64_t i = 0; i < pool_size_; ++i) {
new (&(pool_[i])) T();
}
wait_strategy_.reset(strategy);
return true;
}
template <typename T>
bool BoundedQueue<T>::Enqueue(const T& element) {
uint64_t new_tail = 0;
uint64_t old_commit = 0;
uint64_t old_tail = tail_.load(std::memory_order_acquire);
do {
new_tail = old_tail + 1;
if (GetIndex(new_tail) == GetIndex(head_.load(std::memory_order_acquire))) {
return false;
}
} while (!tail_.compare_exchange_weak(old_tail, new_tail,
std::memory_order_acq_rel,
std::memory_order_relaxed));
pool_[GetIndex(old_tail)] = element;
do {
old_commit = old_tail;
} while (cyber_unlikely(!commit_.compare_exchange_weak(
old_commit, new_tail, std::memory_order_acq_rel,
std::memory_order_relaxed)));
wait_strategy_->NotifyOne();
return true;
}
template <typename T>
bool BoundedQueue<T>::Enqueue(T&& element) {
uint64_t new_tail = 0;
uint64_t old_commit = 0;
uint64_t old_tail = tail_.load(std::memory_order_acquire);
do {
new_tail = old_tail + 1;
if (GetIndex(new_tail) == GetIndex(head_.load(std::memory_order_acquire))) {
return false;
}
} while (!tail_.compare_exchange_weak(old_tail, new_tail,
std::memory_order_acq_rel,
std::memory_order_relaxed));
pool_[GetIndex(old_tail)] = std::move(element);
do {
old_commit = old_tail;
} while (cyber_unlikely(!commit_.compare_exchange_weak(
old_commit, new_tail, std::memory_order_acq_rel,
std::memory_order_relaxed)));
wait_strategy_->NotifyOne();
return true;
}
template <typename T>
bool BoundedQueue<T>::Dequeue(T* element) {
uint64_t new_head = 0;
uint64_t old_head = head_.load(std::memory_order_acquire);
do {
new_head = old_head + 1;
if (new_head == commit_.load(std::memory_order_acquire)) {
return false;
}
*element = pool_[GetIndex(new_head)];
} while (!head_.compare_exchange_weak(old_head, new_head,
std::memory_order_acq_rel,
std::memory_order_relaxed));
return true;
}
template <typename T>
bool BoundedQueue<T>::WaitEnqueue(const T& element) {
while (!break_all_wait_) {
if (Enqueue(element)) {
return true;
}
if (wait_strategy_->EmptyWait()) {
continue;
}
// wait timeout
break;
}
return false;
}
template <typename T>
bool BoundedQueue<T>::WaitEnqueue(T&& element) {
while (!break_all_wait_) {
if (Enqueue(std::move(element))) {
return true;
}
if (wait_strategy_->EmptyWait()) {
continue;
}
// wait timeout
break;
}
return false;
}
template <typename T>
bool BoundedQueue<T>::WaitDequeue(T* element) {
while (!break_all_wait_) {
if (Dequeue(element)) {
return true;
}
if (wait_strategy_->EmptyWait()) {
continue;
}
// wait timeout
break;
}
return false;
}
template <typename T>
inline uint64_t BoundedQueue<T>::Size() {
return tail_ - head_ - 1;
}
template <typename T>
inline bool BoundedQueue<T>::Empty() {
return Size() == 0;
}
template <typename T>
inline uint64_t BoundedQueue<T>::GetIndex(uint64_t num) {
return num - (num / pool_size_) * pool_size_; // faster than %
}
template <typename T>
inline void BoundedQueue<T>::SetWaitStrategy(WaitStrategy* strategy) {
wait_strategy_.reset(strategy);
}
template <typename T>
inline void BoundedQueue<T>::BreakAllWait() {
break_all_wait_ = true;
wait_strategy_->BreakAllWait();
}
} // namespace base
} // namespace cyber
} // namespace apollo
#endif // CYBER_BASE_BOUNDED_QUEUE_H_
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/tools/bootstrap.py
|
#! /usr/bin/env python3
# ****************************************************************************
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#
# ==============================================================================
# -*- coding: utf-8 -*-
"""Script to get build parameters interactively from user.
Adapted significantly from tensorflow.git/configure.py .
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import platform
import re
import subprocess
import sys
from distutils.util import (strtobool)
# pylint: disable=g-import-not-at-top
try:
from shutil import which
except ImportError:
from distutils.spawn import find_executable as which
# pylint: enable=g-import-not-at-top
_DEFAULT_CUDA_VERSION = '10'
_DEFAULT_CUDNN_VERSION = '7'
_DEFAULT_TENSORRT_VERSION = '7'
_DEFAULT_MIGRAPHX_VERSION = '2'
_DEFAULT_CUDA_COMPUTE_CAPABILITIES = '3.7,5.2,6.0,6.1,7.0,7.2,7.5'
_DEFAULT_ROCM_COMPUTE_CAPABILITIES = 'gfx900,gfx906'
_DEFAULT_PYTHON_LIB_PATH = '/usr/lib/python3/dist-packages'
_DEFAULT_PROMPT_ASK_ATTEMPTS = 3
_APOLLO_ROOT_DIR = ''
_APOLLO_BAZELRC = '.apollo.bazelrc'
_APOLLO_CURRENT_BAZEL_VERSION = None
_APOLLO_MIN_BAZEL_VERSION = '2.0.0'
_APOLLO_INSIDE_DOCKER = True
_APOLLO_DOCKER_STAGE = "dev"
_INTERACTIVE_MODE = True
class color:
GREEN = '\033[32m'
RED = '\033[0;31m'
BLUE = '\033[1;34;48m'
YELLOW = '\033[33m'
NO_COLOR = '\033[0m'
_INFO = '[' + color.BLUE + 'INFO' + color.NO_COLOR + '] '
_WARNING = color.YELLOW + '[WARNING] ' + color.NO_COLOR
_ERROR = '[' + color.RED + 'ERROR' + color.NO_COLOR + '] '
class UserInputError(Exception):
pass
def is_linux():
return platform.system() == 'Linux'
def inside_docker():
return os.path.isfile('/.dockerenv')
def docker_stage():
default_apollo_stage = "dev"
if not inside_docker():
return default_apollo_stage
stage_conf = "/etc/apollo.conf"
if not os.path.exists(stage_conf) or not os.path.isfile(stage_conf):
return default_apollo_stage
with open("/etc/apollo.conf") as f:
for line in f:
line = line.strip()
if line.startswith("stage="):
return line.split("=")[-1]
return default_apollo_stage
def default_root_dir():
current_dir = os.path.dirname(__file__)
if len(current_dir) == 0:
current_dir = '.'
return os.path.abspath(os.path.join(current_dir, '..'))
def get_input(question):
try:
try:
answer = raw_input(question)
except NameError:
answer = input(question) # pylint: disable=bad-builtin
except EOFError:
answer = ''
return answer
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def write_to_bazelrc(line):
with open(_APOLLO_BAZELRC, 'a') as f:
f.write(line + '\n')
def write_blank_line_to_bazelrc():
with open(_APOLLO_BAZELRC, 'a') as f:
f.write('\n')
def write_action_env_to_bazelrc(var_name, var):
write_to_bazelrc('build --action_env {}="{}"'.format(var_name, str(var)))
def write_build_var_to_bazelrc(bazel_config_name, option_name):
# TODO(build): Migrate all users of configure.py to use --config Bazel
# options and not to set build configs through environment variables.
write_to_bazelrc('build:%s --define %s=true' % (bazel_config_name,
option_name))
def run_shell(cmd, allow_non_zero=False, stderr=None):
if stderr is None:
stderr = sys.stdout
if allow_non_zero:
try:
output = subprocess.check_output(cmd, stderr=stderr)
except subprocess.CalledProcessError as e:
output = e.output
else:
output = subprocess.check_output(cmd, stderr=stderr)
return output.decode("UTF-8").strip()
def get_python_path(environ_cp, python_bin_path):
"""Get the python site package paths."""
python_paths = []
if environ_cp.get('PYTHONPATH'):
python_paths = environ_cp.get('PYTHONPATH').split(':')
try:
stderr = open(os.devnull, 'wb')
library_paths = run_shell(
[
python_bin_path, '-c',
'import site; print("\\n".join(site.getsitepackages()))'
],
stderr=stderr).split('\n')
except subprocess.CalledProcessError:
library_paths = [
run_shell([
python_bin_path, '-c',
'from distutils.sysconfig import get_python_lib;'
'print(get_python_lib())'
])
]
all_paths = set(python_paths + library_paths)
paths = []
for path in all_paths:
if os.path.isdir(path) and not path.startswith(
os.path.join(_APOLLO_ROOT_DIR, "bazel-bin")):
paths.append(path)
return paths
def get_python_major_version(python_bin_path):
"""Get the python major version."""
return run_shell(
[python_bin_path, '-c', 'import sys; print(sys.version[0])'])
def setup_common_dirs(environ_cp):
"""Setup --distdir and --output_user_root directories"""
cache_dir = os.path.join(_APOLLO_ROOT_DIR, '.cache')
dist_dir = os.path.join(_APOLLO_ROOT_DIR, '.cache/distdir')
# if cyber/setup.bash not sourced
if 'APOLLO_CACHE_DIR' in environ_cp:
cache_dir = environ_cp['APOLLO_CACHE_DIR']
if 'APOLLO_BAZEL_DIST_DIR' in environ_cp:
dist_dir = environ_cp['APOLLO_BAZEL_DIST_DIR']
write_to_bazelrc('startup --output_user_root="{}/bazel"'.format(cache_dir))
write_to_bazelrc('common --distdir="{}"'.format(dist_dir))
write_to_bazelrc('common --repository_cache="{}/repos"'.format(cache_dir))
write_to_bazelrc('build --disk_cache="{}/build"'.format(cache_dir))
write_to_bazelrc('')
def setup_python(environ_cp):
"""Setup python related env variables."""
if not _INTERACTIVE_MODE:
setup_python_non_interactively(environ_cp)
else:
setup_python_interactively(environ_cp)
def setup_python_non_interactively(environ_cp):
"""Setup python related env variables non-interactively."""
# Get PYTHON_BIN_PATH, default is the current running python.
python_bin_path = sys.executable
if not os.path.exists(python_bin_path):
print((_ERROR + 'Invalid python path: {} cannot be found.').format(
python_bin_path))
sys.exit(1)
if not os.path.isfile(python_bin_path) or not os.access(
python_bin_path, os.X_OK):
print((_ERROR + '{} is not executable.').format(python_bin_path))
sys.exit(1)
python_major_version = get_python_major_version(python_bin_path)
if python_major_version != '3':
print(_ERROR + 'Python 2 was retired on April 2020. Use Python 3 instead.')
sys.exit(1)
environ_cp['PYTHON_BIN_PATH'] = python_bin_path
# Get PYTHON_LIB_PATH
python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
if not python_lib_path:
python_lib_paths = get_python_path(environ_cp, python_bin_path)
print(_INFO + ('Found possible ' + color.GREEN + 'Python' + color.NO_COLOR + ' library paths:\n %s') %
'\n '.join(python_lib_paths))
if _DEFAULT_PYTHON_LIB_PATH in python_lib_paths:
default_python_lib_path = _DEFAULT_PYTHON_LIB_PATH
else:
default_python_lib_path = python_lib_paths[0]
python_lib_path = default_python_lib_path
# Set-up env variables used by python_configure.bzl
write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
write_to_bazelrc('build --python_path=\"{}\"'.format(python_bin_path))
# If choosen python_lib_path is from a path specified in the PYTHONPATH
# variable, need to tell bazel to include PYTHONPATH
if environ_cp.get('PYTHONPATH'):
python_paths = environ_cp.get('PYTHONPATH').split(':')
if python_lib_path in python_paths:
write_action_env_to_bazelrc('PYTHONPATH',
environ_cp.get('PYTHONPATH'))
def setup_python_interactively(environ_cp):
"""Setup python related env variables interactively."""
# Get PYTHON_BIN_PATH, default is the current running python.
default_python_bin_path = sys.executable
ask_python_bin_path = (
'Please specify the location of python. [Default is '
'{}]: ').format(default_python_bin_path)
while True:
python_bin_path = get_from_env_or_user_or_default(
environ_cp, 'PYTHON_BIN_PATH', ask_python_bin_path,
default_python_bin_path)
# Check if the path is valid
if os.path.isfile(python_bin_path) and os.access(
python_bin_path, os.X_OK):
break
elif not os.path.exists(python_bin_path):
print((_ERROR + 'Invalid python path: {} cannot be found.').format(
python_bin_path))
else:
print((_ERROR + '{} is not executable. Is it the python binary?').format(
python_bin_path))
environ_cp['PYTHON_BIN_PATH'] = ''
python_major_version = get_python_major_version(python_bin_path)
if python_major_version != '3':
print(_ERROR + 'Python 2 was Retired on April 2020. Use Python 3 instead.')
sys.exit(1)
# Get PYTHON_LIB_PATH
python_lib_path = environ_cp.get('PYTHON_LIB_PATH')
if not python_lib_path:
python_lib_paths = get_python_path(environ_cp, python_bin_path)
print(_INFO + ('Found possible Python library paths:\n %s') %
'\n '.join(python_lib_paths))
default_python_lib_path = python_lib_paths[0]
python_lib_path = get_input(
'Please input the desired Python library path to use. '
'Default is [{}]\n'.format(python_lib_paths[0]))
if not python_lib_path:
python_lib_path = default_python_lib_path
environ_cp['PYTHON_LIB_PATH'] = python_lib_path
# Set-up env variables used by python_configure.bzl
write_action_env_to_bazelrc('PYTHON_BIN_PATH', python_bin_path)
write_action_env_to_bazelrc('PYTHON_LIB_PATH', python_lib_path)
write_to_bazelrc('build --python_path=\"{}\"'.format(python_bin_path))
environ_cp['PYTHON_BIN_PATH'] = python_bin_path
# If choosen python_lib_path is from a path specified in the PYTHONPATH
# variable, need to tell bazel to include PYTHONPATH
if environ_cp.get('PYTHONPATH'):
python_paths = environ_cp.get('PYTHONPATH').split(':')
if python_lib_path in python_paths:
write_action_env_to_bazelrc('PYTHONPATH',
environ_cp.get('PYTHONPATH'))
def reset_apollo_bazelrc():
"""Reset file that contains customized config settings."""
open(_APOLLO_BAZELRC, 'w').close()
def get_var(environ_cp,
var_name,
query_item,
enabled_by_default,
question=None,
yes_reply=None,
no_reply=None):
"""Get boolean input from user.
If var_name is not set in env, ask user to enable query_item or not. If the
response is empty, use the default.
Args:
environ_cp: copy of the os.environ.
var_name: string for name of environment variable, e.g. "TF_NEED_CUDA".
query_item: string for feature related to the variable, e.g. "CUDA for
Nvidia GPUs".
enabled_by_default: boolean for default behavior.
question: optional string for how to ask for user input.
yes_reply: optional string for reply when feature is enabled.
no_reply: optional string for reply when feature is disabled.
Returns:
boolean value of the variable.
Raises:
UserInputError: if an environment variable is set, but it cannot be
interpreted as a boolean indicator, assume that the user has made a
scripting error, and will continue to provide invalid input.
Raise the error to avoid infinitely looping.
"""
if not question:
question = 'Do you wish to build your project with {} support?'.format(
query_item)
if not yes_reply:
yes_reply = '{} support will be enabled for your project.'.format(
query_item)
if not no_reply:
no_reply = 'No {}'.format(yes_reply)
yes_reply += '\n'
no_reply += '\n'
if enabled_by_default:
question += ' [Y/n]: '
else:
question += ' [y/N]: '
var = environ_cp.get(var_name)
if var is not None:
var_content = var.strip().lower()
true_strings = ('1', 't', 'true', 'y', 'yes')
false_strings = ('0', 'f', 'false', 'n', 'no')
if var_content in true_strings:
var = True
elif var_content in false_strings:
var = False
else:
raise UserInputError(
'Environment variable %s must be set as a boolean indicator.\n'
'The following are accepted as TRUE : %s.\n'
'The following are accepted as FALSE: %s.\n'
'Current value is %s.' % (var_name, ', '.join(true_strings),
', '.join(false_strings), var))
while var is None:
user_input_origin = get_input(question)
user_input = user_input_origin.strip().lower()
if user_input == 'y':
print(yes_reply)
var = True
elif user_input == 'n':
print(no_reply)
var = False
elif not user_input:
if enabled_by_default:
print(yes_reply)
var = True
else:
print(no_reply)
var = False
else:
print((_ERROR + 'Invalid selection: {}').format(user_input_origin))
return var
def convert_version_to_int(version):
"""Convert a version number to a integer that can be used to compare.
Version strings of the form X.YZ and X.Y.Z-xxxxx are supported. The
'xxxxx' part, for instance 'homebrew' on OS/X, is ignored.
Args:
version: a version to be converted
Returns:
An integer if converted successfully, otherwise return None.
"""
version = version.split('-')[0]
version_segments = version.split('.')
# Treat "0.24" as "0.24.0"
if len(version_segments) == 2:
version_segments.append('0')
for seg in version_segments:
if not seg.isdigit():
return None
version_str = ''.join(['%03d' % int(seg) for seg in version_segments])
return int(version_str)
def check_bazel_version(min_version):
"""Check installed bazel version.
Args:
min_version: string for minimum bazel version (must exist!).
Returns:
The bazel version detected.
"""
if which('bazel') is None:
print(_ERROR + 'Cannot find bazel. Please install bazel first.')
sys.exit(0)
stderr = open(os.devnull, 'wb')
curr_version = run_shell(
['bazel', '--version'], allow_non_zero=True, stderr=stderr)
if curr_version.startswith('bazel '):
curr_version = curr_version.split('bazel ')[1]
min_version_int = convert_version_to_int(min_version)
curr_version_int = convert_version_to_int(curr_version)
# Check if current bazel version can be detected properly.
if not curr_version_int:
print(_WARNING + 'Current bazel installation is not a release version.')
print(' Make sure you are running at least bazel %s' % min_version)
return curr_version
print((_INFO + 'You have ' + color.GREEN + 'bazel %s' + color.NO_COLOR + ' installed.') % curr_version)
if curr_version_int < min_version_int:
print((_ERROR + 'Please upgrade your bazel installation to version %s or higher') % min_version)
sys.exit(1)
return curr_version
def get_from_env_or_user_or_default(environ_cp, var_name, ask_for_var,
var_default):
"""Get var_name either from env, or user or default.
If var_name has been set as environment variable, use the preset value, else
ask for user input. If no input is provided, the default is used.
Args:
environ_cp: copy of the os.environ.
var_name: string for name of environment variable, e.g. "TF_NEED_CUDA".
ask_for_var: string for how to ask for user input.
var_default: default value string.
Returns:
string value for var_name
"""
var = environ_cp.get(var_name)
if not var:
var = get_input(ask_for_var)
print('\n')
if not var:
var = var_default
return var
def prompt_loop_or_load_from_env(environ_cp,
var_name,
var_default,
ask_for_var,
check_success,
error_msg,
suppress_default_error=False,
resolve_symlinks=False,
n_ask_attempts=_DEFAULT_PROMPT_ASK_ATTEMPTS):
"""Loop over user prompts for an ENV param until receiving a valid response.
For the env param var_name, read from the environment or verify user input
until receiving valid input. When done, set var_name in the environ_cp to its
new value.
Args:
environ_cp: (Dict) copy of the os.environ.
var_name: (String) string for name of environment variable, e.g. "TF_MYVAR".
var_default: (String) default value string.
ask_for_var: (String) string for how to ask for user input.
check_success: (Function) function that takes one argument and returns a
boolean. Should return True if the value provided is considered valid. May
contain a complex error message if error_msg does not provide enough
information. In that case, set suppress_default_error to True.
error_msg: (String) String with one and only one '%s'. Formatted with each
invalid response upon check_success(input) failure.
suppress_default_error: (Bool) Suppress the above error message in favor of
one from the check_success function.
resolve_symlinks: (Bool) Translate symbolic links into the real filepath.
n_ask_attempts: (Integer) Number of times to query for valid input before
raising an error and quitting.
Returns:
[String] The value of var_name after querying for input.
Raises:
UserInputError: if a query has been attempted n_ask_attempts times without
success, assume that the user has made a scripting error, and will
continue to provide invalid input. Raise the error to avoid infinitely
looping.
"""
default = environ_cp.get(var_name) or var_default
full_query = '%s [Default is %s]: ' % (
ask_for_var,
default,
)
for _ in range(n_ask_attempts):
val = get_from_env_or_user_or_default(environ_cp, var_name, full_query,
default)
if check_success(val):
break
if not suppress_default_error:
print(error_msg % val)
environ_cp[var_name] = ''
else:
raise UserInputError(
'Invalid %s setting was provided %d times in a row. '
'Assuming to be a scripting mistake.' % (var_name, n_ask_attempts))
if resolve_symlinks and os.path.islink(val):
val = os.path.realpath(val)
environ_cp[var_name] = val
return val
def set_gcc_host_compiler_path(environ_cp):
"""Set GCC_HOST_COMPILER_PATH."""
default_gcc_host_compiler_path = which('gcc') or ''
cuda_bin_symlink = '%s/bin/gcc' % environ_cp.get('CUDA_TOOLKIT_PATH')
if os.path.islink(cuda_bin_symlink):
# os.readlink is only available in linux
default_gcc_host_compiler_path = os.path.realpath(cuda_bin_symlink)
if not _INTERACTIVE_MODE:
gcc_host_compiler_path = default_gcc_host_compiler_path
if os.path.islink(gcc_host_compiler_path):
gcc_host_compiler_path = os.path.realpath(gcc_host_compiler_path)
else:
gcc_host_compiler_path = prompt_loop_or_load_from_env(
environ_cp,
var_name='GCC_HOST_COMPILER_PATH',
var_default=default_gcc_host_compiler_path,
ask_for_var='Please specify which gcc should be used by nvcc as the host compiler.',
check_success=os.path.exists,
resolve_symlinks=True,
error_msg=_ERROR + 'Invalid gcc path. %s cannot be found.',
)
write_action_env_to_bazelrc('GCC_HOST_COMPILER_PATH',
gcc_host_compiler_path)
def reformat_version_sequence(version_str, sequence_count):
"""Reformat the version string to have the given number of sequences.
For example:
Given (7, 2) -> 7.0
(7.0.1, 2) -> 7.0
(5, 1) -> 5
(5.0.3.2, 1) -> 5
Args:
version_str: String, the version string.
sequence_count: int, an integer.
Returns:
string, reformatted version string.
"""
v = version_str.split('.')
if len(v) < sequence_count:
v = v + (['0'] * (sequence_count - len(v)))
return '.'.join(v[:sequence_count])
def set_cuda_paths(environ_cp):
"""Set TF_CUDA_PATHS."""
ask_cuda_paths = (
'Please specify the comma-separated list of base paths to look for CUDA '
'libraries and headers. [Leave empty to use the default]: ')
tf_cuda_paths = get_from_env_or_user_or_default(
environ_cp, 'TF_CUDA_PATHS', ask_cuda_paths, '')
if tf_cuda_paths:
environ_cp['TF_CUDA_PATHS'] = tf_cuda_paths
def set_cuda_version(environ_cp):
"""Set TF_CUDA_VERSION."""
ask_cuda_version = (
'Please specify the CUDA SDK version you want to use. '
'[Leave empty to default to CUDA %s]: ') % _DEFAULT_CUDA_VERSION
tf_cuda_version = get_from_env_or_user_or_default(
environ_cp, 'TF_CUDA_VERSION', ask_cuda_version, _DEFAULT_CUDA_VERSION)
environ_cp['TF_CUDA_VERSION'] = tf_cuda_version
def set_cudnn_version(environ_cp):
"""Set TF_CUDNN_VERSION."""
ask_cudnn_version = (
'Please specify the cuDNN version you want to use. '
'[Leave empty to default to cuDNN %s]: ') % _DEFAULT_CUDNN_VERSION
tf_cudnn_version = get_from_env_or_user_or_default(
environ_cp, 'TF_CUDNN_VERSION', ask_cudnn_version,
_DEFAULT_CUDNN_VERSION)
environ_cp['TF_CUDNN_VERSION'] = tf_cudnn_version
def is_cuda_compatible(lib, cuda_ver, cudnn_ver):
"""Check compatibility between given library and cudnn/cudart libraries."""
ldd_bin = which('ldd') or '/usr/bin/ldd'
ldd_out = run_shell([ldd_bin, lib], True)
ldd_out = ldd_out.split(os.linesep)
cudnn_pattern = re.compile('.*libcudnn.so\\.?(.*) =>.*$')
cuda_pattern = re.compile('.*libcudart.so\\.?(.*) =>.*$')
cudnn = None
cudart = None
cudnn_ok = True # assume no cudnn dependency by default
cuda_ok = True # assume no cuda dependency by default
for line in ldd_out:
if 'libcudnn.so' in line:
cudnn = cudnn_pattern.search(line)
cudnn_ok = False
elif 'libcudart.so' in line:
cudart = cuda_pattern.search(line)
cuda_ok = False
if cudnn and len(cudnn.group(1)):
cudnn = convert_version_to_int(cudnn.group(1))
if cudart and len(cudart.group(1)):
cudart = convert_version_to_int(cudart.group(1))
if cudnn is not None:
cudnn_ok = (cudnn == cudnn_ver)
if cudart is not None:
cuda_ok = (cudart == cuda_ver)
return cudnn_ok and cuda_ok
def set_tensorrt_version(environ_cp):
"""Set TF_TENSORRT_VERSION."""
if not int(environ_cp.get('TF_NEED_TENSORRT', False)):
return
ask_tensorrt_version = (
'Please specify the TensorRT version you want to use. '
'[Leave empty to default to TensorRT %s]: '
) % _DEFAULT_TENSORRT_VERSION
tf_tensorrt_version = get_from_env_or_user_or_default(
environ_cp, 'TF_TENSORRT_VERSION', ask_tensorrt_version,
_DEFAULT_TENSORRT_VERSION)
environ_cp['TF_TENSORRT_VERSION'] = tf_tensorrt_version
def set_migraphx_version(environ_cp):
"""Set TF_MIGRAPHX_VERSION."""
if not int(environ_cp.get('TF_NEED_MIGRAPHX', False)):
return
ask_migraphx_version = (
'Please specify the MIGraphX version you want to use. '
'[Leave empty to default to MIGraphX %s]: '
) % _DEFAULT_MIGRAPHX_VERSION
tf_migraphx_version = get_from_env_or_user_or_default(
environ_cp, 'TF_MIGRAPHX_VERSION', ask_migraphx_version,
_DEFAULT_MIGRAPHX_VERSION)
environ_cp['TF_MIGRAPHX_VERSION'] = tf_migraphx_version
def set_nccl_version(environ_cp):
"""Set TF_NCCL_VERSION."""
if 'TF_NCCL_VERSION' in environ_cp:
return
ask_nccl_version = (
'Please specify the locally installed NCCL version you want to use. '
)
tf_nccl_version = get_from_env_or_user_or_default(
environ_cp, 'TF_NCCL_VERSION', ask_nccl_version, '')
environ_cp['TF_NCCL_VERSION'] = tf_nccl_version
def get_native_cuda_compute_capabilities(environ_cp):
"""Get native cuda compute capabilities.
Args:
environ_cp: copy of the os.environ.
Returns:
string of native cuda compute capabilities, separated by comma.
"""
device_query_bin = os.path.join(
environ_cp.get('CUDA_TOOLKIT_PATH'), 'extras/demo_suite/deviceQuery')
if os.path.isfile(device_query_bin) and os.access(device_query_bin,
os.X_OK):
try:
output = run_shell(device_query_bin).split('\n')
pattern = re.compile('[0-9]*\\.[0-9]*')
output = [pattern.search(x) for x in output if 'Capability' in x]
output = ','.join(x.group() for x in output if x is not None)
except subprocess.CalledProcessError:
output = ''
else:
output = ''
return output
def get_native_rocm_compute_capabilities(environ_cp):
"""Get native rocm compute capabilities.
Args:
environ_cp: copy of the os.environ.
Returns:
string of native rocm compute capabilities , separated by comma.
(e.g. "gfx000,gfx906")
"""
device_query_bin = os.path.join(
environ_cp.get('ROCM_TOOLKIT_PATH'), 'bin/rocm_agent_enumerator')
if os.path.isfile(device_query_bin) and os.access(device_query_bin,
os.X_OK):
try:
output = run_shell(device_query_bin).split('\n')
output = ','.join(output)
except subprocess.CalledProcessError:
output = ''
else:
output = ''
return output
def set_cuda_compute_capabilities(environ_cp):
"""Set TF_CUDA_COMPUTE_CAPABILITIES."""
if not _INTERACTIVE_MODE:
native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
environ_cp)
if native_cuda_compute_capabilities:
tf_cuda_compute_capabilities = native_cuda_compute_capabilities
else:
tf_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
# Set TF_CUDA_COMPUTE_CAPABILITIES
environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
tf_cuda_compute_capabilities)
return
while True:
native_cuda_compute_capabilities = get_native_cuda_compute_capabilities(
environ_cp)
if not native_cuda_compute_capabilities:
default_cuda_compute_capabilities = _DEFAULT_CUDA_COMPUTE_CAPABILITIES
else:
default_cuda_compute_capabilities = native_cuda_compute_capabilities
ask_cuda_compute_capabilities = (
'Please specify a list of comma-separated '
'CUDA compute capabilities you want to '
'build with.\nYou can find the compute '
'capability of your device at: '
'https://developer.nvidia.com/cuda-gpus.\nPlease'
' note that each additional compute '
'capability significantly increases your '
'build time and binary size, and that '
'we only supports compute '
'capabilities >= 3.7 [Default is: %s]: ' %
default_cuda_compute_capabilities)
tf_cuda_compute_capabilities = get_from_env_or_user_or_default(
environ_cp, 'TF_CUDA_COMPUTE_CAPABILITIES',
ask_cuda_compute_capabilities, default_cuda_compute_capabilities)
# Check whether all capabilities from the input is valid
all_valid = True
# Remove all whitespace characters before splitting the string
# that users may insert by accident, as this will result in error
tf_cuda_compute_capabilities = ''.join(
tf_cuda_compute_capabilities.split())
for compute_capability in tf_cuda_compute_capabilities.split(','):
m = re.match('[0-9]+.[0-9]+', compute_capability)
if not m:
print((_ERROR + 'Invalid compute capability: %s') % compute_capability)
all_valid = False
else:
ver = float(m.group(0))
if ver < 3.5:
print((_ERROR + 'We only supports CUDA compute capabilities 3.7 and higher.'
' Please re-specify the list of compute capabilities excluding version %s.') % ver)
all_valid = False
if all_valid:
break
# Reset and Retry
environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = ''
# Set TF_CUDA_COMPUTE_CAPABILITIES
environ_cp['TF_CUDA_COMPUTE_CAPABILITIES'] = tf_cuda_compute_capabilities
write_action_env_to_bazelrc('TF_CUDA_COMPUTE_CAPABILITIES',
tf_cuda_compute_capabilities)
def set_rocm_compute_capabilities(environ_cp):
"""Set TF_ROCM_COMPUTE_CAPABILITIES."""
native_rocm_compute_capabilities = get_native_rocm_compute_capabilities(
environ_cp)
if native_rocm_compute_capabilities:
tf_rocm_compute_capabilities = native_rocm_compute_capabilities
else:
tf_rocm_compute_capabilities = _DEFAULT_ROCM_COMPUTE_CAPABILITIES
# Set TF_ROCM_COMPUTE_CAPABILITIES
environ_cp['TF_ROCM_COMPUTE_CAPABILITIES'] = tf_rocm_compute_capabilities
write_action_env_to_bazelrc('TF_ROCM_COMPUTE_CAPABILITIES',
tf_rocm_compute_capabilities)
return
def set_other_cuda_vars(environ_cp):
"""Set other CUDA related variables."""
# If CUDA is enabled, always use GPU during build and test.
# write_to_bazelrc('build --config=cuda')
pass
def validate_cuda_config(environ_cp):
"""Run find_cuda_config.py and return cuda_toolkit_path, or None."""
cuda_libraries = ['cuda', 'cudnn']
if int(environ_cp.get('TF_NEED_TENSORRT', False)):
cuda_libraries.append('tensorrt')
if environ_cp.get('TF_NCCL_VERSION', None):
cuda_libraries.append('nccl')
find_cuda_script = os.path.join(
_APOLLO_ROOT_DIR,
'third_party/gpus/find_cuda_config.py')
proc = subprocess.Popen(
[environ_cp['PYTHON_BIN_PATH'], find_cuda_script]
+ cuda_libraries,
stdout=subprocess.PIPE,
env=environ_cp)
if proc.wait():
# Errors from find_cuda_config.py were sent to stderr.
print(_INFO + 'Asking for detailed CUDA configuration...\n')
return False
config = dict(
tuple(line.decode('ascii').rstrip().split(': '))
for line in proc.stdout)
print((_INFO + 'Found ' + color.GREEN + 'CUDA %s' + color.NO_COLOR + ' in:') % config['cuda_version'])
print(' %s' % config['cuda_library_dir'])
print(' %s' % config['cuda_include_dir'])
print((_INFO + 'Found ' + color.GREEN + 'cuDNN %s' + color.NO_COLOR + ' in:') % config['cudnn_version'])
print(' %s' % config['cudnn_library_dir'])
print(' %s' % config['cudnn_include_dir'])
if 'tensorrt_version' in config:
print((_INFO + 'Found ' + color.GREEN + 'TensorRT %s' + color.NO_COLOR + ' in:') % config['tensorrt_version'])
print(' %s' % config['tensorrt_library_dir'])
print(' %s' % config['tensorrt_include_dir'])
if config.get('nccl_version', None):
print((_INFO + 'Found ' + color.GREEN + 'NCCL %s' + color.NO_COLOR + ' in:') % config['nccl_version'])
print(' %s' % config['nccl_library_dir'])
print(' %s' % config['nccl_include_dir'])
environ_cp['CUDA_TOOLKIT_PATH'] = config['cuda_toolkit_path']
return True
def validate_rocm_config(environ_cp):
"""Run find_rocm_config.py and return r_toolkit_path, or None."""
find_rocm_script = os.path.join(
_APOLLO_ROOT_DIR,
'third_party/gpus/find_rocm_config.py')
proc = subprocess.Popen(
[environ_cp['PYTHON_BIN_PATH'], find_rocm_script],
stdout=subprocess.PIPE,
env=environ_cp)
if proc.wait():
# Errors from find_rocm_config.py were sent to stderr.
print(_INFO + 'Asking for detailed ROCM configuration...\n')
return False
config = dict(
tuple(line.decode('ascii').rstrip().split(': '))
for line in proc.stdout)
print((_INFO + 'Found ' + color.GREEN + 'ROCm %s' + color.NO_COLOR + ' in:') % config['rocm_version_number'])
print(' %s' % config['rocm_toolkit_path'])
print(' %s' % config['rocm_header_path'])
print((_INFO + 'Found ' + color.GREEN + 'HIP %s' + color.NO_COLOR + ' in:') % config['hipruntime_version_number'])
print(' %s' % config['hipruntime_library_dir'])
print(' %s' % config['hipruntime_include_dir'])
print((_INFO + 'Found ' + color.GREEN + 'hipBLAS %s' + color.NO_COLOR + ' in:') % config['hipblas_version_number'])
print(' %s' % config['hipblas_library_dir'])
print(' %s' % config['hipblas_include_dir'])
print((_INFO + 'Found ' + color.GREEN + 'rocBLAS %s' + color.NO_COLOR + ' in:') % config['rocblas_version_number'])
print(' %s' % config['rocblas_library_dir'])
print(' %s' % config['rocblas_include_dir'])
print((_INFO + 'Found ' + color.GREEN + 'MIOpen %s' + color.NO_COLOR + ' in:') % config['miopen_version_number'])
print(' %s' % config['miopen_library_dir'])
print(' %s' % config['miopen_include_dir'])
print((_INFO + 'Found ' + color.GREEN + 'MIGraphX %s' + color.NO_COLOR + ' in:') % config['migraphx_version_number'])
print(' %s' % config['migraphx_library_dir'])
print(' %s' % config['migraphx_include_dir'])
environ_cp['ROCM_TOOLKIT_PATH'] = config['rocm_toolkit_path']
return True
def setup_cuda_family_config_interactively(environ_cp):
environ_save = dict(environ_cp)
for _ in range(_DEFAULT_PROMPT_ASK_ATTEMPTS):
if validate_cuda_config(environ_cp):
cuda_env_names = [
'TF_CUDA_VERSION',
'TF_CUBLAS_VERSION',
'TF_CUDNN_VERSION',
'TF_TENSORRT_VERSION',
'TF_NCCL_VERSION',
'TF_CUDA_PATHS',
# Items below are for backwards compatibility
'CUDA_TOOLKIT_PATH',
'CUDNN_INSTALL_PATH',
'NCCL_INSTALL_PATH',
'NCCL_HDR_PATH',
'TENSORRT_INSTALL_PATH'
]
# Note: set_action_env_var above already writes to bazelrc.
for name in cuda_env_names:
if name in environ_cp:
write_action_env_to_bazelrc(name, environ_cp[name])
break
# Restore settings changed below if CUDA config could not be
# validated.
environ_cp = dict(environ_save)
# TODO(build): revisit these settings
set_cuda_version(environ_cp)
set_cudnn_version(environ_cp)
set_tensorrt_version(environ_cp)
set_nccl_version(environ_cp)
set_cuda_paths(environ_cp)
else:
raise UserInputError(
'Invalid CUDA setting were provided %d '
'times in a row. Assuming to be a scripting mistake.' %
_DEFAULT_PROMPT_ASK_ATTEMPTS)
def setup_cuda_family_config_non_interactively(environ_cp):
if not validate_cuda_config(environ_cp):
print(_ERROR + "Cannot validate_cuda_config non-interactively. Aborting ...")
sys.exit(1)
cuda_env_names = [
'TF_CUDA_VERSION',
'TF_CUBLAS_VERSION',
'TF_CUDNN_VERSION',
'TF_TENSORRT_VERSION',
'TF_NCCL_VERSION',
'TF_CUDA_PATHS',
# Items below are for backwards compatibility
'CUDA_TOOLKIT_PATH',
'CUDNN_INSTALL_PATH',
'NCCL_INSTALL_PATH',
'NCCL_HDR_PATH',
'TENSORRT_INSTALL_PATH'
]
for name in cuda_env_names:
if name in environ_cp:
write_action_env_to_bazelrc(name, environ_cp[name])
def setup_cuda_family_config(environ_cp):
"""Setup CUDA/cuDNN/TensorRT/NCCL action env."""
if not _INTERACTIVE_MODE:
setup_cuda_family_config_non_interactively(environ_cp)
else:
setup_cuda_family_config_interactively(environ_cp)
def setup_rocm_family_config(environ_cp):
"""Setup ROCm/hip/hipblas/rocblas/miopen action env."""
if not validate_rocm_config(environ_cp):
print(_ERROR + "Cannot validate_rocm_config non-interactively. Aborting ...")
sys.exit(1)
rocm_env_names = [
'TF_ROCM_VERSION',
'TF_HIPBLAS_VERSION',
'TF_ROCBLAS_VERSION',
'TF_HIP_VERSION',
'TF_MIOPEN_VERSION',
# Items below are for backwards compatibility
'ROCM_TOOLKIT_PATH',
'HIP_INSTALL_PATH',
'HIPBLAS_INSTALL_PATH',
'ROCBLAS_INSTALL_PATH',
'MIOPEN_INSTALL_PATH'
'MIGRAPHX_INSTALL_PATH'
]
for name in rocm_env_names:
if name in environ_cp:
write_action_env_to_bazelrc(name, environ_cp[name])
def set_other_build_cuda_config(environ_cp):
build_text = """
# This config refers to building with CUDA available.
build:using_cuda --define=using_cuda=true
build:using_cuda --action_env TF_NEED_CUDA=1
build:using_cuda --crosstool_top=@local_config_cuda//crosstool:toolchain
# This config refers to building CUDA with nvcc.
build:cuda --config=using_cuda
build:cuda --define=using_cuda_nvcc=true
build:tensorrt --action_env TF_NEED_TENSORRT=1
"""
with open(_APOLLO_BAZELRC, 'a') as f:
f.write(build_text)
def set_other_build_rocm_config(environ_cp):
build_text = """
# This config refers to building with ROCm available.
build:using_rocm --define=using_rocm=true
build:using_rocm --action_env TF_NEED_ROCM=1
build:using_rocm --crosstool_top=@local_config_rocm//crosstool:toolchain
# This config refers to building ROCm with hipcc.
build:rocm --config=using_rocm
build:rocm --define=using_rocm_hipcc=true
build:migraphx --action_env TF_NEED_MIGRAPHX=1
"""
with open(_APOLLO_BAZELRC, 'a') as f:
f.write(build_text)
def set_tensorrt_config(environ_cp):
global _APOLLO_DOCKER_STAGE
def main():
if not is_linux():
raise ValueError('Currently, only Linux is support.')
global _APOLLO_ROOT_DIR
global _APOLLO_BAZELRC
global _APOLLO_CURRENT_BAZEL_VERSION
global _APOLLO_INSIDE_DOCKER
global _INTERACTIVE_MODE
global _APOLLO_DOCKER_STAGE
parser = argparse.ArgumentParser()
parser.add_argument(
'--output_file',
type=str,
default='.apollo.bazelrc',
help='Path of the bazelrc file to write to (relative to APOLLO_ROOT_DIR)')
parser.add_argument('--interactive', type=str2bool, nargs='?',
const=True, default=True,
help='Run this script interactively')
args = parser.parse_args()
_APOLLO_ROOT_DIR = default_root_dir()
_APOLLO_BAZELRC = os.path.join(_APOLLO_ROOT_DIR, args.output_file)
_APOLLO_INSIDE_DOCKER = inside_docker()
_APOLLO_DOCKER_STAGE = docker_stage()
_INTERACTIVE_MODE = args.interactive
# Make a copy of os.environ to be clear when functions and getting and setting
# environment variables.
environ_cp = dict(os.environ)
try:
current_bazel_version = check_bazel_version(_APOLLO_MIN_BAZEL_VERSION)
except subprocess.CalledProcessError as e:
print('Error checking bazel version: ',
e.output.decode('UTF-8').strip())
raise e
_APOLLO_CURRENT_BAZEL_VERSION = convert_version_to_int(
current_bazel_version)
reset_apollo_bazelrc()
setup_common_dirs(environ_cp)
setup_python(environ_cp)
if strtobool(environ_cp.get('TF_NEED_CUDA', 'False')):
write_to_bazelrc('build:gpu --config=cuda')
if strtobool(environ_cp.get('TF_NEED_ROCM', 'False')):
write_to_bazelrc('build:gpu --config=rocm')
if _APOLLO_DOCKER_STAGE == "dev":
if strtobool(environ_cp.get('TF_NEED_CUDA', 'False')):
environ_cp['TF_NEED_TENSORRT'] = '1'
write_to_bazelrc('build:gpu --config=tensorrt')
if strtobool(environ_cp.get('TF_NEED_ROCM', 'False')):
environ_cp['TF_NEED_MIGRAPHX'] = '1'
write_to_bazelrc('build:gpu --config=migraphx')
write_blank_line_to_bazelrc()
set_gcc_host_compiler_path(environ_cp)
write_blank_line_to_bazelrc()
if strtobool(environ_cp.get('TF_NEED_CUDA', 'False')):
setup_cuda_family_config(environ_cp)
set_cuda_compute_capabilities(environ_cp)
set_other_cuda_vars(environ_cp)
set_other_build_cuda_config(environ_cp)
if strtobool(environ_cp.get('TF_NEED_ROCM', 'False')):
setup_rocm_family_config(environ_cp)
set_rocm_compute_capabilities(environ_cp)
set_other_build_rocm_config(environ_cp)
write_build_var_to_bazelrc('teleop', 'WITH_TELEOP')
if not _APOLLO_INSIDE_DOCKER and 'LD_LIBRARY_PATH' in environ_cp:
write_action_env_to_bazelrc('LD_LIBRARY_PATH',
environ_cp.get('LD_LIBRARY_PATH'))
if __name__ == '__main__':
main()
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/tools/python_rules.bzl
|
"""Generates and compiles Python gRPC stubs from proto_library rules.
Tailored from @com_github_grpc_grpc:bazel/python_rules.bzl
"""
load("@rules_python//python:defs.bzl", "py_library")
load("@rules_proto//proto:defs.bzl", "ProtoInfo")
load("@bazel_skylib//lib:paths.bzl", "paths")
load(
"@com_github_grpc_grpc//bazel:protobuf.bzl",
"declare_out_files",
"get_include_directory",
"get_out_dir",
"get_plugin_args",
"get_proto_arguments",
"includes_from_deps",
"protos_from_context",
)
_GENERATED_PROTO_FORMAT = "{}_pb2.py"
_GENERATED_GRPC_PROTO_FORMAT = "{}_pb2_grpc.py"
def _generate_py_impl(context):
protos = protos_from_context(context)
includes = includes_from_deps(context.attr.deps)
out_files = declare_out_files(protos, context, _GENERATED_PROTO_FORMAT)
tools = [context.executable._protoc]
out_dir = get_out_dir(protos, context)
real_out_dir = out_dir.path
if context.build_file_path.startswith("apollo/"):
real_out_dir = paths.join(real_out_dir, "external/apollo")
arguments = ([
"--python_out={}".format(real_out_dir),
] + [
"--proto_path={}".format(get_include_directory(i))
for i in includes
] + [
"--proto_path={}".format(context.genfiles_dir.path),
])
if context.attr.plugin:
arguments += get_plugin_args(
context.executable.plugin,
[],
out_dir.path,
False,
context.attr.plugin.label.name,
)
tools.append(context.executable.plugin)
arguments += get_proto_arguments(protos, context.genfiles_dir.path)
context.actions.run(
inputs = protos + includes,
tools = tools,
outputs = out_files,
executable = context.executable._protoc,
arguments = arguments,
mnemonic = "ProtocInvocation",
)
imports = []
if out_dir.import_path:
imports.append("__main__/%s" % out_dir.import_path)
return [
DefaultInfo(files = depset(direct = out_files)),
PyInfo(
transitive_sources = depset(),
imports = depset(direct = imports),
),
]
_generate_pb2_src = rule(
attrs = {
"deps": attr.label_list(
mandatory = True,
allow_empty = False,
providers = [ProtoInfo],
),
"plugin": attr.label(
mandatory = False,
executable = True,
providers = ["files_to_run"],
cfg = "host",
),
"_protoc": attr.label(
default = Label("//external:protocol_compiler"),
providers = ["files_to_run"],
executable = True,
cfg = "host",
),
},
implementation = _generate_py_impl,
)
def py_proto_library(
name,
deps,
plugin = None,
**kwargs):
"""Generate python code for a protobuf.
Args:
name: The name of the target.
deps: A list of proto_library dependencies. Must contain one proto_library target
element, plus other py_proto_library targets depended on.
plugin: An optional custom protoc plugin to execute together with
generating the protobuf code.
**kwargs: Additional arguments to be supplied to the invocation of
py_library.
"""
codegen_target = "_{}_codegen".format(name)
src_deps = [d for d in deps if d.endswith("_proto")]
if len(src_deps) != 1:
fail("Can only compile a single proto at a time.")
lib_deps = [d for d in deps if d.endswith("_py_pb2")]
_generate_pb2_src(
name = codegen_target,
deps = src_deps,
plugin = plugin,
**kwargs
)
py_library(
name = name,
srcs = [":{}".format(codegen_target)],
deps = [
"@com_google_protobuf//:protobuf_python",
":{}".format(codegen_target),
] + lib_deps,
**kwargs
)
def _generate_pb2_grpc_src_impl(context):
protos = protos_from_context(context)
includes = includes_from_deps(context.attr.deps)
out_files = declare_out_files(protos, context, _GENERATED_GRPC_PROTO_FORMAT)
plugin_flags = ["grpc_2_0"] + context.attr.strip_prefixes
arguments = []
tools = [context.executable._protoc, context.executable._grpc_plugin]
out_dir = get_out_dir(protos, context)
arguments += get_plugin_args(
context.executable._grpc_plugin,
plugin_flags,
out_dir.path,
False,
)
if context.attr.plugin:
arguments += get_plugin_args(
context.executable.plugin,
[],
out_dir.path,
False,
context.attr.plugin.label.name,
)
tools.append(context.executable.plugin)
arguments += [
"--proto_path={}".format(get_include_directory(i))
for i in includes
]
arguments.append("--proto_path={}".format(context.genfiles_dir.path))
arguments += get_proto_arguments(protos, context.genfiles_dir.path)
context.actions.run(
inputs = protos + includes,
tools = tools,
outputs = out_files,
executable = context.executable._protoc,
arguments = arguments,
mnemonic = "ProtocInvocation",
)
imports = []
if out_dir.import_path:
imports.append("__main__/%s" % out_dir.import_path)
return [
DefaultInfo(files = depset(direct = out_files)),
PyInfo(
transitive_sources = depset(),
imports = depset(direct = imports),
),
]
_generate_pb2_grpc_src = rule(
attrs = {
"deps": attr.label_list(
mandatory = True,
allow_empty = False,
providers = [ProtoInfo],
),
"strip_prefixes": attr.string_list(),
"plugin": attr.label(
mandatory = False,
executable = True,
providers = ["files_to_run"],
cfg = "host",
),
"_grpc_plugin": attr.label(
executable = True,
providers = ["files_to_run"],
cfg = "host",
default = Label("@com_github_grpc_grpc//src/compiler:grpc_python_plugin"),
),
"_protoc": attr.label(
executable = True,
providers = ["files_to_run"],
cfg = "host",
default = Label("//external:protocol_compiler"),
),
},
implementation = _generate_pb2_grpc_src_impl,
)
def py_grpc_library(
name,
srcs,
deps,
plugin = None,
strip_prefixes = [],
**kwargs):
"""Generate python code for gRPC services defined in a protobuf.
Args:
name: The name of the target.
srcs: (List of `labels`) a single proto_library target containing the
schema of the service.
deps: (List of `labels`) a single py_proto_library target for the
proto_library in `srcs`.
strip_prefixes: (List of `strings`) If provided, this prefix will be
stripped from the beginning of foo_pb2 modules imported by the
generated stubs. This is useful in combination with the `imports`
attribute of the `py_library` rule.
plugin: An optional custom protoc plugin to execute together with
generating the gRPC code.
**kwargs: Additional arguments to be supplied to the invocation of
py_library.
"""
codegen_grpc_target = "_{}_grpc_codegen".format(name)
if len(srcs) != 1:
fail("Can only compile a single proto at a time.")
if len(deps) != 1:
fail("Deps must have length 1.")
_generate_pb2_grpc_src(
name = codegen_grpc_target,
deps = srcs,
strip_prefixes = strip_prefixes,
plugin = plugin,
**kwargs
)
py_library(
name = name,
srcs = [
":{}".format(codegen_grpc_target),
],
deps = [
Label("@com_github_grpc_grpc//src/python/grpcio/grpc:grpcio"),
] + deps + [
":{}".format(codegen_grpc_target),
],
**kwargs
)
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/tools/bazel.rc
|
# Apollo Bazel configuration file.
# This file tries to group and simplify build options for Apollo
# +------------------------------------------------------------+
# | Startup Options |
# +------------------------------------------------------------+
startup --batch_cpu_scheduling
startup --host_jvm_args="-XX:-UseParallelGC"
fetch --experimental_multi_threaded_digest=true
query --experimental_multi_threaded_digest=true
# +------------------------------------------------------------+
# | Common Options |
# +------------------------------------------------------------+
# Force bazel output to use colors (good for jenkins) and print useful errors.
common --color=yes
# +------------------------------------------------------------+
# | Build Configurations |
# +------------------------------------------------------------+
# Make Bazel print out all options from rc files.
# build --announce_rc
build --show_timestamps
# Work around the sandbox issue.
build --spawn_strategy=standalone
# Enable colorful output of GCC
build --cxxopt="-fdiagnostics-color=always"
# Do not show warnings from external dependencies.
# build --output_filter="^//"
build --per_file_copt=external/upb/.*@-Wno-sign-compare
build --copt="-Werror=sign-compare"
build --copt="-Werror=return-type"
build --copt="-Werror=unused-variable"
build --copt="-Werror=unused-but-set-variable"
build --copt="-Werror=switch"
build --cxxopt="-Werror=reorder"
# Default paths for SYSTEM LIBRARIES
build --define=PREFIX=/usr
build --define=LIBDIR=$(PREFIX)/lib
build --define=INCLUDEDIR=$(PREFIX)/include
build --define=use_fast_cpp_protos=true
# GPU_PLATFORM predefined types
build --define NVIDIA=0
build --define AMD=1
# dbg config, as a shorthand for '--config=optimize -c dbg'
build:dbg -c dbg
build:opt -c opt
#build --config=optimize
# Instruction set optimizations
#build:optimize --copt=-march=native
#build:optimize --host_copt=-march=native
# Now "cpu" configuration was dummy
build:cpu --verbose_failures
build:gpu --define USE_GPU=true
build:gpu --cxxopt="-DUSE_GPU=1"
build:gpu --cxxopt="-DNVIDIA=0"
build:gpu --cxxopt="-DAMD=1"
# GPU platform
build:amd --define GPU_PLATFORM=AMD
build:amd --cxxopt="-DGPU_PLATFORM=AMD"
build:nvidia --define GPU_PLATFORM=NVIDIA
build:nvidia --cxxopt="-DGPU_PLATFORM=NVIDIA"
# Build with profiling
build:prof --linkopt=-lprofiler
build:prof --cxxopt="-DENABLE_PERF=1"
# Build Apollo with C++ 17 features.
build:c++17 --cxxopt=-std=c++1z
# build:c++17 --cxxopt=-stdlib=libc++
build:c++1z --config=c++17
# Enable C++14 (aka c++1y) by default
build --cxxopt="-std=c++14"
build --host_cxxopt="-std=c++14"
# +------------------------------------------------------------+
# | Test Configurations |
# +------------------------------------------------------------+
test --flaky_test_attempts=3
test --test_size_filters=small,medium
# test --test_env=LD_LIBRARY_PATH
# test --test_env=PYTHONPATH
# By default prints output only from failed tests.
test --test_output=errors
test:unit_test --test_verbose_timeout_warnings
# use --copt=-mavx2
test --copt=-mavx2
coverage --javabase="@bazel_tools//tools/jdk:remote_jdk11"
# coverage --host_javabase="@bazel_tools//tools/jdk:remote_jdk11"
coverage --instrument_test_targets
coverage --combined_report=lcov
coverage --nocache_test_results
# coverage --coverage_report_generator="@bazel_tools//tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator:Main"
coverage --cxxopt=--coverage
coverage --cxxopt=-fprofile-arcs
coverage --cxxopt=-ftest-coverage
coverage --linkopt=-lgcov
# +------------------------------------------------------------+
# | CPP Lint Tests & Unit Tests |
# +------------------------------------------------------------+
# By default, cpplint tests are run as part of `bazel test` alongside all of
# the other compilation and test targets. This is a convenience shortcut to
# only do the cpplint testing and nothing else.
# Do bazel test --config=cpplint <target> to enable this configuration.
# To enable the lint test, the BUILD *must* load the cpplint.bzl by having
# 'load("//tools:cpplint.bzl", "cpplint")' at the beginning and 'cpplint()'
# at the end.
test:cpplint --test_tag_filters=cpplint
test:cpplint --build_tests_only
test:cpplint --flaky_test_attempts=1
# Regular unit tests.
test:unit_test --test_tag_filters=-cpplint
# Coverage tests
coverage --test_tag_filters=-cpplint
# +------------------------------------------------------------+
# | Python Configurations |
# +------------------------------------------------------------+
# Python support was configured by third_party/py .
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/tools/cyberfile.xml
|
<package format="2">
<name>bazel-extend-tools</name>
<version>local</version>
<description>
Some extend rules of bazel and scripts.
</description>
<maintainer email="apollo-support@baidu.com">Apollo</maintainer>
<license>Apache License 2.0</license>
<url type="website">https://www.apollo.auto/</url>
<url type="repository">https://github.com/ApolloAuto/apollo</url>
<url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url>
<type>module-wrapper</type>
<src_path url="https://github.com/ApolloAuto/apollo">//tools</src_path>
</package>
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/tools/cc_so_proto_rules.bzl
|
load("@com_github_grpc_grpc//bazel:generate_cc.bzl", "generate_cc")
def cc_so_proto_library(name,
srcs = [],
deps = [],
well_known_protos = False,
**kwargs):
"""Generates C++ proto dynamic library from a proto_library.
Assumes the generated classes will be used in cc_api_version = 2.
Arguments:
name: name of rule.
srcs: a list of C++ proto_library which provides
the compiled code of any message that the services depend on.
deps: a list of C++ cc_so_proto_library which provides
hdrs that the services depend on.
well_known_protos: Should this library additionally depend on well known
protos
**kwargs: rest of arguments, e.g., compatible_with and visibility.
"""
if len(srcs) > 1:
fail("Only one srcs value supported", "srcs")
codegen_target = "_" + name + "_codegen"
libso_target = "lib" + name + ".so"
export_hdr_target = name + "_hdrs"
generate_cc(
name = codegen_target,
srcs = srcs,
well_known_protos = well_known_protos,
**kwargs
)
native.cc_binary(
name = libso_target,
srcs = [":" + codegen_target],
deps = deps +["@com_google_protobuf//:protobuf"],
linkshared = True,
linkstatic = True,
visibility = ["//visibility:public"],
**kwargs
)
native.cc_library(
name = name,
srcs = [libso_target],
hdrs = [":" + codegen_target],
includes = [":" + codegen_target],
deps = deps + ["@com_google_protobuf//:protobuf"],
visibility = ["//visibility:public"],
**kwargs
)
native.filegroup(
name = export_hdr_target,
srcs = [":" + codegen_target],
)
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/tools/workspace.bzl
|
# Apollo external dependencies that can be loaded in WORKSPACE files.
load("//third_party/absl:workspace.bzl", absl = "repo")
load("//third_party/adolc:workspace.bzl", adolc = "repo")
load("//third_party/adv_plat:workspace.bzl", adv_plat = "repo")
load("//third_party/ad_rss_lib:workspace.bzl", ad_rss_lib = "repo")
load("//third_party/atlas:workspace.bzl", atlas = "repo")
load("//third_party/benchmark:workspace.bzl", benchmark = "repo")
load("//third_party/boost:workspace.bzl", boost = "repo")
load("//third_party/caddn_infer_op:workspace.bzl", caddn_infer_op = "repo")
load("//third_party/centerpoint_infer_op:workspace.bzl", centerpoint_infer_op = "repo")
load("//third_party/civetweb:workspace.bzl", civetweb = "repo")
load("//third_party/cpplint:workspace.bzl", cpplint = "repo")
load("//third_party/eigen3:workspace.bzl", eigen = "repo")
load("//third_party/ffmpeg:workspace.bzl", ffmpeg = "repo")
load("//third_party/fftw3:workspace.bzl", fftw3 = "repo")
load("//third_party/fastrtps:workspace.bzl", fastrtps = "repo")
load("//third_party/glog:workspace.bzl", glog = "repo")
load("//third_party/gtest:workspace.bzl", gtest = "repo")
load("//third_party/gflags:workspace.bzl", gflags = "repo")
load("//third_party/ipopt:workspace.bzl", ipopt = "repo")
load("//third_party/libtorch:workspace.bzl", libtorch_cpu = "repo_cpu", libtorch_gpu = "repo_gpu")
load("//third_party/ncurses5:workspace.bzl", ncurses5 = "repo")
load("//third_party/nlohmann_json:workspace.bzl", nlohmann_json = "repo")
load("//third_party/npp:workspace.bzl", npp = "repo")
load("//third_party/opencv:workspace.bzl", opencv = "repo")
load("//third_party/opengl:workspace.bzl", opengl = "repo")
load("//third_party/openh264:workspace.bzl", openh264 = "repo")
load("//third_party/osqp:workspace.bzl", osqp = "repo")
load("//third_party/paddleinference:workspace.bzl", paddleinference = "repo")
load("//third_party/portaudio:workspace.bzl", portaudio = "repo")
load("//third_party/proj:workspace.bzl", proj = "repo")
load("//third_party/protobuf:workspace.bzl", protobuf = "repo")
load("//third_party/qt5:workspace.bzl", qt5 = "repo")
load("//third_party/sqlite3:workspace.bzl", sqlite3 = "repo")
load("//third_party/tinyxml2:workspace.bzl", tinyxml2 = "repo")
load("//third_party/uuid:workspace.bzl", uuid = "repo")
load("//third_party/yaml_cpp:workspace.bzl", yaml_cpp = "repo")
# load("//third_party/glew:workspace.bzl", glew = "repo")
load("//third_party/gpus:cuda_configure.bzl", "cuda_configure")
load("//third_party/gpus:rocm_configure.bzl", "rocm_configure")
load("//third_party/py:python_configure.bzl", "python_configure")
load("//third_party/tensorrt:tensorrt_configure.bzl", "tensorrt_configure")
load("//third_party/vtk:vtk_configure.bzl", "vtk_configure")
load("//third_party/pcl:pcl_configure.bzl", "pcl_configure")
def initialize_third_party():
""" Load third party repositories. See above load() statements. """
absl()
adolc()
adv_plat()
ad_rss_lib()
atlas()
benchmark()
boost()
caddn_infer_op()
centerpoint_infer_op()
cpplint()
civetweb()
eigen()
fastrtps()
ffmpeg()
fftw3()
gflags()
glog()
gtest()
ipopt()
libtorch_cpu()
libtorch_gpu()
ncurses5()
nlohmann_json()
npp()
opencv()
opengl()
openh264()
osqp()
paddleinference()
portaudio()
proj()
protobuf()
qt5()
sqlite3()
tinyxml2()
uuid()
yaml_cpp()
# Define all external repositories required by
def apollo_repositories():
cuda_configure(name = "local_config_cuda")
rocm_configure(name = "local_config_rocm")
tensorrt_configure(name = "local_config_tensorrt")
python_configure(name = "local_config_python")
vtk_configure(name = "local_config_vtk")
pcl_configure(name = "local_config_pcl")
initialize_third_party()
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/tools/cpplint.bzl
|
# -*- python -*-
load("@rules_python//python:defs.bzl", "py_test")
# From https://bazel.build/versions/master/docs/be/c-cpp.html#cc_library.srcs
_SOURCE_EXTENSIONS = [source_ext for source_ext in """
.c
.cc
.cpp
.cxx
.c++
.C
.h
.hh
.hpp
.hxx
.inc
""".split("\n") if len(source_ext)]
# The cpplint.py command-line argument so it doesn't skip our files!
_EXTENSIONS_ARGS = ["--extensions=" + ",".join(
[ext[1:] for ext in _SOURCE_EXTENSIONS],
)]
def _extract_labels(srcs):
"""Convert a srcs= or hdrs= value to its set of labels."""
# Tuples are already labels.
if type(srcs) == type(()):
return list(srcs)
return []
def _is_source_label(label):
for extension in _SOURCE_EXTENSIONS:
if label.endswith(extension):
return True
return False
def _add_linter_rules(source_labels, source_filenames, name, data = None):
# Common attributes for all of our py_test invocations.
data = (data or [])
size = "small"
tags = ["cpplint"]
# Google cpplint.
cpplint_cfg = ["//tools:CPPLINT.cfg"] + native.glob(["CPPLINT.cfg"])
py_test(
name = name + "_cpplint",
srcs = ["@cpplint//:cpplint"],
data = data + cpplint_cfg + source_labels,
args = _EXTENSIONS_ARGS + source_filenames,
main = "cpplint.py",
size = size,
tags = tags,
)
def cpplint(data = None, extra_srcs = None):
"""For every rule in the BUILD file so far, adds a test rule that runs
cpplint over the C++ sources listed in that rule. Thus, BUILD file authors
should call this function at the *end* of every C++-related BUILD file.
By default, only the CPPLINT.cfg from the project root and the current
directory are used. Additional configs can be passed in as data labels.
Sources that are not discoverable through the "sources so far" heuristic can
be passed in as extra_srcs=[].
"""
# Iterate over all rules.
for rule in native.existing_rules().values():
# Extract the list of C++ source code labels and convert to filenames.
candidate_labels = (
_extract_labels(rule.get("srcs", ())) +
_extract_labels(rule.get("hdrs", ()))
)
source_labels = [
label
for label in candidate_labels
if _is_source_label(label)
]
source_filenames = ["$(location %s)" % x for x in source_labels]
# Run the cpplint checker as a unit test.
if len(source_filenames) > 0:
_add_linter_rules(source_labels, source_filenames, rule["name"], data)
# Lint all of the extra_srcs separately in a single rule.
if extra_srcs:
source_labels = extra_srcs
source_filenames = ["$(location %s)" % x for x in source_labels]
_add_linter_rules(
source_labels,
source_filenames,
"extra_srcs_cpplint",
data,
)
| 0
|
apollo_public_repos/apollo
|
apollo_public_repos/apollo/tools/BUILD
|
load("//tools/install:install.bzl", "install", "install_files", "install_src_files")
package(
default_visibility = ["//visibility:public"],
)
exports_files(["CPPLINT.cfg"])
install(
name = "install",
data_dest = "bazel-extend-tools",
data = [
":cyberfile.xml",
],
)
install_src_files(
name = "install_src",
src_dir = ["."],
dest = "bazel-extend-tools/src",
filter = "*",
)
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.