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/tools
apollo_public_repos/apollo/cyber/tools/cyber_monitor/screen.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/tools/cyber_monitor/screen.h" #include <unistd.h> #include <cstdio> #include <cstring> #include <iostream> #include <mutex> #include <thread> #include "cyber/tools/cyber_monitor/cyber_topology_message.h" #include "cyber/tools/cyber_monitor/general_channel_message.h" #include "cyber/tools/cyber_monitor/renderable_message.h" #include <ncurses.h> // NOLINT namespace { constexpr double MinHalfFrameRatio = 12.5; } Screen* Screen::Instance(void) { static Screen s; return &s; } const char Screen::InteractiveCmdStr[] = "Common Commands for all:\n" " q | Q | Esc -- quit\n" " Backspace -- go back\n" " h | H -- go to show help info\n" "\n" "Common Commands for Topology and Channel Message:\n" " PgDn | ^d -- show next page\n" " PgUp | ^u -- show previous page\n" "\n" " Up Arrow -- move up one line\n" " Down Arrow -- move down one line\n" " Right Arrow -- enter the selected Channel or Repeated Datum\n" " Left Arrow -- go back to the upper level\n" "\n" " Enter -- the same with Right Arrow key\n" " a | A -- the same with Left Arrow key\n" " d | D -- the same with Right Arrow key\n" " w | W -- the same with Up Arrow key\n" " s | S -- the same with Down Arrow key\n" "\n" "Commands for Topology message:\n" " f | F -- show frame ratio for all channel messages\n" " t | T -- show channel message type\n" "\n" " Space -- Enable|Disable channel Message\n" "\n" "Commands for Channel:\n" " i | I -- show Reader and Writers of Channel\n" " b | B -- show Debug String of Channel Message\n" "\n" "Commands for Channel Repeated Datum:\n" " n | N -- next repeated data item\n" " m | M -- previous repeated data item\n" " , -- enable|disable to show all repeated items\n"; Screen::Screen() : current_color_pair_(INVALID), canRun_(false), current_state_(State::RenderMessage), highlight_direction_(0), current_render_obj_(nullptr) {} Screen::~Screen() { current_render_obj_ = nullptr; endwin(); } inline bool Screen::IsInit(void) const { return (stdscr != nullptr); } void Screen::Init(void) { initscr(); if (stdscr == nullptr) { return; } nodelay(stdscr, true); keypad(stdscr, true); meta(stdscr, true); curs_set(0); noecho(); bkgd(COLOR_BLACK); start_color(); init_pair(GREEN_BLACK, COLOR_GREEN, COLOR_BLACK); init_pair(YELLOW_BLACK, COLOR_YELLOW, COLOR_BLACK); init_pair(RED_BLACK, COLOR_RED, COLOR_BLACK); init_pair(WHITE_BLACK, COLOR_WHITE, COLOR_BLACK); init_pair(BLACK_WHITE, COLOR_BLACK, COLOR_WHITE); refresh(); clear(); canRun_ = true; } int Screen::Width(void) const { return COLS; } int Screen::Height(void) const { return LINES; } void Screen::SetCurrentColor(ColorPair color) const { if (color == INVALID) { return; } if (IsInit()) { current_color_pair_ = color; attron(COLOR_PAIR(color)); } } void Screen::AddStr(int x, int y, const char* str) const { if (IsInit()) { mvaddstr(y, x, str); } } void Screen::AddStr(const char* str) const { if (IsInit()) { addstr(str); } } void Screen::ClearCurrentColor(void) const { if (IsInit()) { attroff(COLOR_PAIR(current_color_pair_)); current_color_pair_ = INVALID; } } void Screen::AddStr(int x, int y, ColorPair color, const char* str) const { if (IsInit()) { attron(COLOR_PAIR(color)); mvaddstr(y, x, str); attroff(COLOR_PAIR(color)); } } void Screen::MoveOffsetXY(int offsetX, int offsetY) const { if (IsInit()) { int x, y; getyx(stdscr, y, x); move(y + offsetY, x + offsetX); } } void Screen::HighlightLine(int line_no) { if (IsInit() && line_no < Height()) { SetCurrentColor(WHITE_BLACK); for (int x = 0; x < Width(); ++x) { chtype ch = mvinch(line_no + highlight_direction_, x); ch &= A_CHARTEXT; if (ch == ' ') { mvaddch(line_no + highlight_direction_, x, ch); } } ClearCurrentColor(); SetCurrentColor(BLACK_WHITE); for (int x = 0; x < Width(); ++x) { chtype ch = mvinch(line_no, x); mvaddch(line_no, x, ch & A_CHARTEXT); } ClearCurrentColor(); } } int Screen::SwitchState(int ch) { switch (current_state_) { case State::RenderInterCmdInfo: if (KEY_BACKSPACE == ch) { current_state_ = State::RenderMessage; clear(); ch = 27; } break; case State::RenderMessage: if ('h' == ch || 'H' == ch) { current_state_ = State::RenderInterCmdInfo; clear(); } break; default: { } } return ch; } void Screen::Run() { if (stdscr == nullptr || current_render_obj_ == nullptr) { return; } highlight_direction_ = 0; void (Screen::*showFuncs[])(int) = {&Screen::ShowRenderMessage, &Screen::ShowInteractiveCmd}; do { int ch = getch(); if (ch == 'q' || ch == 'Q' || ch == 27) { canRun_ = false; break; } ch = SwitchState(ch); (this->*showFuncs[static_cast<int>(current_state_)])(ch); double fr = current_render_obj_->frame_ratio(); if (fr < MinHalfFrameRatio) { fr = MinHalfFrameRatio; } int period = static_cast<int>(1000.0 / fr); period >>= 1; std::this_thread::sleep_for(std::chrono::milliseconds(period)); } while (canRun_); } void Screen::Resize(void) { if (IsInit()) { clear(); refresh(); } } void Screen::ShowRenderMessage(int ch) { erase(); int line_num = current_render_obj_->Render(this, ch); const int max_height = std::min(Height(), line_num); int* y = current_render_obj_->line_no(); HighlightLine(*y); move(*y, 0); refresh(); switch (ch) { case 's': case 'S': case KEY_DOWN: ++(*y); highlight_direction_ = -1; if (*y >= max_height) { *y = max_height - 1; } break; case 'w': case 'W': case KEY_UP: --(*y); if (*y < 1) { *y = 1; } highlight_direction_ = 1; if (*y < 0) { *y = 0; } break; case 'a': case 'A': case KEY_BACKSPACE: case KEY_LEFT: { RenderableMessage* p = current_render_obj_->parent(); if (p) { current_render_obj_ = p; y = p->line_no(); clear(); } break; } case '\n': case '\r': case 'd': case 'D': case KEY_RIGHT: { RenderableMessage* child = current_render_obj_->Child(*y); if (child) { child->reset_line_page(); current_render_obj_ = child; y = child->line_no(); clear(); } break; } } } void Screen::ShowInteractiveCmd(int) { unsigned y = 0; SetCurrentColor(Screen::WHITE_BLACK); AddStr((Width() - 19) / 2, y++, "Interactive Command"); const char* ptr = InteractiveCmdStr; while (*ptr != '\0') { const char* sub = std::strchr(ptr, '\n'); std::string subStr(ptr, sub); AddStr(0, y++, subStr.c_str()); ptr = sub + 1; } ClearCurrentColor(); }
0
apollo_public_repos/apollo/cyber/tools
apollo_public_repos/apollo/cyber/tools/cyber_monitor/general_message.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 TOOLS_CVT_MONITOR_GENERAL_MESSAGE_H_ #define TOOLS_CVT_MONITOR_GENERAL_MESSAGE_H_ #include "cyber/cyber.h" #include "cyber/message/raw_message.h" #include "cyber/tools/cyber_monitor/general_message_base.h" class Screen; class GeneralMessage : public GeneralMessageBase { public: GeneralMessage(GeneralMessageBase* parent, const google::protobuf::Message* msg, const google::protobuf::Reflection* reflection, const google::protobuf::FieldDescriptor* field); ~GeneralMessage() { field_ = nullptr; message_ptr_ = nullptr; reflection_ptr_ = nullptr; } int Render(const Screen* s, int key) override; private: GeneralMessage(const GeneralMessage&) = delete; GeneralMessage& operator=(const GeneralMessage&) = delete; int item_index_; bool is_folded_; const google::protobuf::FieldDescriptor* field_; const google::protobuf::Message* message_ptr_; const google::protobuf::Reflection* reflection_ptr_; }; #endif // TOOLS_CVT_MONITOR_GENERAL_MESSAGE_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/transport/transport_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/transport/transport.h" #include <memory> #include <typeinfo> #include "gtest/gtest.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/init.h" #include "cyber/transport/common/identity.h" namespace apollo { namespace cyber { namespace transport { using TransmitterPtr = std::shared_ptr<Transmitter<proto::UnitTest>>; using ReceiverPtr = std::shared_ptr<Receiver<proto::UnitTest>>; TEST(TransportTest, constructor) { auto transport_a = Transport::Instance(); auto transport_b = Transport::Instance(); EXPECT_EQ(transport_a->participant(), transport_b->participant()); } TEST(TransportTest, create_transmitter) { QosProfileConf qos_conf; (void)qos_conf; RoleAttributes attr; attr.set_channel_name("create_transmitter"); Identity id; attr.set_id(id.HashValue()); TransmitterPtr intra = Transport::Instance()->CreateTransmitter<proto::UnitTest>( attr, OptionalMode::INTRA); EXPECT_EQ(typeid(*intra), typeid(IntraTransmitter<proto::UnitTest>)); TransmitterPtr shm = Transport::Instance()->CreateTransmitter<proto::UnitTest>( attr, OptionalMode::SHM); EXPECT_EQ(typeid(*shm), typeid(ShmTransmitter<proto::UnitTest>)); } TEST(TransportTest, create_receiver) { RoleAttributes attr; attr.set_channel_name("create_receiver"); Identity id; attr.set_id(id.HashValue()); auto listener = [](const std::shared_ptr<proto::UnitTest>&, const MessageInfo&, const RoleAttributes&) {}; ReceiverPtr intra = Transport::Instance()->CreateReceiver<proto::UnitTest>( attr, listener, OptionalMode::INTRA); EXPECT_EQ(typeid(*intra), typeid(IntraReceiver<proto::UnitTest>)); ReceiverPtr shm = Transport::Instance()->CreateReceiver<proto::UnitTest>( attr, listener, OptionalMode::SHM); EXPECT_EQ(typeid(*shm), typeid(ShmReceiver<proto::UnitTest>)); } } // namespace transport } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); apollo::cyber::Init(argv[0]); apollo::cyber::transport::Transport::Instance(); auto res = RUN_ALL_TESTS(); apollo::cyber::transport::Transport::Instance()->Shutdown(); return res; }
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/transport/transport.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_TRANSPORT_TRANSPORT_H_ #define CYBER_TRANSPORT_TRANSPORT_H_ #include <atomic> #include <memory> #include <string> #include "cyber/proto/transport_conf.pb.h" #include "cyber/common/macros.h" #include "cyber/transport/dispatcher/intra_dispatcher.h" #include "cyber/transport/dispatcher/rtps_dispatcher.h" #include "cyber/transport/dispatcher/shm_dispatcher.h" #include "cyber/transport/qos/qos_profile_conf.h" #include "cyber/transport/receiver/hybrid_receiver.h" #include "cyber/transport/receiver/intra_receiver.h" #include "cyber/transport/receiver/receiver.h" #include "cyber/transport/receiver/rtps_receiver.h" #include "cyber/transport/receiver/shm_receiver.h" #include "cyber/transport/rtps/participant.h" #include "cyber/transport/shm/notifier_factory.h" #include "cyber/transport/transmitter/hybrid_transmitter.h" #include "cyber/transport/transmitter/intra_transmitter.h" #include "cyber/transport/transmitter/rtps_transmitter.h" #include "cyber/transport/transmitter/shm_transmitter.h" #include "cyber/transport/transmitter/transmitter.h" namespace apollo { namespace cyber { namespace transport { using apollo::cyber::proto::OptionalMode; class Transport { public: virtual ~Transport(); void Shutdown(); template <typename M> auto CreateTransmitter(const RoleAttributes& attr, const OptionalMode& mode = OptionalMode::HYBRID) -> typename std::shared_ptr<Transmitter<M>>; template <typename M> auto CreateReceiver(const RoleAttributes& attr, const typename Receiver<M>::MessageListener& msg_listener, const OptionalMode& mode = OptionalMode::HYBRID) -> typename std::shared_ptr<Receiver<M>>; ParticipantPtr participant() const { return participant_; } private: void CreateParticipant(); std::atomic<bool> is_shutdown_ = {false}; ParticipantPtr participant_ = nullptr; NotifierPtr notifier_ = nullptr; IntraDispatcherPtr intra_dispatcher_ = nullptr; ShmDispatcherPtr shm_dispatcher_ = nullptr; RtpsDispatcherPtr rtps_dispatcher_ = nullptr; DECLARE_SINGLETON(Transport) }; template <typename M> auto Transport::CreateTransmitter(const RoleAttributes& attr, const OptionalMode& mode) -> typename std::shared_ptr<Transmitter<M>> { if (is_shutdown_.load()) { AINFO << "transport has been shut down."; return nullptr; } std::shared_ptr<Transmitter<M>> transmitter = nullptr; RoleAttributes modified_attr = attr; if (!modified_attr.has_qos_profile()) { modified_attr.mutable_qos_profile()->CopyFrom( QosProfileConf::QOS_PROFILE_DEFAULT); } switch (mode) { case OptionalMode::INTRA: transmitter = std::make_shared<IntraTransmitter<M>>(modified_attr); break; case OptionalMode::SHM: transmitter = std::make_shared<ShmTransmitter<M>>(modified_attr); break; case OptionalMode::RTPS: transmitter = std::make_shared<RtpsTransmitter<M>>(modified_attr, participant()); break; default: transmitter = std::make_shared<HybridTransmitter<M>>(modified_attr, participant()); break; } RETURN_VAL_IF_NULL(transmitter, nullptr); if (mode != OptionalMode::HYBRID) { transmitter->Enable(); } return transmitter; } template <typename M> auto Transport::CreateReceiver( const RoleAttributes& attr, const typename Receiver<M>::MessageListener& msg_listener, const OptionalMode& mode) -> typename std::shared_ptr<Receiver<M>> { if (is_shutdown_.load()) { AINFO << "transport has been shut down."; return nullptr; } std::shared_ptr<Receiver<M>> receiver = nullptr; RoleAttributes modified_attr = attr; if (!modified_attr.has_qos_profile()) { modified_attr.mutable_qos_profile()->CopyFrom( QosProfileConf::QOS_PROFILE_DEFAULT); } switch (mode) { case OptionalMode::INTRA: receiver = std::make_shared<IntraReceiver<M>>(modified_attr, msg_listener); break; case OptionalMode::SHM: receiver = std::make_shared<ShmReceiver<M>>(modified_attr, msg_listener); break; case OptionalMode::RTPS: receiver = std::make_shared<RtpsReceiver<M>>(modified_attr, msg_listener); break; default: receiver = std::make_shared<HybridReceiver<M>>( modified_attr, msg_listener, participant()); break; } RETURN_VAL_IF_NULL(receiver, nullptr); if (mode != OptionalMode::HYBRID) { receiver->Enable(); } return receiver; } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_TRANSPORT_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/transport/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_transport_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "transport", srcs = ["transport.cc"], hdrs = ["transport.h"], deps = [ "//cyber/service_discovery:role", "//cyber/task", "//cyber/transport/dispatcher:intra_dispatcher", "//cyber/transport/dispatcher:rtps_dispatcher", "//cyber/transport/dispatcher:shm_dispatcher", "//cyber/transport/message:history", "//cyber/transport/qos", "//cyber/transport/receiver", "//cyber/transport/rtps:attributes_filler", "//cyber/transport/rtps:participant", "//cyber/transport/rtps:sub_listener", "//cyber/transport/rtps:underlay_message", "//cyber/transport/rtps:underlay_message_type", "//cyber/transport/transmitter", "@fastrtps", ], ) cc_test( name = "transport_test", size = "small", srcs = ["transport_test.cc"], deps = [ "//cyber:cyber_core", "//cyber/proto:unit_test_cc_proto", "@com_google_googletest//:gtest", ], ) cpplint()
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/transport/transport.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/transport/transport.h" #include "cyber/common/global_data.h" namespace apollo { namespace cyber { namespace transport { Transport::Transport() { CreateParticipant(); notifier_ = NotifierFactory::CreateNotifier(); intra_dispatcher_ = IntraDispatcher::Instance(); shm_dispatcher_ = ShmDispatcher::Instance(); rtps_dispatcher_ = RtpsDispatcher::Instance(); rtps_dispatcher_->set_participant(participant_); } Transport::~Transport() { Shutdown(); } void Transport::Shutdown() { if (is_shutdown_.exchange(true)) { return; } intra_dispatcher_->Shutdown(); shm_dispatcher_->Shutdown(); rtps_dispatcher_->Shutdown(); notifier_->Shutdown(); if (participant_ != nullptr) { participant_->Shutdown(); participant_ = nullptr; } } void Transport::CreateParticipant() { std::string participant_name = common::GlobalData::Instance()->HostName() + "+" + std::to_string(common::GlobalData::Instance()->ProcessId()); participant_ = std::make_shared<Participant>(participant_name, 11512); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/integration_test/intra_transceiver_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/transport/transmitter/intra_transmitter.h" #include <memory> #include <string> #include <vector> #include "gtest/gtest.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/transport/receiver/intra_receiver.h" namespace apollo { namespace cyber { namespace transport { class IntraTranceiverTest : public ::testing::Test { protected: using TransmitterPtr = std::shared_ptr<Transmitter<proto::UnitTest>>; using ReceiverPtr = std::shared_ptr<Receiver<proto::UnitTest>>; IntraTranceiverTest() : channel_name_("intra_channel") {} virtual ~IntraTranceiverTest() {} virtual void SetUp() { RoleAttributes attr; attr.set_channel_name(channel_name_); transmitter_a_ = std::make_shared<IntraTransmitter<proto::UnitTest>>(attr); transmitter_b_ = std::make_shared<IntraTransmitter<proto::UnitTest>>(attr); transmitter_a_->Enable(); transmitter_b_->Enable(); } virtual void TearDown() { transmitter_a_ = nullptr; transmitter_b_ = nullptr; } std::string channel_name_; TransmitterPtr transmitter_a_ = nullptr; TransmitterPtr transmitter_b_ = nullptr; }; TEST_F(IntraTranceiverTest, constructor) { RoleAttributes attr; TransmitterPtr transmitter = std::make_shared<IntraTransmitter<proto::UnitTest>>(attr); ReceiverPtr receiver = std::make_shared<IntraReceiver<proto::UnitTest>>(attr, nullptr); EXPECT_EQ(transmitter->seq_num(), 0); auto& transmitter_id = transmitter->id(); auto& receiver_id = receiver->id(); EXPECT_NE(transmitter_id.ToString(), receiver_id.ToString()); } TEST_F(IntraTranceiverTest, enable_and_disable) { // repeated call transmitter_a_->Enable(); std::vector<proto::UnitTest> msgs; RoleAttributes attr; attr.set_channel_name(channel_name_); ReceiverPtr receiver = std::make_shared<IntraReceiver<proto::UnitTest>>( attr, [&msgs](const std::shared_ptr<proto::UnitTest>& msg, const MessageInfo& msg_info, const RoleAttributes& attr) { (void)msg_info; (void)attr; msgs.emplace_back(*msg); }); receiver->Enable(); // repeated call receiver->Enable(); ReceiverPtr receiver_null_cb = std::make_shared<IntraReceiver<proto::UnitTest>>(attr, nullptr); receiver_null_cb->Enable(); auto msg = std::make_shared<proto::UnitTest>(); msg->set_class_name("IntraTranceiverTest"); msg->set_case_name("enable_and_disable"); EXPECT_TRUE(transmitter_a_->Transmit(msg)); EXPECT_EQ(msgs.size(), 1); EXPECT_TRUE(transmitter_b_->Transmit(msg)); EXPECT_EQ(msgs.size(), 2); for (auto& item : msgs) { EXPECT_EQ(item.class_name(), "IntraTranceiverTest"); EXPECT_EQ(item.case_name(), "enable_and_disable"); } transmitter_b_->Disable(receiver->attributes()); EXPECT_FALSE(transmitter_b_->Transmit(msg)); transmitter_b_->Enable(receiver->attributes()); auto& transmitter_b_attr = transmitter_b_->attributes(); receiver->Disable(); receiver->Enable(transmitter_b_attr); msgs.clear(); EXPECT_TRUE(transmitter_a_->Transmit(msg)); EXPECT_EQ(msgs.size(), 0); EXPECT_TRUE(transmitter_b_->Transmit(msg)); EXPECT_EQ(msgs.size(), 1); for (auto& item : msgs) { EXPECT_EQ(item.class_name(), "IntraTranceiverTest"); EXPECT_EQ(item.case_name(), "enable_and_disable"); } receiver->Disable(transmitter_b_attr); msgs.clear(); EXPECT_TRUE(transmitter_b_->Transmit(msg)); EXPECT_EQ(msgs.size(), 0); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/integration_test/hybrid_transceiver_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 <memory> #include <string> #include <thread> #include <vector> #include "gtest/gtest.h" #include "cyber/common/global_data.h" #include "cyber/common/util.h" #include "cyber/init.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/transport/qos/qos_profile_conf.h" #include "cyber/transport/receiver/hybrid_receiver.h" #include "cyber/transport/transmitter/hybrid_transmitter.h" #include "cyber/transport/transport.h" namespace apollo { namespace cyber { namespace transport { class HybridTransceiverTest : public ::testing::Test { protected: using TransmitterPtr = std::shared_ptr<Transmitter<proto::UnitTest>>; using ReceiverPtr = std::shared_ptr<Receiver<proto::UnitTest>>; HybridTransceiverTest() : channel_name_("hybrid_channel") {} virtual ~HybridTransceiverTest() {} virtual void SetUp() { RoleAttributes attr; attr.set_host_name(common::GlobalData::Instance()->HostName()); attr.set_host_ip(common::GlobalData::Instance()->HostIp()); attr.set_process_id(common::GlobalData::Instance()->ProcessId()); attr.set_channel_name(channel_name_); attr.set_channel_id(common::Hash(channel_name_)); attr.mutable_qos_profile()->CopyFrom(QosProfileConf::QOS_PROFILE_DEFAULT); transmitter_a_ = std::make_shared<HybridTransmitter<proto::UnitTest>>( attr, Transport::Instance()->participant()); attr.set_process_id(common::GlobalData::Instance()->ProcessId() + 1); attr.mutable_qos_profile()->CopyFrom(QosProfileConf::QOS_PROFILE_DEFAULT); transmitter_b_ = std::make_shared<HybridTransmitter<proto::UnitTest>>( attr, Transport::Instance()->participant()); } virtual void TearDown() { transmitter_a_ = nullptr; transmitter_b_ = nullptr; } std::string channel_name_; TransmitterPtr transmitter_a_ = nullptr; TransmitterPtr transmitter_b_ = nullptr; }; TEST_F(HybridTransceiverTest, constructor) { RoleAttributes attr; TransmitterPtr transmitter = std::make_shared<HybridTransmitter<proto::UnitTest>>( attr, Transport::Instance()->participant()); ReceiverPtr receiver = std::make_shared<HybridReceiver<proto::UnitTest>>( attr, nullptr, Transport::Instance()->participant()); EXPECT_EQ(transmitter->seq_num(), 0); auto& transmitter_id = transmitter->id(); auto& receiver_id = receiver->id(); EXPECT_NE(transmitter_id.ToString(), receiver_id.ToString()); } TEST_F(HybridTransceiverTest, enable_and_disable_with_param_no_relation) { RoleAttributes attr; attr.set_host_name(common::GlobalData::Instance()->HostName()); attr.set_process_id(common::GlobalData::Instance()->ProcessId()); attr.mutable_qos_profile()->CopyFrom(QosProfileConf::QOS_PROFILE_DEFAULT); attr.set_channel_name("enable_and_disable_with_param_no_relation"); attr.set_channel_id( common::Hash("enable_and_disable_with_param_no_relation")); std::mutex mtx; std::vector<proto::UnitTest> msgs; ReceiverPtr receiver_a = std::make_shared<HybridReceiver<proto::UnitTest>>( attr, [&](const std::shared_ptr<proto::UnitTest>& msg, const MessageInfo& msg_info, const RoleAttributes& attr) { (void)msg_info; (void)attr; std::lock_guard<std::mutex> lock(mtx); msgs.emplace_back(*msg); }, Transport::Instance()->participant()); ReceiverPtr receiver_b = std::make_shared<HybridReceiver<proto::UnitTest>>( attr, [&](const std::shared_ptr<proto::UnitTest>& msg, const MessageInfo& msg_info, const RoleAttributes& attr) { (void)msg_info; (void)attr; std::lock_guard<std::mutex> lock(mtx); msgs.emplace_back(*msg); }, Transport::Instance()->participant()); auto msg = std::make_shared<proto::UnitTest>(); msg->set_class_name("HybridTransceiverTest"); msg->set_case_name("enable_and_disable_with_param_no_relation"); transmitter_a_->Enable(receiver_a->attributes()); transmitter_a_->Enable(receiver_b->attributes()); receiver_a->Enable(transmitter_a_->attributes()); receiver_b->Enable(transmitter_a_->attributes()); transmitter_a_->Transmit(msg); std::this_thread::sleep_for(std::chrono::milliseconds(200)); EXPECT_EQ(msgs.size(), 0); msgs.clear(); transmitter_a_->Disable(receiver_a->attributes()); transmitter_a_->Disable(receiver_b->attributes()); receiver_a->Disable(transmitter_a_->attributes()); receiver_b->Disable(transmitter_a_->attributes()); } TEST_F(HybridTransceiverTest, enable_and_disable_with_param_same_process) { RoleAttributes attr; attr.set_host_name(common::GlobalData::Instance()->HostName()); attr.set_process_id(common::GlobalData::Instance()->ProcessId()); attr.mutable_qos_profile()->CopyFrom(QosProfileConf::QOS_PROFILE_DEFAULT); attr.set_channel_name(channel_name_); attr.set_channel_id(common::Hash(channel_name_)); std::mutex mtx; std::vector<proto::UnitTest> msgs; ReceiverPtr receiver_a = std::make_shared<HybridReceiver<proto::UnitTest>>( attr, [&](const std::shared_ptr<proto::UnitTest>& msg, const MessageInfo& msg_info, const RoleAttributes& attr) { (void)msg_info; (void)attr; std::lock_guard<std::mutex> lock(mtx); msgs.emplace_back(*msg); }, Transport::Instance()->participant()); ReceiverPtr receiver_b = std::make_shared<HybridReceiver<proto::UnitTest>>( attr, [&](const std::shared_ptr<proto::UnitTest>& msg, const MessageInfo& msg_info, const RoleAttributes& attr) { (void)msg_info; (void)attr; std::lock_guard<std::mutex> lock(mtx); msgs.emplace_back(*msg); }, Transport::Instance()->participant()); std::string class_name("HybridTransceiverTest"); std::string case_name("enable_and_disable_with_param_same_process"); auto msg = std::make_shared<proto::UnitTest>(); msg->set_class_name(class_name); msg->set_case_name(case_name); // this msg will lose transmitter_a_->Transmit(msg); transmitter_a_->Enable(receiver_a->attributes()); transmitter_a_->Enable(receiver_b->attributes()); receiver_a->Enable(transmitter_a_->attributes()); receiver_b->Enable(transmitter_a_->attributes()); // repeated call receiver_b->Enable(transmitter_a_->attributes()); transmitter_a_->Transmit(msg); std::this_thread::sleep_for(std::chrono::milliseconds(200)); EXPECT_EQ(msgs.size(), 2); for (auto& item : msgs) { EXPECT_EQ(item.class_name(), class_name); EXPECT_EQ(item.case_name(), case_name); } msgs.clear(); transmitter_a_->Disable(receiver_a->attributes()); transmitter_a_->Disable(receiver_b->attributes()); receiver_a->Disable(transmitter_a_->attributes()); receiver_b->Disable(transmitter_a_->attributes()); // repeated call receiver_b->Disable(transmitter_a_->attributes()); transmitter_a_->Transmit(msg); std::this_thread::sleep_for(std::chrono::milliseconds(200)); EXPECT_EQ(msgs.size(), 0); } TEST_F(HybridTransceiverTest, enable_and_disable_with_param_same_host_diff_proc) { RoleAttributes attr; attr.set_host_name(common::GlobalData::Instance()->HostName()); attr.set_process_id(1); attr.mutable_qos_profile()->CopyFrom(QosProfileConf::QOS_PROFILE_DEFAULT); attr.set_channel_name(channel_name_); attr.set_channel_id(common::Hash(channel_name_)); std::mutex mtx; std::vector<proto::UnitTest> msgs; ReceiverPtr receiver_a = std::make_shared<HybridReceiver<proto::UnitTest>>( attr, [&](const std::shared_ptr<proto::UnitTest>& msg, const MessageInfo& msg_info, const RoleAttributes& attr) { (void)msg_info; (void)attr; std::lock_guard<std::mutex> lock(mtx); msgs.emplace_back(*msg); }, Transport::Instance()->participant()); ReceiverPtr receiver_b = std::make_shared<HybridReceiver<proto::UnitTest>>( attr, [&](const std::shared_ptr<proto::UnitTest>& msg, const MessageInfo& msg_info, const RoleAttributes& attr) { (void)msg_info; (void)attr; std::lock_guard<std::mutex> lock(mtx); msgs.emplace_back(*msg); }, Transport::Instance()->participant()); std::string class_name("HybridTransceiverTest"); std::string case_name("enable_and_disable_with_param_same_host_diff_proc"); auto msg = std::make_shared<proto::UnitTest>(); msg->set_class_name(class_name); msg->set_case_name(case_name); transmitter_b_->Transmit(msg); transmitter_b_->Enable(receiver_a->attributes()); transmitter_b_->Enable(receiver_b->attributes()); receiver_a->Enable(transmitter_b_->attributes()); receiver_b->Enable(transmitter_b_->attributes()); std::this_thread::sleep_for(std::chrono::milliseconds(200)); transmitter_b_->Transmit(msg); std::this_thread::sleep_for(std::chrono::milliseconds(200)); // 1 from receiver_b, 1 from receiver_a EXPECT_EQ(msgs.size(), 2); for (auto& item : msgs) { EXPECT_EQ(item.class_name(), class_name); EXPECT_EQ(item.case_name(), case_name); } msgs.clear(); transmitter_b_->Disable(receiver_a->attributes()); transmitter_b_->Disable(receiver_b->attributes()); receiver_a->Disable(transmitter_b_->attributes()); receiver_b->Disable(transmitter_b_->attributes()); transmitter_b_->Transmit(msg); std::this_thread::sleep_for(std::chrono::milliseconds(200)); EXPECT_EQ(msgs.size(), 0); } TEST_F(HybridTransceiverTest, enable_and_disable_with_param_diff_host) { RoleAttributes attr; attr.set_host_name("sorac"); attr.set_process_id(12345); attr.mutable_qos_profile()->CopyFrom(QosProfileConf::QOS_PROFILE_DEFAULT); attr.set_channel_name(channel_name_); attr.set_channel_id(common::Hash(channel_name_)); std::mutex mtx; std::vector<proto::UnitTest> msgs; ReceiverPtr receiver_a = std::make_shared<HybridReceiver<proto::UnitTest>>( attr, [&](const std::shared_ptr<proto::UnitTest>& msg, const MessageInfo& msg_info, const RoleAttributes& attr) { (void)msg_info; (void)attr; std::lock_guard<std::mutex> lock(mtx); msgs.emplace_back(*msg); }, Transport::Instance()->participant()); ReceiverPtr receiver_b = std::make_shared<HybridReceiver<proto::UnitTest>>( attr, [&](const std::shared_ptr<proto::UnitTest>& msg, const MessageInfo& msg_info, const RoleAttributes& attr) { (void)msg_info; (void)attr; std::lock_guard<std::mutex> lock(mtx); msgs.emplace_back(*msg); }, Transport::Instance()->participant()); std::string class_name("HybridTransceiverTest"); std::string case_name("enable_and_disable_with_param_same_host_diff_proc"); auto msg = std::make_shared<proto::UnitTest>(); msg->set_class_name(class_name); msg->set_case_name(case_name); transmitter_b_->Enable(receiver_a->attributes()); transmitter_b_->Enable(receiver_b->attributes()); receiver_a->Enable(transmitter_b_->attributes()); receiver_b->Enable(transmitter_b_->attributes()); std::this_thread::sleep_for(std::chrono::milliseconds(200)); transmitter_b_->Transmit(msg); std::this_thread::sleep_for(std::chrono::milliseconds(200)); // 1 from receiver_b, 1 from receiver_a EXPECT_EQ(msgs.size(), 2); for (auto& item : msgs) { EXPECT_EQ(item.class_name(), class_name); EXPECT_EQ(item.case_name(), case_name); } msgs.clear(); transmitter_b_->Disable(receiver_a->attributes()); transmitter_b_->Disable(receiver_b->attributes()); transmitter_b_->Transmit(msg); std::this_thread::sleep_for(std::chrono::milliseconds(200)); EXPECT_EQ(msgs.size(), 0); } } // namespace transport } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); apollo::cyber::Init(argv[0]); apollo::cyber::transport::Transport::Instance(); auto res = RUN_ALL_TESTS(); apollo::cyber::transport::Transport::Instance()->Shutdown(); return res; }
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/integration_test/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") cc_test( name = "hybrid_transceiver_test", size = "small", srcs = ["hybrid_transceiver_test.cc"], deps = [ "//cyber:cyber_core", "//cyber/proto:unit_test_cc_proto", "@com_google_googletest//:gtest", ], ) cc_test( name = "intra_transceiver_test", size = "small", srcs = ["intra_transceiver_test.cc"], deps = [ "//cyber:cyber_core", "//cyber/proto:unit_test_cc_proto", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "rtps_transceiver_test", size = "small", srcs = ["rtps_transceiver_test.cc"], deps = [ "//cyber:cyber_core", "//cyber/proto:unit_test_cc_proto", "@com_google_googletest//:gtest", ], ) cc_test( name = "shm_transceiver_test", size = "small", srcs = ["shm_transceiver_test.cc"], deps = [ "//cyber:cyber_core", "//cyber/proto:unit_test_cc_proto", "@com_google_googletest//:gtest", ], ) cpplint()
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/integration_test/rtps_transceiver_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/transport/transmitter/rtps_transmitter.h" #include <memory> #include <string> #include <thread> #include <vector> #include "gtest/gtest.h" #include "cyber/common/util.h" #include "cyber/init.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/transport/receiver/rtps_receiver.h" #include "cyber/transport/transport.h" namespace apollo { namespace cyber { namespace transport { class RtpsTransceiverTest : public ::testing::Test { protected: using TransmitterPtr = std::shared_ptr<Transmitter<proto::UnitTest>>; using ReceiverPtr = std::shared_ptr<Receiver<proto::UnitTest>>; RtpsTransceiverTest() : channel_name_("rtps_channel") {} virtual ~RtpsTransceiverTest() {} virtual void SetUp() { RoleAttributes attr; attr.set_channel_name(channel_name_); attr.set_channel_id(common::Hash(channel_name_)); transmitter_a_ = std::make_shared<RtpsTransmitter<proto::UnitTest>>( attr, Transport::Instance()->participant()); transmitter_b_ = std::make_shared<RtpsTransmitter<proto::UnitTest>>( attr, Transport::Instance()->participant()); transmitter_a_->Enable(); transmitter_b_->Enable(); } virtual void TearDown() { transmitter_a_ = nullptr; transmitter_b_ = nullptr; } std::string channel_name_; TransmitterPtr transmitter_a_ = nullptr; TransmitterPtr transmitter_b_ = nullptr; }; TEST_F(RtpsTransceiverTest, constructor) { RoleAttributes attr; TransmitterPtr transmitter = std::make_shared<RtpsTransmitter<proto::UnitTest>>( attr, Transport::Instance()->participant()); ReceiverPtr receiver = std::make_shared<RtpsReceiver<proto::UnitTest>>(attr, nullptr); EXPECT_EQ(transmitter->seq_num(), 0); auto& transmitter_id = transmitter->id(); auto& receiver_id = receiver->id(); EXPECT_NE(transmitter_id.ToString(), receiver_id.ToString()); } TEST_F(RtpsTransceiverTest, enable_and_disable) { // repeated call transmitter_a_->Enable(); std::vector<proto::UnitTest> msgs; RoleAttributes attr; attr.set_channel_name(channel_name_); attr.set_channel_id(common::Hash(channel_name_)); ReceiverPtr receiver = std::make_shared<RtpsReceiver<proto::UnitTest>>( attr, [&msgs](const std::shared_ptr<proto::UnitTest>& msg, const MessageInfo& msg_info, const RoleAttributes& attr) { (void)msg_info; (void)attr; msgs.emplace_back(*msg); }); receiver->Enable(); // repeated call receiver->Enable(); ReceiverPtr receiver_null_cb = std::make_shared<RtpsReceiver<proto::UnitTest>>(attr, nullptr); receiver_null_cb->Enable(); auto msg = std::make_shared<proto::UnitTest>(); msg->set_class_name("RtpsTransceiverTest"); msg->set_case_name("enable_and_disable"); EXPECT_TRUE(transmitter_a_->Transmit(msg)); std::this_thread::sleep_for(std::chrono::milliseconds(200)); EXPECT_EQ(msgs.size(), 1); EXPECT_TRUE(transmitter_b_->Transmit(msg)); std::this_thread::sleep_for(std::chrono::milliseconds(200)); EXPECT_EQ(msgs.size(), 2); for (auto& item : msgs) { EXPECT_EQ(item.class_name(), "RtpsTransceiverTest"); EXPECT_EQ(item.case_name(), "enable_and_disable"); } transmitter_b_->Disable(receiver->attributes()); EXPECT_FALSE(transmitter_b_->Transmit(msg)); transmitter_b_->Enable(receiver->attributes()); auto& transmitter_b_attr = transmitter_b_->attributes(); receiver->Disable(); receiver->Enable(transmitter_b_attr); msgs.clear(); EXPECT_TRUE(transmitter_a_->Transmit(msg)); std::this_thread::sleep_for(std::chrono::milliseconds(200)); EXPECT_EQ(msgs.size(), 0); EXPECT_TRUE(transmitter_b_->Transmit(msg)); std::this_thread::sleep_for(std::chrono::milliseconds(200)); EXPECT_EQ(msgs.size(), 1); for (auto& item : msgs) { EXPECT_EQ(item.class_name(), "RtpsTransceiverTest"); EXPECT_EQ(item.case_name(), "enable_and_disable"); } receiver->Disable(transmitter_b_attr); msgs.clear(); EXPECT_TRUE(transmitter_b_->Transmit(msg)); std::this_thread::sleep_for(std::chrono::milliseconds(200)); EXPECT_EQ(msgs.size(), 0); } } // namespace transport } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); apollo::cyber::Init(argv[0]); apollo::cyber::transport::Transport::Instance(); auto res = RUN_ALL_TESTS(); apollo::cyber::transport::Transport::Instance()->Shutdown(); return res; }
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/integration_test/shm_transceiver_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 <memory> #include <string> #include <thread> #include <vector> #include "gtest/gtest.h" #include "cyber/common/global_data.h" #include "cyber/common/util.h" #include "cyber/init.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/transport/receiver/shm_receiver.h" #include "cyber/transport/transmitter/shm_transmitter.h" #include "cyber/transport/transport.h" namespace apollo { namespace cyber { namespace transport { class ShmTransceiverTest : public ::testing::Test { protected: using TransmitterPtr = std::shared_ptr<Transmitter<proto::UnitTest>>; using ReceiverPtr = std::shared_ptr<Receiver<proto::UnitTest>>; ShmTransceiverTest() : channel_name_("shm_channel") {} virtual ~ShmTransceiverTest() {} virtual void SetUp() { RoleAttributes attr; attr.set_host_name(common::GlobalData::Instance()->HostName()); attr.set_host_ip(common::GlobalData::Instance()->HostIp()); attr.set_channel_name(channel_name_); attr.set_channel_id(common::Hash(channel_name_)); transmitter_a_ = std::make_shared<ShmTransmitter<proto::UnitTest>>(attr); transmitter_b_ = std::make_shared<ShmTransmitter<proto::UnitTest>>(attr); transmitter_a_->Enable(); transmitter_b_->Enable(); } virtual void TearDown() { transmitter_a_ = nullptr; transmitter_b_ = nullptr; } std::string channel_name_; TransmitterPtr transmitter_a_ = nullptr; TransmitterPtr transmitter_b_ = nullptr; }; TEST_F(ShmTransceiverTest, constructor) { RoleAttributes attr; TransmitterPtr transmitter = std::make_shared<ShmTransmitter<proto::UnitTest>>(attr); ReceiverPtr receiver = std::make_shared<ShmReceiver<proto::UnitTest>>(attr, nullptr); EXPECT_EQ(transmitter->seq_num(), 0); auto& transmitter_id = transmitter->id(); auto& receiver_id = receiver->id(); EXPECT_NE(transmitter_id.ToString(), receiver_id.ToString()); } TEST_F(ShmTransceiverTest, enable_and_disable) { // repeated call transmitter_a_->Enable(); std::vector<proto::UnitTest> msgs; RoleAttributes attr; attr.set_channel_name(channel_name_); attr.set_channel_id(common::Hash(channel_name_)); ReceiverPtr receiver = std::make_shared<ShmReceiver<proto::UnitTest>>( attr, [&msgs](const std::shared_ptr<proto::UnitTest>& msg, const MessageInfo& msg_info, const RoleAttributes& attr) { (void)msg_info; (void)attr; msgs.emplace_back(*msg); }); receiver->Enable(); // repeated call receiver->Enable(); ReceiverPtr receiver_null_cb = std::make_shared<ShmReceiver<proto::UnitTest>>(attr, nullptr); receiver_null_cb->Enable(); auto msg = std::make_shared<proto::UnitTest>(); msg->set_class_name("ShmTransceiverTest"); msg->set_case_name("enable_and_disable"); EXPECT_TRUE(transmitter_a_->Transmit(msg)); std::this_thread::sleep_for(std::chrono::milliseconds(100)); EXPECT_EQ(msgs.size(), 1); EXPECT_TRUE(transmitter_b_->Transmit(msg)); std::this_thread::sleep_for(std::chrono::milliseconds(100)); EXPECT_EQ(msgs.size(), 2); for (auto& item : msgs) { EXPECT_EQ(item.class_name(), "ShmTransceiverTest"); EXPECT_EQ(item.case_name(), "enable_and_disable"); } transmitter_b_->Disable(receiver->attributes()); EXPECT_FALSE(transmitter_b_->Transmit(msg)); transmitter_b_->Enable(receiver->attributes()); auto& transmitter_b_attr = transmitter_b_->attributes(); receiver->Disable(); receiver->Enable(transmitter_b_attr); msgs.clear(); EXPECT_TRUE(transmitter_a_->Transmit(msg)); std::this_thread::sleep_for(std::chrono::milliseconds(100)); EXPECT_EQ(msgs.size(), 0); EXPECT_TRUE(transmitter_b_->Transmit(msg)); std::this_thread::sleep_for(std::chrono::milliseconds(100)); EXPECT_EQ(msgs.size(), 1); for (auto& item : msgs) { EXPECT_EQ(item.class_name(), "ShmTransceiverTest"); EXPECT_EQ(item.case_name(), "enable_and_disable"); } receiver->Disable(transmitter_b_attr); msgs.clear(); EXPECT_TRUE(transmitter_b_->Transmit(msg)); std::this_thread::sleep_for(std::chrono::milliseconds(100)); EXPECT_EQ(msgs.size(), 0); } } // namespace transport } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); apollo::cyber::Init(argv[0]); apollo::cyber::transport::Transport::Instance(); auto res = RUN_ALL_TESTS(); apollo::cyber::transport::Transport::Instance()->Shutdown(); return res; }
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/readable_info.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/transport/shm/readable_info.h" #include <cstring> #include "cyber/common/log.h" namespace apollo { namespace cyber { namespace transport { const size_t ReadableInfo::kSize = sizeof(uint64_t) * 2 + sizeof(uint32_t); ReadableInfo::ReadableInfo() : host_id_(0), block_index_(0), channel_id_(0) {} ReadableInfo::ReadableInfo(uint64_t host_id, uint32_t block_index, uint64_t channel_id) : host_id_(host_id), block_index_(block_index), channel_id_(channel_id) {} ReadableInfo::~ReadableInfo() {} ReadableInfo& ReadableInfo::operator=(const ReadableInfo& other) { if (this != &other) { this->host_id_ = other.host_id_; this->block_index_ = other.block_index_; this->channel_id_ = other.channel_id_; } return *this; } bool ReadableInfo::SerializeTo(std::string* dst) const { RETURN_VAL_IF_NULL(dst, false); dst->assign(reinterpret_cast<char*>(const_cast<uint64_t*>(&host_id_)), sizeof(host_id_)); dst->append(reinterpret_cast<char*>(const_cast<uint32_t*>(&block_index_)), sizeof(block_index_)); dst->append(reinterpret_cast<char*>(const_cast<uint64_t*>(&channel_id_)), sizeof(channel_id_)); return true; } bool ReadableInfo::DeserializeFrom(const std::string& src) { return DeserializeFrom(src.data(), src.size()); } bool ReadableInfo::DeserializeFrom(const char* src, std::size_t len) { RETURN_VAL_IF_NULL(src, false); if (len != kSize) { AWARN << "src size[" << len << "] mismatch."; return false; } char* ptr = const_cast<char*>(src); memcpy(reinterpret_cast<char*>(&host_id_), ptr, sizeof(host_id_)); ptr += sizeof(host_id_); memcpy(reinterpret_cast<char*>(&block_index_), ptr, sizeof(block_index_)); ptr += sizeof(block_index_); memcpy(reinterpret_cast<char*>(&channel_id_), ptr, sizeof(channel_id_)); return true; } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/condition_notifier_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/transport/shm/condition_notifier.h" #include "gtest/gtest.h" namespace apollo { namespace cyber { namespace transport { TEST(ConditionNotifierTest, constructor) { auto notifier = ConditionNotifier::Instance(); EXPECT_NE(notifier, nullptr); } TEST(ConditionNotifierTest, notify_listen) { auto notifier = ConditionNotifier::Instance(); ReadableInfo readable_info; while (notifier->Listen(100, &readable_info)) { } EXPECT_FALSE(notifier->Listen(100, &readable_info)); EXPECT_TRUE(notifier->Notify(readable_info)); EXPECT_TRUE(notifier->Listen(100, &readable_info)); EXPECT_FALSE(notifier->Listen(100, &readable_info)); EXPECT_TRUE(notifier->Notify(readable_info)); EXPECT_TRUE(notifier->Notify(readable_info)); EXPECT_TRUE(notifier->Listen(100, &readable_info)); EXPECT_TRUE(notifier->Listen(100, &readable_info)); EXPECT_FALSE(notifier->Listen(100, &readable_info)); } TEST(ConditionNotifierTest, shutdown) { auto notifier = ConditionNotifier::Instance(); notifier->Shutdown(); ReadableInfo readable_info; EXPECT_FALSE(notifier->Notify(readable_info)); EXPECT_FALSE(notifier->Listen(100, &readable_info)); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/xsi_segment.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_TRANSPORT_SHM_XSI_SEGMENT_H_ #define CYBER_TRANSPORT_SHM_XSI_SEGMENT_H_ #include "cyber/transport/shm/segment.h" namespace apollo { namespace cyber { namespace transport { class XsiSegment : public Segment { public: explicit XsiSegment(uint64_t channel_id); virtual ~XsiSegment(); static const char* Type() { return "xsi"; } private: void Reset() override; bool Remove() override; bool OpenOnly() override; bool OpenOrCreate() override; key_t key_; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_SHM_XSI_SEGMENT_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/segment.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/transport/shm/segment.h" #include "cyber/common/log.h" #include "cyber/common/util.h" #include "cyber/transport/shm/shm_conf.h" namespace apollo { namespace cyber { namespace transport { Segment::Segment(uint64_t channel_id) : init_(false), conf_(), channel_id_(channel_id), state_(nullptr), blocks_(nullptr), managed_shm_(nullptr), block_buf_lock_(), block_buf_addrs_() {} bool Segment::AcquireBlockToWrite(std::size_t msg_size, WritableBlock* writable_block) { RETURN_VAL_IF_NULL(writable_block, false); if (!init_ && !OpenOrCreate()) { AERROR << "create shm failed, can't write now."; return false; } bool result = true; if (state_->need_remap()) { result = Remap(); } if (msg_size > conf_.ceiling_msg_size()) { AINFO << "msg_size: " << msg_size << " larger than current shm_buffer_size: " << conf_.ceiling_msg_size() << " , need recreate."; result = Recreate(msg_size); } if (!result) { AERROR << "segment update failed."; return false; } uint32_t index = GetNextWritableBlockIndex(); writable_block->index = index; writable_block->block = &blocks_[index]; writable_block->buf = block_buf_addrs_[index]; return true; } void Segment::ReleaseWrittenBlock(const WritableBlock& writable_block) { auto index = writable_block.index; if (index >= conf_.block_num()) { return; } blocks_[index].ReleaseWriteLock(); } bool Segment::AcquireBlockToRead(ReadableBlock* readable_block) { RETURN_VAL_IF_NULL(readable_block, false); if (!init_ && !OpenOnly()) { AERROR << "failed to open shared memory, can't read now."; return false; } auto index = readable_block->index; if (index >= conf_.block_num()) { AERROR << "invalid block_index[" << index << "]."; return false; } bool result = true; if (state_->need_remap()) { result = Remap(); } if (!result) { AERROR << "segment update failed."; return false; } if (!blocks_[index].TryLockForRead()) { return false; } readable_block->block = blocks_ + index; readable_block->buf = block_buf_addrs_[index]; return true; } void Segment::ReleaseReadBlock(const ReadableBlock& readable_block) { auto index = readable_block.index; if (index >= conf_.block_num()) { return; } blocks_[index].ReleaseReadLock(); } bool Segment::Destroy() { if (!init_) { return true; } init_ = false; try { state_->DecreaseReferenceCounts(); uint32_t reference_counts = state_->reference_counts(); if (reference_counts == 0) { return Remove(); } } catch (...) { AERROR << "exception."; return false; } ADEBUG << "destroy."; return true; } bool Segment::Remap() { init_ = false; ADEBUG << "before reset."; Reset(); ADEBUG << "after reset."; return OpenOnly(); } bool Segment::Recreate(const uint64_t& msg_size) { init_ = false; state_->set_need_remap(true); Reset(); Remove(); conf_.Update(msg_size); return OpenOrCreate(); } uint32_t Segment::GetNextWritableBlockIndex() { const auto block_num = conf_.block_num(); while (1) { uint32_t try_idx = state_->FetchAddSeq(1) % block_num; if (blocks_[try_idx].TryLockForWrite()) { return try_idx; } } return 0; } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/block.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/transport/shm/block.h" #include "cyber/common/log.h" namespace apollo { namespace cyber { namespace transport { const int32_t Block::kRWLockFree = 0; const int32_t Block::kWriteExclusive = -1; const int32_t Block::kMaxTryLockTimes = 5; Block::Block() : msg_size_(0), msg_info_size_(0) {} Block::~Block() {} bool Block::TryLockForWrite() { int32_t rw_lock_free = kRWLockFree; if (!lock_num_.compare_exchange_weak(rw_lock_free, kWriteExclusive, std::memory_order_acq_rel, std::memory_order_relaxed)) { ADEBUG << "lock num: " << lock_num_.load(); return false; } return true; } bool Block::TryLockForRead() { int32_t lock_num = lock_num_.load(); if (lock_num < kRWLockFree) { AINFO << "block is being written."; return false; } int32_t try_times = 0; while (!lock_num_.compare_exchange_weak(lock_num, lock_num + 1, std::memory_order_acq_rel, std::memory_order_relaxed)) { ++try_times; if (try_times == kMaxTryLockTimes) { AINFO << "fail to add read lock num, curr num: " << lock_num; return false; } lock_num = lock_num_.load(); if (lock_num < kRWLockFree) { AINFO << "block is being written."; return false; } } return true; } void Block::ReleaseWriteLock() { lock_num_.fetch_add(1); } void Block::ReleaseReadLock() { lock_num_.fetch_sub(1); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/segment_factory.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_TRANSPORT_SHM_SEGMENT_FACTORY_H_ #define CYBER_TRANSPORT_SHM_SEGMENT_FACTORY_H_ #include "cyber/transport/shm/segment.h" namespace apollo { namespace cyber { namespace transport { class SegmentFactory { public: static SegmentPtr CreateSegment(uint64_t channel_id); }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_SHM_SEGMENT_FACTORY_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/state.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/transport/shm/state.h" namespace apollo { namespace cyber { namespace transport { State::State(const uint64_t& ceiling_msg_size) : ceiling_msg_size_(ceiling_msg_size) {} State::~State() {} } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/segment.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_TRANSPORT_SHM_SEGMENT_H_ #define CYBER_TRANSPORT_SHM_SEGMENT_H_ #include <memory> #include <mutex> #include <string> #include <unordered_map> #include "cyber/transport/shm/block.h" #include "cyber/transport/shm/shm_conf.h" #include "cyber/transport/shm/state.h" namespace apollo { namespace cyber { namespace transport { class Segment; using SegmentPtr = std::shared_ptr<Segment>; struct WritableBlock { uint32_t index = 0; Block* block = nullptr; uint8_t* buf = nullptr; }; using ReadableBlock = WritableBlock; class Segment { public: explicit Segment(uint64_t channel_id); virtual ~Segment() {} bool AcquireBlockToWrite(std::size_t msg_size, WritableBlock* writable_block); void ReleaseWrittenBlock(const WritableBlock& writable_block); bool AcquireBlockToRead(ReadableBlock* readable_block); void ReleaseReadBlock(const ReadableBlock& readable_block); protected: virtual bool Destroy(); virtual void Reset() = 0; virtual bool Remove() = 0; virtual bool OpenOnly() = 0; virtual bool OpenOrCreate() = 0; bool init_; ShmConf conf_; uint64_t channel_id_; State* state_; Block* blocks_; void* managed_shm_; std::mutex block_buf_lock_; std::unordered_map<uint32_t, uint8_t*> block_buf_addrs_; private: bool Remap(); bool Recreate(const uint64_t& msg_size); uint32_t GetNextWritableBlockIndex(); }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_SHM_SEGMENT_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/segment_factory.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/transport/shm/segment_factory.h" #include <memory> #include <string> #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/transport/shm/posix_segment.h" #include "cyber/transport/shm/xsi_segment.h" namespace apollo { namespace cyber { namespace transport { using apollo::cyber::common::GlobalData; auto SegmentFactory::CreateSegment(uint64_t channel_id) -> SegmentPtr { std::string segment_type(XsiSegment::Type()); auto& shm_conf = GlobalData::Instance()->Config(); if (shm_conf.has_transport_conf() && shm_conf.transport_conf().has_shm_conf() && shm_conf.transport_conf().shm_conf().has_shm_type()) { segment_type = shm_conf.transport_conf().shm_conf().shm_type(); } ADEBUG << "segment type: " << segment_type; if (segment_type == PosixSegment::Type()) { return std::make_shared<PosixSegment>(channel_id); } return std::make_shared<XsiSegment>(channel_id); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/multicast_notifier.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/transport/shm/multicast_notifier.h" #include <arpa/inet.h> #include <fcntl.h> #include <poll.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <cstring> #include <string> #include "cyber/common/global_data.h" #include "cyber/common/log.h" namespace apollo { namespace cyber { namespace transport { using common::GlobalData; MulticastNotifier::MulticastNotifier() { if (!Init()) { Shutdown(); } } MulticastNotifier::~MulticastNotifier() { Shutdown(); } void MulticastNotifier::Shutdown() { if (is_shutdown_.exchange(true)) { return; } if (notify_fd_ != -1) { close(notify_fd_); notify_fd_ = -1; } memset(&notify_addr_, 0, sizeof(notify_addr_)); if (listen_fd_ != -1) { close(listen_fd_); listen_fd_ = -1; } memset(&listen_addr_, 0, sizeof(listen_addr_)); } bool MulticastNotifier::Notify(const ReadableInfo& info) { if (is_shutdown_.load()) { return false; } std::string info_str; info.SerializeTo(&info_str); ssize_t nbytes = sendto(notify_fd_, info_str.c_str(), info_str.size(), 0, (struct sockaddr*)&notify_addr_, sizeof(notify_addr_)); return nbytes > 0; } bool MulticastNotifier::Listen(int timeout_ms, ReadableInfo* info) { if (is_shutdown_.load()) { return false; } if (info == nullptr) { AERROR << "info nullptr."; return false; } struct pollfd fds; fds.fd = listen_fd_; fds.events = POLLIN; int ready_num = poll(&fds, 1, timeout_ms); if (ready_num > 0) { char buf[32] = {0}; // larger than ReadableInfo::kSize ssize_t nbytes = recvfrom(listen_fd_, buf, 32, 0, nullptr, nullptr); if (nbytes == -1) { AERROR << "fail to recvfrom, " << strerror(errno); return false; } return info->DeserializeFrom(buf, nbytes); } else if (ready_num == 0) { ADEBUG << "timeout, no readableinfo."; } else { if (errno == EINTR) { AINFO << "poll was interrupted."; } else { AERROR << "fail to poll, " << strerror(errno); } } return false; } bool MulticastNotifier::Init() { std::string mcast_ip("239.255.0.100"); uint16_t mcast_port = 8888; auto& g_conf = GlobalData::Instance()->Config(); if (g_conf.has_transport_conf() && g_conf.transport_conf().has_shm_conf() && g_conf.transport_conf().shm_conf().has_shm_locator()) { auto& locator = g_conf.transport_conf().shm_conf().shm_locator(); mcast_ip = locator.ip(); mcast_port = static_cast<uint16_t>(locator.port()); } ADEBUG << "multicast notifier ip: " << mcast_ip; ADEBUG << "multicast notifier port: " << mcast_port; notify_fd_ = socket(AF_INET, SOCK_DGRAM, 0); if (notify_fd_ == -1) { AERROR << "fail to create notify fd, " << strerror(errno); return false; } memset(&notify_addr_, 0, sizeof(notify_addr_)); notify_addr_.sin_family = AF_INET; notify_addr_.sin_addr.s_addr = inet_addr(mcast_ip.c_str()); notify_addr_.sin_port = htons(mcast_port); listen_fd_ = socket(AF_INET, SOCK_DGRAM, 0); if (listen_fd_ == -1) { AERROR << "fail to create listen fd, " << strerror(errno); return false; } if (fcntl(listen_fd_, F_SETFL, O_NONBLOCK) == -1) { AERROR << "fail to set listen fd nonblock, " << strerror(errno); return false; } memset(&listen_addr_, 0, sizeof(listen_addr_)); listen_addr_.sin_family = AF_INET; listen_addr_.sin_addr.s_addr = htonl(INADDR_ANY); listen_addr_.sin_port = htons(mcast_port); int yes = 1; if (setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0) { AERROR << "fail to setsockopt SO_REUSEADDR, " << strerror(errno); return false; } if (bind(listen_fd_, (struct sockaddr*)&listen_addr_, sizeof(listen_addr_)) < 0) { AERROR << "fail to bind addr, " << strerror(errno); return false; } int loop = 1; if (setsockopt(listen_fd_, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)) < 0) { AERROR << "fail to setsockopt IP_MULTICAST_LOOP, " << strerror(errno); return false; } struct ip_mreq mreq; mreq.imr_multiaddr.s_addr = inet_addr(mcast_ip.c_str()); mreq.imr_interface.s_addr = htonl(INADDR_ANY); if (setsockopt(listen_fd_, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) { AERROR << "fail to setsockopt IP_ADD_MEMBERSHIP, " << strerror(errno); return false; } return true; } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/xsi_segment.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/transport/shm/xsi_segment.h" #include <sys/ipc.h> #include <sys/shm.h> #include <sys/types.h> #include "cyber/common/log.h" #include "cyber/common/util.h" #include "cyber/transport/shm/segment.h" #include "cyber/transport/shm/shm_conf.h" namespace apollo { namespace cyber { namespace transport { XsiSegment::XsiSegment(uint64_t channel_id) : Segment(channel_id) { key_ = static_cast<key_t>(channel_id); } XsiSegment::~XsiSegment() { Destroy(); } bool XsiSegment::OpenOrCreate() { if (init_) { return true; } // create managed_shm_ int retry = 0; int shmid = 0; while (retry < 2) { shmid = shmget(key_, conf_.managed_shm_size(), 0644 | IPC_CREAT | IPC_EXCL); if (shmid != -1) { break; } if (EINVAL == errno) { AINFO << "need larger space, recreate."; Reset(); Remove(); ++retry; } else if (EEXIST == errno) { ADEBUG << "shm already exist, open only."; return OpenOnly(); } else { break; } } if (shmid == -1) { AERROR << "create shm failed, error code: " << strerror(errno); return false; } // attach managed_shm_ managed_shm_ = shmat(shmid, nullptr, 0); if (managed_shm_ == reinterpret_cast<void*>(-1)) { AERROR << "attach shm failed, error: " << strerror(errno); shmctl(shmid, IPC_RMID, 0); return false; } // create field state_ state_ = new (managed_shm_) State(conf_.ceiling_msg_size()); if (state_ == nullptr) { AERROR << "create state failed."; shmdt(managed_shm_); managed_shm_ = nullptr; shmctl(shmid, IPC_RMID, 0); return false; } conf_.Update(state_->ceiling_msg_size()); // create field blocks_ blocks_ = new (static_cast<char*>(managed_shm_) + sizeof(State)) Block[conf_.block_num()]; if (blocks_ == nullptr) { AERROR << "create blocks failed."; state_->~State(); state_ = nullptr; shmdt(managed_shm_); managed_shm_ = nullptr; shmctl(shmid, IPC_RMID, 0); return false; } // create block buf uint32_t i = 0; for (; i < conf_.block_num(); ++i) { uint8_t* addr = new (static_cast<char*>(managed_shm_) + sizeof(State) + conf_.block_num() * sizeof(Block) + i * conf_.block_buf_size()) uint8_t[conf_.block_buf_size()]; std::lock_guard<std::mutex> _g(block_buf_lock_); block_buf_addrs_[i] = addr; } if (i != conf_.block_num()) { AERROR << "create block buf failed."; state_->~State(); state_ = nullptr; blocks_ = nullptr; { std::lock_guard<std::mutex> _g(block_buf_lock_); block_buf_addrs_.clear(); } shmdt(managed_shm_); managed_shm_ = nullptr; shmctl(shmid, IPC_RMID, 0); return false; } state_->IncreaseReferenceCounts(); init_ = true; ADEBUG << "open or create true."; return true; } bool XsiSegment::OpenOnly() { if (init_) { return true; } // get managed_shm_ int shmid = shmget(key_, 0, 0644); if (shmid == -1) { AERROR << "get shm failed. error: " << strerror(errno); return false; } // attach managed_shm_ managed_shm_ = shmat(shmid, nullptr, 0); if (managed_shm_ == reinterpret_cast<void*>(-1)) { AERROR << "attach shm failed, error: " << strerror(errno); return false; } // get field state_ state_ = reinterpret_cast<State*>(managed_shm_); if (state_ == nullptr) { AERROR << "get state failed."; shmdt(managed_shm_); managed_shm_ = nullptr; return false; } conf_.Update(state_->ceiling_msg_size()); // get field blocks_ blocks_ = reinterpret_cast<Block*>(static_cast<char*>(managed_shm_) + sizeof(State)); if (blocks_ == nullptr) { AERROR << "get blocks failed."; state_ = nullptr; shmdt(managed_shm_); managed_shm_ = nullptr; return false; } // get block buf uint32_t i = 0; for (; i < conf_.block_num(); ++i) { uint8_t* addr = reinterpret_cast<uint8_t*>( static_cast<char*>(managed_shm_) + sizeof(State) + conf_.block_num() * sizeof(Block) + i * conf_.block_buf_size()); if (addr == nullptr) { break; } std::lock_guard<std::mutex> _g(block_buf_lock_); block_buf_addrs_[i] = addr; } if (i != conf_.block_num()) { AERROR << "open only failed."; state_->~State(); state_ = nullptr; blocks_ = nullptr; { std::lock_guard<std::mutex> _g(block_buf_lock_); block_buf_addrs_.clear(); } shmdt(managed_shm_); managed_shm_ = nullptr; shmctl(shmid, IPC_RMID, 0); return false; } state_->IncreaseReferenceCounts(); init_ = true; ADEBUG << "open only true."; return true; } bool XsiSegment::Remove() { int shmid = shmget(key_, 0, 0644); if (shmid == -1 || shmctl(shmid, IPC_RMID, 0) == -1) { AERROR << "remove shm failed, error code: " << strerror(errno); return false; } ADEBUG << "remove success."; return true; } void XsiSegment::Reset() { state_ = nullptr; blocks_ = nullptr; { std::lock_guard<std::mutex> _g(block_buf_lock_); block_buf_addrs_.clear(); } if (managed_shm_ != nullptr) { shmdt(managed_shm_); managed_shm_ = nullptr; return; } } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/shm_conf.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_TRANSPORT_SHM_SHM_CONF_H_ #define CYBER_TRANSPORT_SHM_SHM_CONF_H_ #include <cstdint> #include <string> namespace apollo { namespace cyber { namespace transport { class ShmConf { public: ShmConf(); explicit ShmConf(const uint64_t& real_msg_size); virtual ~ShmConf(); void Update(const uint64_t& real_msg_size); const uint64_t& ceiling_msg_size() { return ceiling_msg_size_; } const uint64_t& block_buf_size() { return block_buf_size_; } const uint32_t& block_num() { return block_num_; } const uint64_t& managed_shm_size() { return managed_shm_size_; } private: uint64_t GetCeilingMessageSize(const uint64_t& real_msg_size); uint64_t GetBlockBufSize(const uint64_t& ceiling_msg_size); uint32_t GetBlockNum(const uint64_t& ceiling_msg_size); uint64_t ceiling_msg_size_; uint64_t block_buf_size_; uint32_t block_num_; uint64_t managed_shm_size_; // Extra size, Byte static const uint64_t EXTRA_SIZE; // State size, Byte static const uint64_t STATE_SIZE; // Block size, Byte static const uint64_t BLOCK_SIZE; // Message info size, Byte static const uint64_t MESSAGE_INFO_SIZE; // For message 0-10K static const uint32_t BLOCK_NUM_16K; static const uint64_t MESSAGE_SIZE_16K; // For message 10K-100K static const uint32_t BLOCK_NUM_128K; static const uint64_t MESSAGE_SIZE_128K; // For message 100K-1M static const uint32_t BLOCK_NUM_1M; static const uint64_t MESSAGE_SIZE_1M; // For message 1M-6M static const uint32_t BLOCK_NUM_8M; static const uint64_t MESSAGE_SIZE_8M; // For message 6M-10M static const uint32_t BLOCK_NUM_16M; static const uint64_t MESSAGE_SIZE_16M; // For message 10M+ static const uint32_t BLOCK_NUM_MORE; static const uint64_t MESSAGE_SIZE_MORE; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_SHM_SHM_CONF_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/notifier_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_TRANSPORT_SHM_NOTIFIER_BASE_H_ #define CYBER_TRANSPORT_SHM_NOTIFIER_BASE_H_ #include <memory> #include "cyber/transport/shm/readable_info.h" namespace apollo { namespace cyber { namespace transport { class NotifierBase; using NotifierPtr = NotifierBase*; class NotifierBase { public: virtual ~NotifierBase() = default; virtual void Shutdown() = 0; virtual bool Notify(const ReadableInfo& info) = 0; virtual bool Listen(int timeout_ms, ReadableInfo* info) = 0; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_SHM_NOTIFIER_BASE_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/condition_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_TRANSPORT_SHM_CONDITION_NOTIFIER_H_ #define CYBER_TRANSPORT_SHM_CONDITION_NOTIFIER_H_ #include <sys/types.h> #include <atomic> #include <cstdint> #include "cyber/common/macros.h" #include "cyber/transport/shm/notifier_base.h" namespace apollo { namespace cyber { namespace transport { const uint32_t kBufLength = 4096; class ConditionNotifier : public NotifierBase { struct Indicator { std::atomic<uint64_t> next_seq = {0}; ReadableInfo infos[kBufLength]; uint64_t seqs[kBufLength] = {0}; }; public: virtual ~ConditionNotifier(); void Shutdown() override; bool Notify(const ReadableInfo& info) override; bool Listen(int timeout_ms, ReadableInfo* info) override; static const char* Type() { return "condition"; } private: bool Init(); bool OpenOrCreate(); bool OpenOnly(); bool Remove(); void Reset(); key_t key_ = 0; void* managed_shm_ = nullptr; size_t shm_size_ = 0; Indicator* indicator_ = nullptr; uint64_t next_seq_ = 0; std::atomic<bool> is_shutdown_ = {false}; DECLARE_SINGLETON(ConditionNotifier) }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_SHM_CONDITION_NOTIFIER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/posix_segment.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/transport/shm/posix_segment.h" #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include "cyber/common/log.h" #include "cyber/common/util.h" #include "cyber/transport/shm/block.h" #include "cyber/transport/shm/segment.h" #include "cyber/transport/shm/shm_conf.h" namespace apollo { namespace cyber { namespace transport { PosixSegment::PosixSegment(uint64_t channel_id) : Segment(channel_id) { shm_name_ = std::to_string(channel_id); } PosixSegment::~PosixSegment() { Destroy(); } bool PosixSegment::OpenOrCreate() { if (init_) { return true; } // create managed_shm_ int fd = shm_open(shm_name_.c_str(), O_RDWR | O_CREAT | O_EXCL, 0644); if (fd < 0) { if (EEXIST == errno) { ADEBUG << "shm already exist, open only."; return OpenOnly(); } else { AERROR << "create shm failed, error: " << strerror(errno); return false; } } if (ftruncate(fd, conf_.managed_shm_size()) < 0) { AERROR << "ftruncate failed: " << strerror(errno); close(fd); return false; } // attach managed_shm_ managed_shm_ = mmap(nullptr, conf_.managed_shm_size(), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (managed_shm_ == MAP_FAILED) { AERROR << "attach shm failed:" << strerror(errno); close(fd); shm_unlink(shm_name_.c_str()); return false; } close(fd); // create field state_ state_ = new (managed_shm_) State(conf_.ceiling_msg_size()); if (state_ == nullptr) { AERROR << "create state failed."; munmap(managed_shm_, conf_.managed_shm_size()); managed_shm_ = nullptr; shm_unlink(shm_name_.c_str()); return false; } conf_.Update(state_->ceiling_msg_size()); // create field blocks_ blocks_ = new (static_cast<char*>(managed_shm_) + sizeof(State)) Block[conf_.block_num()]; if (blocks_ == nullptr) { AERROR << "create blocks failed."; state_->~State(); state_ = nullptr; munmap(managed_shm_, conf_.managed_shm_size()); managed_shm_ = nullptr; shm_unlink(shm_name_.c_str()); return false; } // create block buf uint32_t i = 0; for (; i < conf_.block_num(); ++i) { uint8_t* addr = new (static_cast<char*>(managed_shm_) + sizeof(State) + conf_.block_num() * sizeof(Block) + i * conf_.block_buf_size()) uint8_t[conf_.block_buf_size()]; if (addr == nullptr) { break; } std::lock_guard<std::mutex> lg(block_buf_lock_); block_buf_addrs_[i] = addr; } if (i != conf_.block_num()) { AERROR << "create block buf failed."; state_->~State(); state_ = nullptr; blocks_ = nullptr; { std::lock_guard<std::mutex> lg(block_buf_lock_); block_buf_addrs_.clear(); } munmap(managed_shm_, conf_.managed_shm_size()); managed_shm_ = nullptr; shm_unlink(shm_name_.c_str()); return false; } state_->IncreaseReferenceCounts(); init_ = true; return true; } bool PosixSegment::OpenOnly() { if (init_) { return true; } // get managed_shm_ int fd = shm_open(shm_name_.c_str(), O_RDWR, 0644); if (fd == -1) { AERROR << "get shm failed: " << strerror(errno); return false; } struct stat file_attr; if (fstat(fd, &file_attr) < 0) { AERROR << "fstat failed: " << strerror(errno); close(fd); return false; } // attach managed_shm_ managed_shm_ = mmap(nullptr, file_attr.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (managed_shm_ == MAP_FAILED) { AERROR << "attach shm failed: " << strerror(errno); close(fd); return false; } close(fd); // get field state_ state_ = reinterpret_cast<State*>(managed_shm_); if (state_ == nullptr) { AERROR << "get state failed."; munmap(managed_shm_, file_attr.st_size); managed_shm_ = nullptr; return false; } conf_.Update(state_->ceiling_msg_size()); // get field blocks_ blocks_ = reinterpret_cast<Block*>(static_cast<char*>(managed_shm_) + sizeof(State)); if (blocks_ == nullptr) { AERROR << "get blocks failed."; state_ = nullptr; munmap(managed_shm_, conf_.managed_shm_size()); managed_shm_ = nullptr; return false; } // get block buf uint32_t i = 0; for (; i < conf_.block_num(); ++i) { uint8_t* addr = reinterpret_cast<uint8_t*>( static_cast<char*>(managed_shm_) + sizeof(State) + conf_.block_num() * sizeof(Block) + i * conf_.block_buf_size()); std::lock_guard<std::mutex> lg(block_buf_lock_); block_buf_addrs_[i] = addr; } if (i != conf_.block_num()) { AERROR << "open only failed."; state_->~State(); state_ = nullptr; blocks_ = nullptr; { std::lock_guard<std::mutex> lg(block_buf_lock_); block_buf_addrs_.clear(); } munmap(managed_shm_, conf_.managed_shm_size()); managed_shm_ = nullptr; shm_unlink(shm_name_.c_str()); return false; } state_->IncreaseReferenceCounts(); init_ = true; ADEBUG << "open only true."; return true; } bool PosixSegment::Remove() { if (shm_unlink(shm_name_.c_str()) < 0) { AERROR << "shm_unlink failed: " << strerror(errno); return false; } return true; } void PosixSegment::Reset() { state_ = nullptr; blocks_ = nullptr; { std::lock_guard<std::mutex> lg(block_buf_lock_); block_buf_addrs_.clear(); } if (managed_shm_ != nullptr) { munmap(managed_shm_, conf_.managed_shm_size()); managed_shm_ = nullptr; return; } } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/condition_notifier.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/transport/shm/condition_notifier.h" #include <sys/ipc.h> #include <sys/shm.h> #include <thread> #include "cyber/common/log.h" #include "cyber/common/util.h" namespace apollo { namespace cyber { namespace transport { using common::Hash; ConditionNotifier::ConditionNotifier() { key_ = static_cast<key_t>(Hash("/apollo/cyber/transport/shm/notifier")); ADEBUG << "condition notifier key: " << key_; shm_size_ = sizeof(Indicator); if (!Init()) { AERROR << "fail to init condition notifier."; is_shutdown_.store(true); return; } next_seq_ = indicator_->next_seq.load(); ADEBUG << "next_seq: " << next_seq_; } ConditionNotifier::~ConditionNotifier() { Shutdown(); } void ConditionNotifier::Shutdown() { if (is_shutdown_.exchange(true)) { return; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); Reset(); } bool ConditionNotifier::Notify(const ReadableInfo& info) { if (is_shutdown_.load()) { ADEBUG << "notifier is shutdown."; return false; } uint64_t seq = indicator_->next_seq.fetch_add(1); uint64_t idx = seq % kBufLength; indicator_->infos[idx] = info; indicator_->seqs[idx] = seq; return true; } bool ConditionNotifier::Listen(int timeout_ms, ReadableInfo* info) { if (info == nullptr) { AERROR << "info nullptr."; return false; } if (is_shutdown_.load()) { ADEBUG << "notifier is shutdown."; return false; } int timeout_us = timeout_ms * 1000; while (!is_shutdown_.load()) { uint64_t seq = indicator_->next_seq.load(); if (seq != next_seq_) { auto idx = next_seq_ % kBufLength; auto actual_seq = indicator_->seqs[idx]; if (actual_seq >= next_seq_) { next_seq_ = actual_seq; *info = indicator_->infos[idx]; ++next_seq_; return true; } else { ADEBUG << "seq[" << next_seq_ << "] is writing, can not read now."; } } if (timeout_us > 0) { std::this_thread::sleep_for(std::chrono::microseconds(50)); timeout_us -= 50; } else { return false; } } return false; } bool ConditionNotifier::Init() { return OpenOrCreate(); } bool ConditionNotifier::OpenOrCreate() { // create managed_shm_ int retry = 0; int shmid = 0; while (retry < 2) { shmid = shmget(key_, shm_size_, 0644 | IPC_CREAT | IPC_EXCL); if (shmid != -1) { break; } if (EINVAL == errno) { AINFO << "need larger space, recreate."; Reset(); Remove(); ++retry; } else if (EEXIST == errno) { ADEBUG << "shm already exist, open only."; return OpenOnly(); } else { break; } } if (shmid == -1) { AERROR << "create shm failed, error code: " << strerror(errno); return false; } // attach managed_shm_ managed_shm_ = shmat(shmid, nullptr, 0); if (managed_shm_ == reinterpret_cast<void*>(-1)) { AERROR << "attach shm failed."; shmctl(shmid, IPC_RMID, 0); return false; } // create indicator_ indicator_ = new (managed_shm_) Indicator(); if (indicator_ == nullptr) { AERROR << "create indicator failed."; shmdt(managed_shm_); managed_shm_ = nullptr; shmctl(shmid, IPC_RMID, 0); return false; } ADEBUG << "open or create true."; return true; } bool ConditionNotifier::OpenOnly() { // get managed_shm_ int shmid = shmget(key_, 0, 0644); if (shmid == -1) { AERROR << "get shm failed, error: " << strerror(errno); return false; } // attach managed_shm_ managed_shm_ = shmat(shmid, nullptr, 0); if (managed_shm_ == reinterpret_cast<void*>(-1)) { AERROR << "attach shm failed, error: " << strerror(errno); return false; } // get indicator_ indicator_ = reinterpret_cast<Indicator*>(managed_shm_); if (indicator_ == nullptr) { AERROR << "get indicator failed."; shmdt(managed_shm_); managed_shm_ = nullptr; return false; } ADEBUG << "open true."; return true; } bool ConditionNotifier::Remove() { int shmid = shmget(key_, 0, 0644); if (shmid == -1 || shmctl(shmid, IPC_RMID, 0) == -1) { AERROR << "remove shm failed, error code: " << strerror(errno); return false; } ADEBUG << "remove success."; return true; } void ConditionNotifier::Reset() { indicator_ = nullptr; if (managed_shm_ != nullptr) { shmdt(managed_shm_); managed_shm_ = nullptr; } } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/notifier_factory.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_TRANSPORT_SHM_NOTIFIER_FACTORY_H_ #define CYBER_TRANSPORT_SHM_NOTIFIER_FACTORY_H_ #include <memory> #include "cyber/transport/shm/notifier_base.h" namespace apollo { namespace cyber { namespace transport { class NotifierFactory { public: static NotifierPtr CreateNotifier(); private: static NotifierPtr CreateConditionNotifier(); static NotifierPtr CreateMulticastNotifier(); }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_SHM_NOTIFIER_FACTORY_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/multicast_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_TRANSPORT_SHM_MULTICAST_NOTIFIER_H_ #define CYBER_TRANSPORT_SHM_MULTICAST_NOTIFIER_H_ #include <netinet/in.h> #include <atomic> #include "cyber/common/macros.h" #include "cyber/transport/shm/notifier_base.h" namespace apollo { namespace cyber { namespace transport { class MulticastNotifier : public NotifierBase { public: virtual ~MulticastNotifier(); void Shutdown() override; bool Notify(const ReadableInfo& info) override; bool Listen(int timeout_ms, ReadableInfo* info) override; static const char* Type() { return "multicast"; } private: bool Init(); int notify_fd_ = -1; struct sockaddr_in notify_addr_; int listen_fd_ = -1; struct sockaddr_in listen_addr_; std::atomic<bool> is_shutdown_ = {false}; DECLARE_SINGLETON(MulticastNotifier) }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_SHM_MULTICAST_NOTIFIER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/block.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_TRANSPORT_SHM_BLOCK_H_ #define CYBER_TRANSPORT_SHM_BLOCK_H_ #include <atomic> #include <cstdint> namespace apollo { namespace cyber { namespace transport { class Block { friend class Segment; public: Block(); virtual ~Block(); uint64_t msg_size() const { return msg_size_; } void set_msg_size(uint64_t msg_size) { msg_size_ = msg_size; } uint64_t msg_info_size() const { return msg_info_size_; } void set_msg_info_size(uint64_t msg_info_size) { msg_info_size_ = msg_info_size; } static const int32_t kRWLockFree; static const int32_t kWriteExclusive; static const int32_t kMaxTryLockTimes; private: bool TryLockForWrite(); bool TryLockForRead(); void ReleaseWriteLock(); void ReleaseReadLock(); std::atomic<int32_t> lock_num_ = {0}; uint64_t msg_size_; uint64_t msg_info_size_; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_SHM_BLOCK_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/readable_info.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_TRANSPORT_SHM_READABLE_INFO_H_ #define CYBER_TRANSPORT_SHM_READABLE_INFO_H_ #include <cstddef> #include <cstdint> #include <memory> #include <string> namespace apollo { namespace cyber { namespace transport { class ReadableInfo; using ReadableInfoPtr = std::shared_ptr<ReadableInfo>; class ReadableInfo { public: ReadableInfo(); ReadableInfo(uint64_t host_id, uint32_t block_index, uint64_t channel_id); virtual ~ReadableInfo(); ReadableInfo& operator=(const ReadableInfo& other); bool DeserializeFrom(const std::string& src); bool DeserializeFrom(const char* src, std::size_t len); bool SerializeTo(std::string* dst) const; uint64_t host_id() const { return host_id_; } void set_host_id(uint64_t host_id) { host_id_ = host_id; } uint32_t block_index() const { return block_index_; } void set_block_index(uint32_t block_index) { block_index_ = block_index; } uint64_t channel_id() const { return channel_id_; } void set_channel_id(uint64_t channel_id) { channel_id_ = channel_id; } static const size_t kSize; private: uint64_t host_id_; uint32_t block_index_; uint64_t channel_id_; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_SHM_READABLE_INFO_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_transport_shm_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "block", srcs = ["block.cc"], hdrs = ["block.h"], deps = [ "//cyber/base:atomic_rw_lock", "//cyber/common:log", ], ) cc_library( name = "condition_notifier", srcs = ["condition_notifier.cc"], hdrs = ["condition_notifier.h"], deps = [ ":notifier_base", "//cyber/common:global_data", "//cyber/common:log", "//cyber/common:util", ], ) cc_library( name = "multicast_notifier", srcs = ["multicast_notifier.cc"], hdrs = ["multicast_notifier.h"], deps = [ ":notifier_base", "//cyber/common:global_data", "//cyber/common:log", "//cyber/common:macros", ], ) cc_library( name = "notifier_base", hdrs = ["notifier_base.h"], deps = [ ":readable_info", ], ) cc_library( name = "notifier_factory", srcs = ["notifier_factory.cc"], hdrs = ["notifier_factory.h"], deps = [ ":condition_notifier", ":multicast_notifier", ":notifier_base", "//cyber/common:global_data", "//cyber/common:log", ], ) cc_library( name = "readable_info", srcs = ["readable_info.cc"], hdrs = ["readable_info.h"], deps = [ "//cyber/common:log", ], ) cc_library( name = "xsi_segment", srcs = ["xsi_segment.cc"], hdrs = ["xsi_segment.h"], deps = [ ":segment", "//cyber/common:log", "//cyber/common:util", ], ) cc_library( name = "posix_segment", srcs = ["posix_segment.cc"], hdrs = ["posix_segment.h"], deps = [ ":segment", "//cyber/common:log", "//cyber/common:util", ], ) cc_library( name = "segment", srcs = ["segment.cc"], hdrs = ["segment.h"], deps = [ ":block", ":shm_conf", ":state", "//cyber/common:log", "//cyber/common:util", ], ) cc_library( name = "segment_factory", srcs = ["segment_factory.cc"], hdrs = ["segment_factory.h"], deps = [ ":posix_segment", ":segment", ":xsi_segment", "//cyber/common:global_data", "//cyber/common:log", ], ) cc_library( name = "shm_conf", srcs = ["shm_conf.cc"], hdrs = ["shm_conf.h"], deps = [ "//cyber/common:log", ], ) cc_library( name = "state", srcs = ["state.cc"], hdrs = ["state.h"], ) cc_test( name = "condition_notifier_test", size = "small", srcs = ["condition_notifier_test.cc"], tags = ["exclusive"], deps = [ "//cyber:cyber_core", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cpplint()
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/posix_segment.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_TRANSPORT_SHM_POSIX_SEGMENT_H_ #define CYBER_TRANSPORT_SHM_POSIX_SEGMENT_H_ #include <string> #include "cyber/transport/shm/segment.h" namespace apollo { namespace cyber { namespace transport { class PosixSegment : public Segment { public: explicit PosixSegment(uint64_t channel_id); virtual ~PosixSegment(); static const char* Type() { return "posix"; } private: void Reset() override; bool Remove() override; bool OpenOnly() override; bool OpenOrCreate() override; std::string shm_name_; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_SHM_POSIX_SEGMENT_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/shm_conf.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/transport/shm/shm_conf.h" #include "cyber/common/log.h" namespace apollo { namespace cyber { namespace transport { ShmConf::ShmConf() { Update(MESSAGE_SIZE_16K); } ShmConf::ShmConf(const uint64_t& real_msg_size) { Update(real_msg_size); } ShmConf::~ShmConf() {} void ShmConf::Update(const uint64_t& real_msg_size) { ceiling_msg_size_ = GetCeilingMessageSize(real_msg_size); block_buf_size_ = GetBlockBufSize(ceiling_msg_size_); block_num_ = GetBlockNum(ceiling_msg_size_); managed_shm_size_ = EXTRA_SIZE + STATE_SIZE + (BLOCK_SIZE + block_buf_size_) * block_num_; } const uint64_t ShmConf::EXTRA_SIZE = 1024 * 4; const uint64_t ShmConf::STATE_SIZE = 1024; const uint64_t ShmConf::BLOCK_SIZE = 1024; const uint64_t ShmConf::MESSAGE_INFO_SIZE = 1024; const uint32_t ShmConf::BLOCK_NUM_16K = 512; const uint64_t ShmConf::MESSAGE_SIZE_16K = 1024 * 16; const uint32_t ShmConf::BLOCK_NUM_128K = 128; const uint64_t ShmConf::MESSAGE_SIZE_128K = 1024 * 128; const uint32_t ShmConf::BLOCK_NUM_1M = 64; const uint64_t ShmConf::MESSAGE_SIZE_1M = 1024 * 1024; const uint32_t ShmConf::BLOCK_NUM_8M = 32; const uint64_t ShmConf::MESSAGE_SIZE_8M = 1024 * 1024 * 8; const uint32_t ShmConf::BLOCK_NUM_16M = 16; const uint64_t ShmConf::MESSAGE_SIZE_16M = 1024 * 1024 * 16; const uint32_t ShmConf::BLOCK_NUM_MORE = 8; const uint64_t ShmConf::MESSAGE_SIZE_MORE = 1024 * 1024 * 32; uint64_t ShmConf::GetCeilingMessageSize(const uint64_t& real_msg_size) { uint64_t ceiling_msg_size = MESSAGE_SIZE_16K; if (real_msg_size <= MESSAGE_SIZE_16K) { ceiling_msg_size = MESSAGE_SIZE_16K; } else if (real_msg_size <= MESSAGE_SIZE_128K) { ceiling_msg_size = MESSAGE_SIZE_128K; } else if (real_msg_size <= MESSAGE_SIZE_1M) { ceiling_msg_size = MESSAGE_SIZE_1M; } else if (real_msg_size <= MESSAGE_SIZE_8M) { ceiling_msg_size = MESSAGE_SIZE_8M; } else if (real_msg_size <= MESSAGE_SIZE_16M) { ceiling_msg_size = MESSAGE_SIZE_16M; } else { ceiling_msg_size = MESSAGE_SIZE_MORE; } return ceiling_msg_size; } uint64_t ShmConf::GetBlockBufSize(const uint64_t& ceiling_msg_size) { return ceiling_msg_size + MESSAGE_INFO_SIZE; } uint32_t ShmConf::GetBlockNum(const uint64_t& ceiling_msg_size) { uint32_t num = 0; switch (ceiling_msg_size) { case MESSAGE_SIZE_16K: num = BLOCK_NUM_16K; break; case MESSAGE_SIZE_128K: num = BLOCK_NUM_128K; break; case MESSAGE_SIZE_1M: num = BLOCK_NUM_1M; break; case MESSAGE_SIZE_8M: num = BLOCK_NUM_8M; break; case MESSAGE_SIZE_16M: num = BLOCK_NUM_16M; break; case MESSAGE_SIZE_MORE: num = BLOCK_NUM_MORE; break; default: AERROR << "unknown ceiling_msg_size[" << ceiling_msg_size << "]"; break; } return num; } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/state.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_TRANSPORT_SHM_STATE_H_ #define CYBER_TRANSPORT_SHM_STATE_H_ #include <atomic> #include <cstdint> #include <mutex> #include <string> namespace apollo { namespace cyber { namespace transport { class State { public: explicit State(const uint64_t& ceiling_msg_size); virtual ~State(); void DecreaseReferenceCounts() { uint32_t current_reference_count = reference_count_.load(); do { if (current_reference_count == 0) { return; } } while (!reference_count_.compare_exchange_strong( current_reference_count, current_reference_count - 1)); } void IncreaseReferenceCounts() { reference_count_.fetch_add(1); } uint32_t FetchAddSeq(uint32_t diff) { return seq_.fetch_add(diff); } uint32_t seq() { return seq_.load(); } void set_need_remap(bool need) { need_remap_.store(need); } bool need_remap() { return need_remap_; } uint64_t ceiling_msg_size() { return ceiling_msg_size_.load(); } uint32_t reference_counts() { return reference_count_.load(); } private: std::atomic<bool> need_remap_ = {false}; std::atomic<uint32_t> seq_ = {0}; std::atomic<uint32_t> reference_count_ = {0}; std::atomic<uint64_t> ceiling_msg_size_; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_SHM_STATE_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/shm/notifier_factory.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/transport/shm/notifier_factory.h" #include <string> #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/transport/shm/condition_notifier.h" #include "cyber/transport/shm/multicast_notifier.h" namespace apollo { namespace cyber { namespace transport { using common::GlobalData; auto NotifierFactory::CreateNotifier() -> NotifierPtr { std::string notifier_type(ConditionNotifier::Type()); auto& g_conf = GlobalData::Instance()->Config(); if (g_conf.has_transport_conf() && g_conf.transport_conf().has_shm_conf() && g_conf.transport_conf().shm_conf().has_notifier_type()) { notifier_type = g_conf.transport_conf().shm_conf().notifier_type(); } ADEBUG << "notifier type: " << notifier_type; if (notifier_type == MulticastNotifier::Type()) { return CreateMulticastNotifier(); } else if (notifier_type == ConditionNotifier::Type()) { return CreateConditionNotifier(); } AINFO << "unknown notifier, we use default notifier: " << notifier_type; return CreateConditionNotifier(); } auto NotifierFactory::CreateConditionNotifier() -> NotifierPtr { return ConditionNotifier::Instance(); } auto NotifierFactory::CreateMulticastNotifier() -> NotifierPtr { return MulticastNotifier::Instance(); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/transmitter/rtps_transmitter.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_TRANSPORT_TRANSMITTER_RTPS_TRANSMITTER_H_ #define CYBER_TRANSPORT_TRANSMITTER_RTPS_TRANSMITTER_H_ #include <memory> #include <string> #include "cyber/common/log.h" #include "cyber/message/message_traits.h" #include "cyber/transport/rtps/attributes_filler.h" #include "cyber/transport/rtps/participant.h" #include "cyber/transport/transmitter/transmitter.h" #include "fastrtps/Domain.h" #include "fastrtps/attributes/PublisherAttributes.h" #include "fastrtps/participant/Participant.h" #include "fastrtps/publisher/Publisher.h" namespace apollo { namespace cyber { namespace transport { template <typename M> class RtpsTransmitter : public Transmitter<M> { public: using MessagePtr = std::shared_ptr<M>; RtpsTransmitter(const RoleAttributes& attr, const ParticipantPtr& participant); virtual ~RtpsTransmitter(); void Enable() override; void Disable() override; bool Transmit(const MessagePtr& msg, const MessageInfo& msg_info) override; private: bool Transmit(const M& msg, const MessageInfo& msg_info); ParticipantPtr participant_; eprosima::fastrtps::Publisher* publisher_; }; template <typename M> RtpsTransmitter<M>::RtpsTransmitter(const RoleAttributes& attr, const ParticipantPtr& participant) : Transmitter<M>(attr), participant_(participant), publisher_(nullptr) {} template <typename M> RtpsTransmitter<M>::~RtpsTransmitter() { Disable(); } template <typename M> void RtpsTransmitter<M>::Enable() { if (this->enabled_) { return; } RETURN_IF_NULL(participant_); eprosima::fastrtps::PublisherAttributes pub_attr; RETURN_IF(!AttributesFiller::FillInPubAttr( this->attr_.channel_name(), this->attr_.qos_profile(), &pub_attr)); publisher_ = eprosima::fastrtps::Domain::createPublisher( participant_->fastrtps_participant(), pub_attr); RETURN_IF_NULL(publisher_); this->enabled_ = true; } template <typename M> void RtpsTransmitter<M>::Disable() { if (this->enabled_) { publisher_ = nullptr; this->enabled_ = false; } } template <typename M> bool RtpsTransmitter<M>::Transmit(const MessagePtr& msg, const MessageInfo& msg_info) { return Transmit(*msg, msg_info); } template <typename M> bool RtpsTransmitter<M>::Transmit(const M& msg, const MessageInfo& msg_info) { if (!this->enabled_) { ADEBUG << "not enable."; return false; } UnderlayMessage m; RETURN_VAL_IF(!message::SerializeToString(msg, &m.data()), false); eprosima::fastrtps::rtps::WriteParams wparams; char* ptr = reinterpret_cast<char*>(&wparams.related_sample_identity().writer_guid()); memcpy(ptr, msg_info.sender_id().data(), ID_SIZE); memcpy(ptr + ID_SIZE, msg_info.spare_id().data(), ID_SIZE); wparams.related_sample_identity().sequence_number().high = (int32_t)((msg_info.seq_num() & 0xFFFFFFFF00000000) >> 32); wparams.related_sample_identity().sequence_number().low = (int32_t)(msg_info.seq_num() & 0xFFFFFFFF); if (participant_->is_shutdown()) { return false; } return publisher_->write(reinterpret_cast<void*>(&m), wparams); } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_TRANSMITTER_RTPS_TRANSMITTER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/transmitter/shm_transmitter.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_TRANSPORT_TRANSMITTER_SHM_TRANSMITTER_H_ #define CYBER_TRANSPORT_TRANSMITTER_SHM_TRANSMITTER_H_ #include <cstring> #include <iostream> #include <memory> #include <string> #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/common/util.h" #include "cyber/message/message_traits.h" #include "cyber/transport/shm/notifier_factory.h" #include "cyber/transport/shm/readable_info.h" #include "cyber/transport/shm/segment_factory.h" #include "cyber/transport/transmitter/transmitter.h" namespace apollo { namespace cyber { namespace transport { template <typename M> class ShmTransmitter : public Transmitter<M> { public: using MessagePtr = std::shared_ptr<M>; explicit ShmTransmitter(const RoleAttributes& attr); virtual ~ShmTransmitter(); void Enable() override; void Disable() override; bool Transmit(const MessagePtr& msg, const MessageInfo& msg_info) override; private: bool Transmit(const M& msg, const MessageInfo& msg_info); SegmentPtr segment_; uint64_t channel_id_; uint64_t host_id_; NotifierPtr notifier_; }; template <typename M> ShmTransmitter<M>::ShmTransmitter(const RoleAttributes& attr) : Transmitter<M>(attr), segment_(nullptr), channel_id_(attr.channel_id()), notifier_(nullptr) { host_id_ = common::Hash(attr.host_ip()); } template <typename M> ShmTransmitter<M>::~ShmTransmitter() { Disable(); } template <typename M> void ShmTransmitter<M>::Enable() { if (this->enabled_) { return; } segment_ = SegmentFactory::CreateSegment(channel_id_); notifier_ = NotifierFactory::CreateNotifier(); this->enabled_ = true; } template <typename M> void ShmTransmitter<M>::Disable() { if (this->enabled_) { segment_ = nullptr; notifier_ = nullptr; this->enabled_ = false; } } template <typename M> bool ShmTransmitter<M>::Transmit(const MessagePtr& msg, const MessageInfo& msg_info) { return Transmit(*msg, msg_info); } template <typename M> bool ShmTransmitter<M>::Transmit(const M& msg, const MessageInfo& msg_info) { if (!this->enabled_) { ADEBUG << "not enable."; return false; } WritableBlock wb; std::size_t msg_size = message::ByteSize(msg); if (!segment_->AcquireBlockToWrite(msg_size, &wb)) { AERROR << "acquire block failed."; return false; } ADEBUG << "block index: " << wb.index; if (!message::SerializeToArray(msg, wb.buf, static_cast<int>(msg_size))) { AERROR << "serialize to array failed."; segment_->ReleaseWrittenBlock(wb); return false; } wb.block->set_msg_size(msg_size); char* msg_info_addr = reinterpret_cast<char*>(wb.buf) + msg_size; if (!msg_info.SerializeTo(msg_info_addr, MessageInfo::kSize)) { AERROR << "serialize message info failed."; segment_->ReleaseWrittenBlock(wb); return false; } wb.block->set_msg_info_size(MessageInfo::kSize); segment_->ReleaseWrittenBlock(wb); ReadableInfo readable_info(host_id_, wb.index, channel_id_); ADEBUG << "Writing sharedmem message: " << common::GlobalData::GetChannelById(channel_id_) << " to block: " << wb.index; return notifier_->Notify(readable_info); } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_TRANSMITTER_SHM_TRANSMITTER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/transmitter/hybrid_transmitter.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_TRANSPORT_TRANSMITTER_HYBRID_TRANSMITTER_H_ #define CYBER_TRANSPORT_TRANSMITTER_HYBRID_TRANSMITTER_H_ #include <chrono> #include <map> #include <memory> #include <set> #include <string> #include <unordered_map> #include <vector> #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/common/types.h" #include "cyber/proto/role_attributes.pb.h" #include "cyber/proto/transport_conf.pb.h" #include "cyber/task/task.h" #include "cyber/transport/message/history.h" #include "cyber/transport/rtps/participant.h" #include "cyber/transport/transmitter/intra_transmitter.h" #include "cyber/transport/transmitter/rtps_transmitter.h" #include "cyber/transport/transmitter/shm_transmitter.h" #include "cyber/transport/transmitter/transmitter.h" namespace apollo { namespace cyber { namespace transport { using apollo::cyber::proto::OptionalMode; using apollo::cyber::proto::QosDurabilityPolicy; using apollo::cyber::proto::RoleAttributes; template <typename M> class HybridTransmitter : public Transmitter<M> { public: using MessagePtr = std::shared_ptr<M>; using HistoryPtr = std::shared_ptr<History<M>>; using TransmitterPtr = std::shared_ptr<Transmitter<M>>; using TransmitterMap = std::unordered_map<OptionalMode, TransmitterPtr, std::hash<int>>; using ReceiverMap = std::unordered_map<OptionalMode, std::set<uint64_t>, std::hash<int>>; using CommunicationModePtr = std::shared_ptr<proto::CommunicationMode>; using MappingTable = std::unordered_map<Relation, OptionalMode, std::hash<int>>; HybridTransmitter(const RoleAttributes& attr, const ParticipantPtr& participant); virtual ~HybridTransmitter(); void Enable() override; void Disable() override; void Enable(const RoleAttributes& opposite_attr) override; void Disable(const RoleAttributes& opposite_attr) override; bool Transmit(const MessagePtr& msg, const MessageInfo& msg_info) override; private: void InitMode(); void ObtainConfig(); void InitHistory(); void InitTransmitters(); void ClearTransmitters(); void InitReceivers(); void ClearReceivers(); void TransmitHistoryMsg(const RoleAttributes& opposite_attr); void ThreadFunc(const RoleAttributes& opposite_attr, const std::vector<typename History<M>::CachedMessage>& msgs); Relation GetRelation(const RoleAttributes& opposite_attr); HistoryPtr history_; TransmitterMap transmitters_; ReceiverMap receivers_; std::mutex mutex_; CommunicationModePtr mode_; MappingTable mapping_table_; ParticipantPtr participant_; }; template <typename M> HybridTransmitter<M>::HybridTransmitter(const RoleAttributes& attr, const ParticipantPtr& participant) : Transmitter<M>(attr), history_(nullptr), mode_(nullptr), participant_(participant) { InitMode(); ObtainConfig(); InitHistory(); InitTransmitters(); InitReceivers(); } template <typename M> HybridTransmitter<M>::~HybridTransmitter() { ClearReceivers(); ClearTransmitters(); } template <typename M> void HybridTransmitter<M>::Enable() { std::lock_guard<std::mutex> lock(mutex_); for (auto& item : transmitters_) { item.second->Enable(); } } template <typename M> void HybridTransmitter<M>::Disable() { std::lock_guard<std::mutex> lock(mutex_); for (auto& item : transmitters_) { item.second->Disable(); } } template <typename M> void HybridTransmitter<M>::Enable(const RoleAttributes& opposite_attr) { auto relation = GetRelation(opposite_attr); if (relation == NO_RELATION) { return; } uint64_t id = opposite_attr.id(); std::lock_guard<std::mutex> lock(mutex_); receivers_[mapping_table_[relation]].insert(id); transmitters_[mapping_table_[relation]]->Enable(); TransmitHistoryMsg(opposite_attr); } template <typename M> void HybridTransmitter<M>::Disable(const RoleAttributes& opposite_attr) { auto relation = GetRelation(opposite_attr); if (relation == NO_RELATION) { return; } uint64_t id = opposite_attr.id(); std::lock_guard<std::mutex> lock(mutex_); receivers_[mapping_table_[relation]].erase(id); if (receivers_[mapping_table_[relation]].empty()) { transmitters_[mapping_table_[relation]]->Disable(); } } template <typename M> bool HybridTransmitter<M>::Transmit(const MessagePtr& msg, const MessageInfo& msg_info) { std::lock_guard<std::mutex> lock(mutex_); history_->Add(msg, msg_info); for (auto& item : transmitters_) { item.second->Transmit(msg, msg_info); } return true; } template <typename M> void HybridTransmitter<M>::InitMode() { mode_ = std::make_shared<proto::CommunicationMode>(); mapping_table_[SAME_PROC] = mode_->same_proc(); mapping_table_[DIFF_PROC] = mode_->diff_proc(); mapping_table_[DIFF_HOST] = mode_->diff_host(); } template <typename M> void HybridTransmitter<M>::ObtainConfig() { auto& global_conf = common::GlobalData::Instance()->Config(); if (!global_conf.has_transport_conf()) { return; } if (!global_conf.transport_conf().has_communication_mode()) { return; } mode_->CopyFrom(global_conf.transport_conf().communication_mode()); mapping_table_[SAME_PROC] = mode_->same_proc(); mapping_table_[DIFF_PROC] = mode_->diff_proc(); mapping_table_[DIFF_HOST] = mode_->diff_host(); } template <typename M> void HybridTransmitter<M>::InitHistory() { HistoryAttributes history_attr(this->attr_.qos_profile().history(), this->attr_.qos_profile().depth()); history_ = std::make_shared<History<M>>(history_attr); if (this->attr_.qos_profile().durability() == QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL) { history_->Enable(); } } template <typename M> void HybridTransmitter<M>::InitTransmitters() { std::set<OptionalMode> modes; modes.insert(mode_->same_proc()); modes.insert(mode_->diff_proc()); modes.insert(mode_->diff_host()); for (auto& mode : modes) { switch (mode) { case OptionalMode::INTRA: transmitters_[mode] = std::make_shared<IntraTransmitter<M>>(this->attr_); break; case OptionalMode::SHM: transmitters_[mode] = std::make_shared<ShmTransmitter<M>>(this->attr_); break; default: transmitters_[mode] = std::make_shared<RtpsTransmitter<M>>(this->attr_, participant_); break; } } } template <typename M> void HybridTransmitter<M>::ClearTransmitters() { for (auto& item : transmitters_) { item.second->Disable(); } transmitters_.clear(); } template <typename M> void HybridTransmitter<M>::InitReceivers() { std::set<uint64_t> empty; for (auto& item : transmitters_) { receivers_[item.first] = empty; } } template <typename M> void HybridTransmitter<M>::ClearReceivers() { receivers_.clear(); } template <typename M> void HybridTransmitter<M>::TransmitHistoryMsg( const RoleAttributes& opposite_attr) { // check qos if (this->attr_.qos_profile().durability() != QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL) { return; } // get unsent messages std::vector<typename History<M>::CachedMessage> unsent_msgs; history_->GetCachedMessage(&unsent_msgs); if (unsent_msgs.empty()) { return; } auto attr = opposite_attr; cyber::Async(&HybridTransmitter<M>::ThreadFunc, this, attr, unsent_msgs); } template <typename M> void HybridTransmitter<M>::ThreadFunc( const RoleAttributes& opposite_attr, const std::vector<typename History<M>::CachedMessage>& msgs) { // create transmitter to transmit msgs RoleAttributes new_attr; new_attr.CopyFrom(this->attr_); std::string new_channel_name = std::to_string(this->attr_.id()) + std::to_string(opposite_attr.id()); uint64_t channel_id = common::GlobalData::RegisterChannel(new_channel_name); new_attr.set_channel_name(new_channel_name); new_attr.set_channel_id(channel_id); auto new_transmitter = std::make_shared<RtpsTransmitter<M>>(new_attr, participant_); new_transmitter->Enable(); for (auto& item : msgs) { new_transmitter->Transmit(item.msg, item.msg_info); cyber::USleep(1000); } new_transmitter->Disable(); ADEBUG << "trans threadfunc exit."; } template <typename M> Relation HybridTransmitter<M>::GetRelation( const RoleAttributes& opposite_attr) { if (opposite_attr.channel_name() != this->attr_.channel_name()) { return NO_RELATION; } if (opposite_attr.host_ip() != this->attr_.host_ip()) { return DIFF_HOST; } if (opposite_attr.process_id() != this->attr_.process_id()) { return DIFF_PROC; } return SAME_PROC; } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_TRANSMITTER_HYBRID_TRANSMITTER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/transmitter/transmitter.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_TRANSPORT_TRANSMITTER_TRANSMITTER_H_ #define CYBER_TRANSPORT_TRANSMITTER_TRANSMITTER_H_ #include <cstdint> #include <memory> #include <string> #include "cyber/event/perf_event_cache.h" #include "cyber/transport/common/endpoint.h" #include "cyber/transport/message/message_info.h" namespace apollo { namespace cyber { namespace transport { using apollo::cyber::event::PerfEventCache; using apollo::cyber::event::TransPerf; template <typename M> class Transmitter : public Endpoint { public: using MessagePtr = std::shared_ptr<M>; explicit Transmitter(const RoleAttributes& attr); virtual ~Transmitter(); virtual void Enable() = 0; virtual void Disable() = 0; virtual void Enable(const RoleAttributes& opposite_attr); virtual void Disable(const RoleAttributes& opposite_attr); virtual bool Transmit(const MessagePtr& msg); virtual bool Transmit(const MessagePtr& msg, const MessageInfo& msg_info) = 0; uint64_t NextSeqNum() { return ++seq_num_; } uint64_t seq_num() const { return seq_num_; } protected: uint64_t seq_num_; MessageInfo msg_info_; }; template <typename M> Transmitter<M>::Transmitter(const RoleAttributes& attr) : Endpoint(attr), seq_num_(0) { msg_info_.set_sender_id(this->id_); msg_info_.set_seq_num(this->seq_num_); } template <typename M> Transmitter<M>::~Transmitter() {} template <typename M> bool Transmitter<M>::Transmit(const MessagePtr& msg) { msg_info_.set_seq_num(NextSeqNum()); PerfEventCache::Instance()->AddTransportEvent( TransPerf::TRANSMIT_BEGIN, attr_.channel_id(), msg_info_.seq_num()); return Transmit(msg, msg_info_); } template <typename M> void Transmitter<M>::Enable(const RoleAttributes& opposite_attr) { (void)opposite_attr; Enable(); } template <typename M> void Transmitter<M>::Disable(const RoleAttributes& opposite_attr) { (void)opposite_attr; Disable(); } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_TRANSMITTER_TRANSMITTER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/transmitter/intra_transmitter.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_TRANSPORT_TRANSMITTER_INTRA_TRANSMITTER_H_ #define CYBER_TRANSPORT_TRANSMITTER_INTRA_TRANSMITTER_H_ #include <memory> #include <string> #include "cyber/common/log.h" #include "cyber/transport/dispatcher/intra_dispatcher.h" #include "cyber/transport/transmitter/transmitter.h" namespace apollo { namespace cyber { namespace transport { template <typename M> class IntraTransmitter : public Transmitter<M> { public: using MessagePtr = std::shared_ptr<M>; explicit IntraTransmitter(const RoleAttributes& attr); virtual ~IntraTransmitter(); void Enable() override; void Disable() override; bool Transmit(const MessagePtr& msg, const MessageInfo& msg_info) override; private: uint64_t channel_id_; IntraDispatcherPtr dispatcher_; }; template <typename M> IntraTransmitter<M>::IntraTransmitter(const RoleAttributes& attr) : Transmitter<M>(attr), channel_id_(attr.channel_id()), dispatcher_(nullptr) {} template <typename M> IntraTransmitter<M>::~IntraTransmitter() { Disable(); } template <typename M> void IntraTransmitter<M>::Enable() { if (!this->enabled_) { dispatcher_ = IntraDispatcher::Instance(); this->enabled_ = true; } } template <typename M> void IntraTransmitter<M>::Disable() { if (this->enabled_) { dispatcher_ = nullptr; this->enabled_ = false; } } template <typename M> bool IntraTransmitter<M>::Transmit(const MessagePtr& msg, const MessageInfo& msg_info) { if (!this->enabled_) { ADEBUG << "not enable."; return false; } dispatcher_->OnMessage(channel_id_, msg, msg_info); return true; } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_TRANSMITTER_INTRA_TRANSMITTER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/transmitter/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_transport_transmitter_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "transmitter", deps = [ ":hybrid_transmitter", ":intra_transmitter", ":rtps_transmitter", ":shm_transmitter", ], ) cc_library( name = "hybrid_transmitter", hdrs = ["hybrid_transmitter.h"], deps = [ ":transmitter_interface", ], ) cc_library( name = "intra_transmitter", hdrs = ["intra_transmitter.h"], deps = [ ":transmitter_interface", ], ) cc_library( name = "transmitter_interface", hdrs = ["transmitter.h"], deps = [ "//cyber/event:perf_event_cache", "//cyber/transport/common:endpoint", "//cyber/transport/message:message_info", ], ) cc_library( name = "rtps_transmitter", hdrs = ["rtps_transmitter.h"], deps = [ ":transmitter_interface", ], ) cc_library( name = "shm_transmitter", hdrs = ["shm_transmitter.h"], deps = [ ":transmitter_interface", ], ) cpplint()
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/qos/qos_profile_conf.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_TRANSPORT_QOS_QOS_PROFILE_CONF_H_ #define CYBER_TRANSPORT_QOS_QOS_PROFILE_CONF_H_ #include <cstdint> #include "cyber/proto/qos_profile.pb.h" namespace apollo { namespace cyber { namespace transport { using cyber::proto::QosDurabilityPolicy; using cyber::proto::QosHistoryPolicy; using cyber::proto::QosProfile; using cyber::proto::QosReliabilityPolicy; class QosProfileConf { public: QosProfileConf(); virtual ~QosProfileConf(); static QosProfile CreateQosProfile(const QosHistoryPolicy& history, uint32_t depth, uint32_t mps, const QosReliabilityPolicy& reliability, const QosDurabilityPolicy& durability); static const uint32_t QOS_HISTORY_DEPTH_SYSTEM_DEFAULT; static const uint32_t QOS_MPS_SYSTEM_DEFAULT; static const QosProfile QOS_PROFILE_DEFAULT; static const QosProfile QOS_PROFILE_SENSOR_DATA; static const QosProfile QOS_PROFILE_PARAMETERS; static const QosProfile QOS_PROFILE_SERVICES_DEFAULT; static const QosProfile QOS_PROFILE_PARAM_EVENT; static const QosProfile QOS_PROFILE_SYSTEM_DEFAULT; static const QosProfile QOS_PROFILE_TF_STATIC; static const QosProfile QOS_PROFILE_TOPO_CHANGE; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_QOS_QOS_PROFILE_CONF_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/qos/qos_profile_conf.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/transport/qos/qos_profile_conf.h" namespace apollo { namespace cyber { namespace transport { QosProfileConf::QosProfileConf() {} QosProfileConf::~QosProfileConf() {} QosProfile QosProfileConf::CreateQosProfile( const QosHistoryPolicy& history, uint32_t depth, uint32_t mps, const QosReliabilityPolicy& reliability, const QosDurabilityPolicy& durability) { QosProfile qos_profile; qos_profile.set_history(history); qos_profile.set_depth(depth); qos_profile.set_mps(mps); qos_profile.set_reliability(reliability); qos_profile.set_durability(durability); return qos_profile; } const uint32_t QosProfileConf::QOS_HISTORY_DEPTH_SYSTEM_DEFAULT = 0; const uint32_t QosProfileConf::QOS_MPS_SYSTEM_DEFAULT = 0; const QosProfile QosProfileConf::QOS_PROFILE_DEFAULT = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_LAST, 1, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_VOLATILE); const QosProfile QosProfileConf::QOS_PROFILE_SENSOR_DATA = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_LAST, 5, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_BEST_EFFORT, QosDurabilityPolicy::DURABILITY_VOLATILE); const QosProfile QosProfileConf::QOS_PROFILE_PARAMETERS = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_VOLATILE); const QosProfile QosProfileConf::QOS_PROFILE_SERVICES_DEFAULT = CreateQosProfile(QosHistoryPolicy::HISTORY_KEEP_LAST, 10, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); const QosProfile QosProfileConf::QOS_PROFILE_PARAM_EVENT = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_VOLATILE); const QosProfile QosProfileConf::QOS_PROFILE_SYSTEM_DEFAULT = CreateQosProfile( QosHistoryPolicy::HISTORY_SYSTEM_DEFAULT, QOS_HISTORY_DEPTH_SYSTEM_DEFAULT, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); const QosProfile QosProfileConf::QOS_PROFILE_TF_STATIC = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); const QosProfile QosProfileConf::QOS_PROFILE_TOPO_CHANGE = CreateQosProfile( QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE, QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/qos/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") filegroup( name = "cyber_transport_qos_hdrs", srcs = glob([ "*.h", ]), visibility = ["//visibility:public"], ) cc_library( name = "qos", visibility = ["//visibility:public"], deps = [ ":qos_profile_conf", ], ) cc_library( name = "qos_profile_conf", srcs = ["qos_profile_conf.cc"], hdrs = ["qos_profile_conf.h"], deps = [ "//cyber/proto:qos_profile_cc_proto", ], ) cpplint()
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/shm_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/transport/dispatcher/shm_dispatcher.h" #include <memory> #include "gtest/gtest.h" #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/common/util.h" #include "cyber/init.h" #include "cyber/message/raw_message.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/transport/common/identity.h" #include "cyber/transport/transport.h" namespace apollo { namespace cyber { namespace transport { TEST(ShmDispatcherTest, add_listener) { auto dispatcher = ShmDispatcher::Instance(); RoleAttributes self_attr; self_attr.set_channel_name("add_listener"); self_attr.set_channel_id(common::Hash("add_listener")); Identity self_id; self_attr.set_id(self_id.HashValue()); dispatcher->AddListener<proto::Chatter>( self_attr, [](const std::shared_ptr<proto::Chatter>&, const MessageInfo&) {}); RoleAttributes oppo_attr; oppo_attr.CopyFrom(self_attr); Identity oppo_id; oppo_attr.set_id(oppo_id.HashValue()); dispatcher->AddListener<proto::Chatter>( self_attr, oppo_attr, [](const std::shared_ptr<proto::Chatter>&, const MessageInfo&) {}); } TEST(ShmDispatcherTest, on_message) { auto dispatcher = ShmDispatcher::Instance(); RoleAttributes oppo_attr; oppo_attr.set_host_name(common::GlobalData::Instance()->HostName()); oppo_attr.set_host_ip(common::GlobalData::Instance()->HostIp()); oppo_attr.set_channel_name("on_message"); oppo_attr.set_channel_id(common::Hash("on_message")); Identity oppo_id; oppo_attr.set_id(oppo_id.HashValue()); auto transmitter = Transport::Instance()->CreateTransmitter<message::RawMessage>( oppo_attr, proto::OptionalMode::SHM); EXPECT_NE(transmitter, nullptr); auto send_msg = std::make_shared<message::RawMessage>("raw_message"); transmitter->Transmit(send_msg); sleep(1); RoleAttributes self_attr; self_attr.set_channel_name("on_message"); self_attr.set_channel_id(common::Hash("on_message")); Identity self_id; self_attr.set_id(self_id.HashValue()); auto recv_msg = std::make_shared<message::RawMessage>(); dispatcher->AddListener<message::RawMessage>( self_attr, [&recv_msg](const std::shared_ptr<message::RawMessage>& msg, const MessageInfo& msg_info) { (void)msg_info; recv_msg->message = msg->message; }); transmitter->Transmit(send_msg); sleep(1); EXPECT_EQ(recv_msg->message, send_msg->message); } TEST(ShmDispatcherTest, shutdown) { auto dispatcher = ShmDispatcher::Instance(); dispatcher->Shutdown(); // repeated call dispatcher->Shutdown(); } } // namespace transport } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); apollo::cyber::Init(argv[0]); apollo::cyber::transport::Transport::Instance(); auto res = RUN_ALL_TESTS(); apollo::cyber::transport::Transport::Instance()->Shutdown(); return res; }
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/shm_dispatcher.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/transport/dispatcher/shm_dispatcher.h" #include "cyber/common/global_data.h" #include "cyber/common/util.h" #include "cyber/scheduler/scheduler_factory.h" #include "cyber/transport/shm/readable_info.h" namespace apollo { namespace cyber { namespace transport { using common::GlobalData; ShmDispatcher::ShmDispatcher() : host_id_(0) { Init(); } ShmDispatcher::~ShmDispatcher() { Shutdown(); } void ShmDispatcher::Shutdown() { if (is_shutdown_.exchange(true)) { return; } if (thread_.joinable()) { thread_.join(); } { ReadLockGuard<AtomicRWLock> lock(segments_lock_); segments_.clear(); } } void ShmDispatcher::AddSegment(const RoleAttributes& self_attr) { uint64_t channel_id = self_attr.channel_id(); WriteLockGuard<AtomicRWLock> lock(segments_lock_); if (segments_.count(channel_id) > 0) { return; } auto segment = SegmentFactory::CreateSegment(channel_id); segments_[channel_id] = segment; previous_indexes_[channel_id] = UINT32_MAX; } void ShmDispatcher::ReadMessage(uint64_t channel_id, uint32_t block_index) { ADEBUG << "Reading sharedmem message: " << GlobalData::GetChannelById(channel_id) << " from block: " << block_index; auto rb = std::make_shared<ReadableBlock>(); rb->index = block_index; if (!segments_[channel_id]->AcquireBlockToRead(rb.get())) { AWARN << "fail to acquire block, channel: " << GlobalData::GetChannelById(channel_id) << " index: " << block_index; return; } MessageInfo msg_info; const char* msg_info_addr = reinterpret_cast<char*>(rb->buf) + rb->block->msg_size(); if (msg_info.DeserializeFrom(msg_info_addr, rb->block->msg_info_size())) { OnMessage(channel_id, rb, msg_info); } else { AERROR << "error msg info of channel:" << GlobalData::GetChannelById(channel_id); } segments_[channel_id]->ReleaseReadBlock(*rb); } void ShmDispatcher::OnMessage(uint64_t channel_id, const std::shared_ptr<ReadableBlock>& rb, const MessageInfo& msg_info) { if (is_shutdown_.load()) { return; } ListenerHandlerBasePtr* handler_base = nullptr; if (msg_listeners_.Get(channel_id, &handler_base)) { auto handler = std::dynamic_pointer_cast<ListenerHandler<ReadableBlock>>( *handler_base); handler->Run(rb, msg_info); } else { AERROR << "Cannot find " << GlobalData::GetChannelById(channel_id) << "'s handler."; } } void ShmDispatcher::ThreadFunc() { ReadableInfo readable_info; while (!is_shutdown_.load()) { if (!notifier_->Listen(100, &readable_info)) { ADEBUG << "listen failed."; continue; } if (readable_info.host_id() != host_id_) { ADEBUG << "shm readable info from other host."; continue; } uint64_t channel_id = readable_info.channel_id(); uint32_t block_index = readable_info.block_index(); { ReadLockGuard<AtomicRWLock> lock(segments_lock_); if (segments_.count(channel_id) == 0) { continue; } // check block index if (previous_indexes_.count(channel_id) == 0) { previous_indexes_[channel_id] = UINT32_MAX; } uint32_t& previous_index = previous_indexes_[channel_id]; if (block_index != 0 && previous_index != UINT32_MAX) { if (block_index == previous_index) { ADEBUG << "Receive SAME index " << block_index << " of channel " << channel_id; } else if (block_index < previous_index) { ADEBUG << "Receive PREVIOUS message. last: " << previous_index << ", now: " << block_index; } else if (block_index - previous_index > 1) { ADEBUG << "Receive JUMP message. last: " << previous_index << ", now: " << block_index; } } previous_index = block_index; ReadMessage(channel_id, block_index); } } } bool ShmDispatcher::Init() { host_id_ = common::Hash(GlobalData::Instance()->HostIp()); notifier_ = NotifierFactory::CreateNotifier(); thread_ = std::thread(&ShmDispatcher::ThreadFunc, this); scheduler::Instance()->SetInnerThreadAttr("shm_disp", &thread_); return true; } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/rtps_dispatcher.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/transport/dispatcher/rtps_dispatcher.h" namespace apollo { namespace cyber { namespace transport { RtpsDispatcher::RtpsDispatcher() : participant_(nullptr) {} RtpsDispatcher::~RtpsDispatcher() { Shutdown(); } void RtpsDispatcher::Shutdown() { if (is_shutdown_.exchange(true)) { return; } { std::lock_guard<std::mutex> lock(subs_mutex_); for (auto& item : subs_) { item.second.sub = nullptr; } } participant_ = nullptr; } void RtpsDispatcher::AddSubscriber(const RoleAttributes& self_attr) { if (participant_ == nullptr) { AWARN << "please set participant firstly."; return; } uint64_t channel_id = self_attr.channel_id(); std::lock_guard<std::mutex> lock(subs_mutex_); if (subs_.count(channel_id) > 0) { return; } Subscriber new_sub; eprosima::fastrtps::SubscriberAttributes sub_attr; auto& qos = self_attr.qos_profile(); RETURN_IF(!AttributesFiller::FillInSubAttr(self_attr.channel_name(), qos, &sub_attr)); new_sub.sub_listener = std::make_shared<SubListener>( std::bind(&RtpsDispatcher::OnMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); new_sub.sub = eprosima::fastrtps::Domain::createSubscriber( participant_->fastrtps_participant(), sub_attr, new_sub.sub_listener.get()); RETURN_IF_NULL(new_sub.sub); subs_[channel_id] = new_sub; } void RtpsDispatcher::OnMessage(uint64_t channel_id, const std::shared_ptr<std::string>& msg_str, const MessageInfo& msg_info) { if (is_shutdown_.load()) { return; } ListenerHandlerBasePtr* handler_base = nullptr; if (msg_listeners_.Get(channel_id, &handler_base)) { auto handler = std::dynamic_pointer_cast<ListenerHandler<std::string>>(*handler_base); handler->Run(msg_str, msg_info); } } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/intra_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_TRANSPORT_DISPATCHER_INTRA_DISPATCHER_H_ #define CYBER_TRANSPORT_DISPATCHER_INTRA_DISPATCHER_H_ #include <iostream> #include <map> #include <memory> #include <string> #include <utility> #include "cyber/base/atomic_rw_lock.h" #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "cyber/message/message_traits.h" #include "cyber/message/raw_message.h" #include "cyber/transport/dispatcher/dispatcher.h" namespace apollo { namespace cyber { namespace transport { class IntraDispatcher; using IntraDispatcherPtr = IntraDispatcher*; class ChannelChain; using ChannelChainPtr = std::shared_ptr<ChannelChain>; template <typename MessageT> using MessageListener = std::function<void(const std::shared_ptr<MessageT>&, const MessageInfo&)>; // use a channel chain to wrap specific ListenerHandler. // If the message is MessageT, then we use pointer directly, or we first parse // to a string, and use it to serialise to another message type. class ChannelChain { using BaseHandlersType = std::map<uint64_t, std::map<std::string, ListenerHandlerBasePtr>>; public: template <typename MessageT> bool AddListener(uint64_t self_id, uint64_t channel_id, const std::string& message_type, const MessageListener<MessageT>& listener) { WriteLockGuard<base::AtomicRWLock> lg(rw_lock_); auto ret = GetHandler<MessageT>(channel_id, message_type, &handlers_); auto handler = ret.first; if (handler == nullptr) { AERROR << "get handler failed. channel: " << GlobalData::GetChannelById(channel_id) << ", message type: " << message::GetMessageName<MessageT>(); return ret.second; } handler->Connect(self_id, listener); return ret.second; } template <typename MessageT> bool AddListener(uint64_t self_id, uint64_t oppo_id, uint64_t channel_id, const std::string& message_type, const MessageListener<MessageT>& listener) { WriteLockGuard<base::AtomicRWLock> lg(oppo_rw_lock_); if (oppo_handlers_.find(oppo_id) == oppo_handlers_.end()) { oppo_handlers_[oppo_id] = BaseHandlersType(); } BaseHandlersType& handlers = oppo_handlers_[oppo_id]; auto ret = GetHandler<MessageT>(channel_id, message_type, &handlers); auto handler = ret.first; if (handler == nullptr) { AERROR << "get handler failed. channel: " << GlobalData::GetChannelById(channel_id) << ", message type: " << message_type; return ret.second; } handler->Connect(self_id, oppo_id, listener); return ret.second; } template <typename MessageT> void RemoveListener(uint64_t self_id, uint64_t channel_id, const std::string& message_type) { WriteLockGuard<base::AtomicRWLock> lg(rw_lock_); auto handler = RemoveHandler(channel_id, message_type, &handlers_); if (handler) { handler->Disconnect(self_id); } } template <typename MessageT> void RemoveListener(uint64_t self_id, uint64_t oppo_id, uint64_t channel_id, const std::string& message_type) { WriteLockGuard<base::AtomicRWLock> lg(oppo_rw_lock_); if (oppo_handlers_.find(oppo_id) == oppo_handlers_.end()) { return; } BaseHandlersType& handlers = oppo_handlers_[oppo_id]; auto handler = RemoveHandler(channel_id, message_type, &handlers); if (oppo_handlers_[oppo_id].empty()) { oppo_handlers_.erase(oppo_id); } if (handler) { handler->Disconnect(self_id, oppo_id); } } template <typename MessageT> void Run(uint64_t self_id, uint64_t channel_id, const std::string& message_type, const std::shared_ptr<MessageT>& message, const MessageInfo& message_info) { ReadLockGuard<base::AtomicRWLock> lg(rw_lock_); Run(channel_id, message_type, handlers_, message, message_info); } template <typename MessageT> void Run(uint64_t self_id, uint64_t oppo_id, uint64_t channel_id, const std::string& message_type, const std::shared_ptr<MessageT>& message, const MessageInfo& message_info) { ReadLockGuard<base::AtomicRWLock> lg(oppo_rw_lock_); if (oppo_handlers_.find(oppo_id) == oppo_handlers_.end()) { return; } BaseHandlersType& handlers = oppo_handlers_[oppo_id]; Run(channel_id, message_type, handlers, message, message_info); } private: // NOTE: lock hold template <typename MessageT> std::pair<std::shared_ptr<ListenerHandler<MessageT>>, bool> GetHandler( uint64_t channel_id, const std::string& message_type, BaseHandlersType* handlers) { std::shared_ptr<ListenerHandler<MessageT>> handler; bool created = false; // if the handler is created if (handlers->find(channel_id) == handlers->end()) { (*handlers)[channel_id] = std::map<std::string, ListenerHandlerBasePtr>(); } if ((*handlers)[channel_id].find(message_type) == (*handlers)[channel_id].end()) { ADEBUG << "Create new ListenerHandler for channel " << GlobalData::GetChannelById(channel_id) << ", message type: " << message_type; handler.reset(new ListenerHandler<MessageT>()); (*handlers)[channel_id][message_type] = handler; created = true; } else { ADEBUG << "Find channel " << GlobalData::GetChannelById(channel_id) << "'s ListenerHandler, message type: " << message_type; handler = std::dynamic_pointer_cast<ListenerHandler<MessageT>>( (*handlers)[channel_id][message_type]); } return std::make_pair(handler, created); } // NOTE: Lock hold ListenerHandlerBasePtr RemoveHandler(int64_t channel_id, const std::string message_type, BaseHandlersType* handlers) { ListenerHandlerBasePtr handler_base; if (handlers->find(channel_id) != handlers->end()) { if ((*handlers)[channel_id].find(message_type) != (*handlers)[channel_id].end()) { handler_base = (*handlers)[channel_id][message_type]; ADEBUG << "remove " << GlobalData::GetChannelById(channel_id) << "'s " << message_type << " ListenerHandler"; (*handlers)[channel_id].erase(message_type); } if ((*handlers)[channel_id].empty()) { ADEBUG << "remove " << GlobalData::GetChannelById(channel_id) << "'s all ListenerHandler"; (*handlers).erase(channel_id); } } return handler_base; } template <typename MessageT> void Run(const uint64_t channel_id, const std::string& message_type, const BaseHandlersType& handlers, const std::shared_ptr<MessageT>& message, const MessageInfo& message_info) { const auto channel_handlers_itr = handlers.find(channel_id); if (channel_handlers_itr == handlers.end()) { AERROR << "Cant find channel " << GlobalData::GetChannelById(channel_id) << " in Chain"; return; } const auto& channel_handlers = channel_handlers_itr->second; ADEBUG << GlobalData::GetChannelById(channel_id) << "'s chain run, size: " << channel_handlers.size() << ", message type: " << message_type; std::string msg; for (const auto& ele : channel_handlers) { auto handler_base = ele.second; if (message_type == ele.first) { ADEBUG << "Run handler for message type: " << ele.first << " directly"; auto handler = std::static_pointer_cast<ListenerHandler<MessageT>>(handler_base); if (handler == nullptr) { continue; } handler->Run(message, message_info); } else { ADEBUG << "Run handler for message type: " << ele.first << " from string"; if (msg.empty()) { auto msg_size = message::FullByteSize(*message); if (msg_size < 0) { AERROR << "Failed to get message size. channel[" << common::GlobalData::GetChannelById(channel_id) << "]"; continue; } msg.resize(msg_size); if (!message::SerializeToHC(*message, const_cast<char*>(msg.data()), msg_size)) { AERROR << "Chain Serialize error for channel id: " << channel_id; msg.clear(); } } if (!msg.empty()) { (handler_base)->RunFromString(msg, message_info); } } } } BaseHandlersType handlers_; base::AtomicRWLock rw_lock_; std::map<uint64_t, BaseHandlersType> oppo_handlers_; base::AtomicRWLock oppo_rw_lock_; }; class IntraDispatcher : public Dispatcher { public: virtual ~IntraDispatcher(); template <typename MessageT> void OnMessage(uint64_t channel_id, const std::shared_ptr<MessageT>& message, const MessageInfo& message_info); template <typename MessageT> void AddListener(const RoleAttributes& self_attr, const MessageListener<MessageT>& listener); template <typename MessageT> void AddListener(const RoleAttributes& self_attr, const RoleAttributes& opposite_attr, const MessageListener<MessageT>& listener); template <typename MessageT> void RemoveListener(const RoleAttributes& self_attr); template <typename MessageT> void RemoveListener(const RoleAttributes& self_attr, const RoleAttributes& opposite_attr); DECLARE_SINGLETON(IntraDispatcher) private: template <typename MessageT> std::shared_ptr<ListenerHandler<MessageT>> GetHandler(uint64_t channel_id); ChannelChainPtr chain_; }; template <typename MessageT> void IntraDispatcher::OnMessage(uint64_t channel_id, const std::shared_ptr<MessageT>& message, const MessageInfo& message_info) { if (is_shutdown_.load()) { return; } ListenerHandlerBasePtr* handler_base = nullptr; ADEBUG << "intra on message, channel:" << common::GlobalData::GetChannelById(channel_id); if (msg_listeners_.Get(channel_id, &handler_base)) { auto handler = std::dynamic_pointer_cast<ListenerHandler<MessageT>>(*handler_base); if (handler) { handler->Run(message, message_info); } else { auto msg_size = message::FullByteSize(*message); if (msg_size < 0) { AERROR << "Failed to get message size. channel[" << common::GlobalData::GetChannelById(channel_id) << "]"; return; } std::string msg; msg.resize(msg_size); if (message::SerializeToHC(*message, const_cast<char*>(msg.data()), msg_size)) { (*handler_base)->RunFromString(msg, message_info); } else { AERROR << "Failed to serialize message. channel[" << common::GlobalData::GetChannelById(channel_id) << "]"; } } } } template <typename MessageT> std::shared_ptr<ListenerHandler<MessageT>> IntraDispatcher::GetHandler( uint64_t channel_id) { std::shared_ptr<ListenerHandler<MessageT>> handler; ListenerHandlerBasePtr* handler_base = nullptr; if (msg_listeners_.Get(channel_id, &handler_base)) { handler = std::dynamic_pointer_cast<ListenerHandler<MessageT>>(*handler_base); if (handler == nullptr) { ADEBUG << "Find a new type for channel " << GlobalData::GetChannelById(channel_id) << " with type " << message::GetMessageName<MessageT>(); } } else { ADEBUG << "Create new ListenerHandler for channel " << GlobalData::GetChannelById(channel_id) << " with type " << message::GetMessageName<MessageT>(); handler.reset(new ListenerHandler<MessageT>()); msg_listeners_.Set(channel_id, handler); } return handler; } template <typename MessageT> void IntraDispatcher::AddListener(const RoleAttributes& self_attr, const MessageListener<MessageT>& listener) { if (is_shutdown_.load()) { return; } auto channel_id = self_attr.channel_id(); std::string message_type = message::GetMessageName<MessageT>(); uint64_t self_id = self_attr.id(); bool created = chain_->AddListener(self_id, channel_id, message_type, listener); auto handler = GetHandler<MessageT>(self_attr.channel_id()); if (handler && created) { auto listener_wrapper = [this, self_id, channel_id, message_type]( const std::shared_ptr<MessageT>& message, const MessageInfo& message_info) { this->chain_->Run<MessageT>(self_id, channel_id, message_type, message, message_info); }; handler->Connect(self_id, listener_wrapper); } } template <typename MessageT> void IntraDispatcher::AddListener(const RoleAttributes& self_attr, const RoleAttributes& opposite_attr, const MessageListener<MessageT>& listener) { if (is_shutdown_.load()) { return; } auto channel_id = self_attr.channel_id(); std::string message_type = message::GetMessageName<MessageT>(); uint64_t self_id = self_attr.id(); uint64_t oppo_id = opposite_attr.id(); bool created = chain_->AddListener(self_id, oppo_id, channel_id, message_type, listener); auto handler = GetHandler<MessageT>(self_attr.channel_id()); if (handler && created) { auto listener_wrapper = [this, self_id, oppo_id, channel_id, message_type]( const std::shared_ptr<MessageT>& message, const MessageInfo& message_info) { this->chain_->Run<MessageT>(self_id, oppo_id, channel_id, message_type, message, message_info); }; handler->Connect(self_id, oppo_id, listener_wrapper); } } template <typename MessageT> void IntraDispatcher::RemoveListener(const RoleAttributes& self_attr) { if (is_shutdown_.load()) { return; } Dispatcher::RemoveListener<MessageT>(self_attr); chain_->RemoveListener<MessageT>(self_attr.id(), self_attr.channel_id(), message::GetMessageName<MessageT>()); } template <typename MessageT> void IntraDispatcher::RemoveListener(const RoleAttributes& self_attr, const RoleAttributes& opposite_attr) { if (is_shutdown_.load()) { return; } Dispatcher::RemoveListener<MessageT>(self_attr, opposite_attr); chain_->RemoveListener<MessageT>(self_attr.id(), opposite_attr.id(), self_attr.channel_id(), message::GetMessageName<MessageT>()); } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_DISPATCHER_INTRA_DISPATCHER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/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_TRANSPORT_DISPATCHER_DISPATCHER_H_ #define CYBER_TRANSPORT_DISPATCHER_DISPATCHER_H_ #include <atomic> #include <functional> #include <iostream> #include <memory> #include <mutex> #include <string> #include <unordered_map> #include "cyber/base/atomic_hash_map.h" #include "cyber/base/atomic_rw_lock.h" #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/proto/role_attributes.pb.h" #include "cyber/transport/message/listener_handler.h" #include "cyber/transport/message/message_info.h" namespace apollo { namespace cyber { namespace transport { using apollo::cyber::base::AtomicHashMap; using apollo::cyber::base::AtomicRWLock; using apollo::cyber::base::ReadLockGuard; using apollo::cyber::base::WriteLockGuard; using apollo::cyber::common::GlobalData; using cyber::proto::RoleAttributes; class Dispatcher; using DispatcherPtr = std::shared_ptr<Dispatcher>; template <typename MessageT> using MessageListener = std::function<void(const std::shared_ptr<MessageT>&, const MessageInfo&)>; class Dispatcher { public: Dispatcher(); virtual ~Dispatcher(); virtual void Shutdown(); template <typename MessageT> void AddListener(const RoleAttributes& self_attr, const MessageListener<MessageT>& listener); template <typename MessageT> void AddListener(const RoleAttributes& self_attr, const RoleAttributes& opposite_attr, const MessageListener<MessageT>& listener); template <typename MessageT> void RemoveListener(const RoleAttributes& self_attr); template <typename MessageT> void RemoveListener(const RoleAttributes& self_attr, const RoleAttributes& opposite_attr); bool HasChannel(uint64_t channel_id); protected: std::atomic<bool> is_shutdown_; // key: channel_id of message AtomicHashMap<uint64_t, ListenerHandlerBasePtr> msg_listeners_; base::AtomicRWLock rw_lock_; }; template <typename MessageT> void Dispatcher::AddListener(const RoleAttributes& self_attr, const MessageListener<MessageT>& listener) { if (is_shutdown_.load()) { return; } uint64_t channel_id = self_attr.channel_id(); std::shared_ptr<ListenerHandler<MessageT>> handler; ListenerHandlerBasePtr* handler_base = nullptr; if (msg_listeners_.Get(channel_id, &handler_base)) { handler = std::dynamic_pointer_cast<ListenerHandler<MessageT>>(*handler_base); if (handler == nullptr) { AERROR << "please ensure that readers with the same channel[" << self_attr.channel_name() << "] in the same process have the same message type"; return; } } else { ADEBUG << "new reader for channel:" << GlobalData::GetChannelById(channel_id); handler.reset(new ListenerHandler<MessageT>()); msg_listeners_.Set(channel_id, handler); } handler->Connect(self_attr.id(), listener); } template <typename MessageT> void Dispatcher::AddListener(const RoleAttributes& self_attr, const RoleAttributes& opposite_attr, const MessageListener<MessageT>& listener) { if (is_shutdown_.load()) { return; } uint64_t channel_id = self_attr.channel_id(); std::shared_ptr<ListenerHandler<MessageT>> handler; ListenerHandlerBasePtr* handler_base = nullptr; if (msg_listeners_.Get(channel_id, &handler_base)) { handler = std::dynamic_pointer_cast<ListenerHandler<MessageT>>(*handler_base); if (handler == nullptr) { AERROR << "please ensure that readers with the same channel[" << self_attr.channel_name() << "] in the same process have the same message type"; return; } } else { ADEBUG << "new reader for channel:" << GlobalData::GetChannelById(channel_id); handler.reset(new ListenerHandler<MessageT>()); msg_listeners_.Set(channel_id, handler); } handler->Connect(self_attr.id(), opposite_attr.id(), listener); } template <typename MessageT> void Dispatcher::RemoveListener(const RoleAttributes& self_attr) { if (is_shutdown_.load()) { return; } uint64_t channel_id = self_attr.channel_id(); ListenerHandlerBasePtr* handler_base = nullptr; if (msg_listeners_.Get(channel_id, &handler_base)) { (*handler_base)->Disconnect(self_attr.id()); } } template <typename MessageT> void Dispatcher::RemoveListener(const RoleAttributes& self_attr, const RoleAttributes& opposite_attr) { if (is_shutdown_.load()) { return; } uint64_t channel_id = self_attr.channel_id(); ListenerHandlerBasePtr* handler_base = nullptr; if (msg_listeners_.Get(channel_id, &handler_base)) { (*handler_base)->Disconnect(self_attr.id(), opposite_attr.id()); } } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_DISPATCHER_DISPATCHER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/intra_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/transport/dispatcher/intra_dispatcher.h" #include <memory> #include "gtest/gtest.h" #include "cyber/common/util.h" #include "cyber/message/raw_message.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/transport/common/identity.h" namespace apollo { namespace cyber { namespace transport { TEST(DispatcherTest, on_message) { auto dispatcher = IntraDispatcher::Instance(); std::vector<std::shared_ptr<proto::Chatter>> chatter_msgs; std::vector<std::shared_ptr<message::RawMessage>> raw_msgs; auto chatter = std::make_shared<proto::Chatter>(); chatter->set_content("chatter"); auto chatter2 = std::make_shared<proto::Chatter>(); chatter2->set_content("raw message"); std::string str; chatter2->SerializeToString(&str); auto raw = std::make_shared<message::RawMessage>(str); auto chatter_callback = [&chatter_msgs]( const std::shared_ptr<proto::Chatter>& msg, const MessageInfo&) { AINFO << "chatter callback"; chatter_msgs.push_back(msg); }; auto raw_callback = [&raw_msgs]( const std::shared_ptr<message::RawMessage>& msg, const MessageInfo&) { AINFO << "raw callback"; raw_msgs.push_back(msg); }; MessageInfo msg_info; const std::string channel_name = "channel"; const uint64_t channel_id = common::Hash(channel_name); proto::RoleAttributes self_attr1; self_attr1.set_channel_name(channel_name); self_attr1.set_channel_id(channel_id); self_attr1.set_id(Identity().HashValue()); proto::RoleAttributes self_attr2(self_attr1); self_attr2.set_id(Identity().HashValue()); proto::RoleAttributes self_none; self_none.set_channel_name("channel1"); self_none.set_channel_id(common::Hash("channel1")); proto::RoleAttributes oppo_attr1(self_attr1); Identity identity1; oppo_attr1.set_id(identity1.HashValue()); proto::RoleAttributes oppo_attr2(self_attr1); Identity identity2; oppo_attr2.set_id(identity2.HashValue()); // AddListener // add chatter dispatcher->AddListener<proto::Chatter>(self_attr1, chatter_callback); // add raw dispatcher->AddListener<message::RawMessage>(self_attr2, raw_callback); // add chatter opposite dispatcher->AddListener<proto::Chatter>(self_attr1, oppo_attr1, chatter_callback); // add raw opposite dispatcher->AddListener<message::RawMessage>(self_attr2, oppo_attr1, raw_callback); // run 1 + 2 dispatcher->OnMessage<proto::Chatter>(channel_id, chatter, msg_info); EXPECT_EQ(1, chatter_msgs.size()); EXPECT_EQ(1, raw_msgs.size()); // run 1, 3 + 2, 4 msg_info.set_sender_id(identity1); dispatcher->OnMessage<message::RawMessage>(channel_id, raw, msg_info); EXPECT_EQ(3, chatter_msgs.size()); EXPECT_EQ(3, raw_msgs.size()); Identity identity3; msg_info.set_sender_id(identity3); // no oppo handler, but self handler will run dispatcher->OnMessage<proto::Chatter>(channel_id, chatter, msg_info); // run 1 + 2 EXPECT_EQ(4, chatter_msgs.size()); EXPECT_EQ(4, raw_msgs.size()); // RemoveListenerHandler // find no key dispatcher->RemoveListener<proto::Chatter>(self_none); dispatcher->RemoveListener<proto::Chatter>(self_none, oppo_attr2); // find keys dispatcher->RemoveListener<proto::Chatter>(self_attr1); dispatcher->RemoveListener<proto::Chatter>(self_attr2); dispatcher->RemoveListener<proto::Chatter>(self_attr1, oppo_attr1); dispatcher->RemoveListener<proto::Chatter>(self_attr2, oppo_attr2); // run nothing raw_msgs.clear(); chatter_msgs.clear(); MessageInfo msg_info1; dispatcher->OnMessage<proto::Chatter>(channel_id, chatter, msg_info); EXPECT_EQ(0, chatter_msgs.size()); EXPECT_EQ(0, raw_msgs.size()); msg_info.set_sender_id(identity1); dispatcher->OnMessage<proto::Chatter>(channel_id, chatter, msg_info); EXPECT_EQ(0, chatter_msgs.size()); EXPECT_EQ(0, raw_msgs.size()); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/rtps_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/transport/dispatcher/rtps_dispatcher.h" #include <memory> #include "gtest/gtest.h" #include "cyber/common/util.h" #include "cyber/init.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/transport/common/identity.h" #include "cyber/transport/qos/qos_profile_conf.h" #include "cyber/transport/transport.h" namespace apollo { namespace cyber { namespace transport { TEST(RtpsDispatcherTest, add_listener) { auto dispatcher = RtpsDispatcher::Instance(); RoleAttributes self_attr; self_attr.set_channel_name("add_listener"); self_attr.set_channel_id(common::Hash("add_listener")); Identity self_id; self_attr.set_id(self_id.HashValue()); self_attr.mutable_qos_profile()->CopyFrom( QosProfileConf::QOS_PROFILE_DEFAULT); dispatcher->AddListener<proto::Chatter>( self_attr, [](const std::shared_ptr<proto::Chatter>&, const MessageInfo&) {}); RoleAttributes oppo_attr; oppo_attr.CopyFrom(self_attr); Identity oppo_id; oppo_attr.set_id(oppo_id.HashValue()); dispatcher->AddListener<proto::Chatter>( self_attr, oppo_attr, [](const std::shared_ptr<proto::Chatter>&, const MessageInfo&) {}); } TEST(RtpsDispatcherTest, on_message) { auto dispatcher = RtpsDispatcher::Instance(); RoleAttributes self_attr; self_attr.set_channel_name("channel_0"); self_attr.set_channel_id(common::Hash("channel_0")); Identity self_id; self_attr.set_id(self_id.HashValue()); self_attr.mutable_qos_profile()->CopyFrom( QosProfileConf::QOS_PROFILE_DEFAULT); auto recv_msg = std::make_shared<proto::Chatter>(); dispatcher->AddListener<proto::Chatter>( self_attr, [&recv_msg](const std::shared_ptr<proto::Chatter>& msg, const MessageInfo& msg_info) { (void)msg_info; recv_msg->CopyFrom(*msg); }); auto transmitter = Transport::Instance()->CreateTransmitter<proto::Chatter>( self_attr, proto::OptionalMode::RTPS); EXPECT_NE(transmitter, nullptr); auto send_msg = std::make_shared<proto::Chatter>(); send_msg->set_timestamp(123); send_msg->set_lidar_timestamp(456); send_msg->set_seq(789); send_msg->set_content("on_message"); transmitter->Transmit(send_msg); sleep(1); EXPECT_EQ(recv_msg->timestamp(), send_msg->timestamp()); EXPECT_EQ(recv_msg->lidar_timestamp(), send_msg->lidar_timestamp()); EXPECT_EQ(recv_msg->seq(), send_msg->seq()); EXPECT_EQ(recv_msg->content(), send_msg->content()); } TEST(RtpsDispatcherTest, shutdown) { auto dispatcher = RtpsDispatcher::Instance(); dispatcher->Shutdown(); // repeated call dispatcher->Shutdown(); } } // namespace transport } // namespace cyber } // namespace apollo int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); apollo::cyber::Init(argv[0]); apollo::cyber::transport::Transport::Instance(); auto res = RUN_ALL_TESTS(); apollo::cyber::transport::Transport::Instance()->Shutdown(); return res; }
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/rtps_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_TRANSPORT_DISPATCHER_RTPS_DISPATCHER_H_ #define CYBER_TRANSPORT_DISPATCHER_RTPS_DISPATCHER_H_ #include <iostream> #include <memory> #include <mutex> #include <string> #include <unordered_map> #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "cyber/message/message_traits.h" #include "cyber/transport/dispatcher/dispatcher.h" #include "cyber/transport/rtps/attributes_filler.h" #include "cyber/transport/rtps/participant.h" #include "cyber/transport/rtps/sub_listener.h" namespace apollo { namespace cyber { namespace transport { struct Subscriber { Subscriber() : sub(nullptr), sub_listener(nullptr) {} eprosima::fastrtps::Subscriber* sub; SubListenerPtr sub_listener; }; class RtpsDispatcher; using RtpsDispatcherPtr = RtpsDispatcher*; class RtpsDispatcher : public Dispatcher { public: virtual ~RtpsDispatcher(); void Shutdown() override; template <typename MessageT> void AddListener(const RoleAttributes& self_attr, const MessageListener<MessageT>& listener); template <typename MessageT> void AddListener(const RoleAttributes& self_attr, const RoleAttributes& opposite_attr, const MessageListener<MessageT>& listener); void set_participant(const ParticipantPtr& participant) { participant_ = participant; } private: void OnMessage(uint64_t channel_id, const std::shared_ptr<std::string>& msg_str, const MessageInfo& msg_info); void AddSubscriber(const RoleAttributes& self_attr); // key: channel_id std::unordered_map<uint64_t, Subscriber> subs_; std::mutex subs_mutex_; ParticipantPtr participant_; DECLARE_SINGLETON(RtpsDispatcher) }; template <typename MessageT> void RtpsDispatcher::AddListener(const RoleAttributes& self_attr, const MessageListener<MessageT>& listener) { auto listener_adapter = [listener]( const std::shared_ptr<std::string>& msg_str, const MessageInfo& msg_info) { auto msg = std::make_shared<MessageT>(); RETURN_IF(!message::ParseFromString(*msg_str, msg.get())); listener(msg, msg_info); }; Dispatcher::AddListener<std::string>(self_attr, listener_adapter); AddSubscriber(self_attr); } template <typename MessageT> void RtpsDispatcher::AddListener(const RoleAttributes& self_attr, const RoleAttributes& opposite_attr, const MessageListener<MessageT>& listener) { auto listener_adapter = [listener]( const std::shared_ptr<std::string>& msg_str, const MessageInfo& msg_info) { auto msg = std::make_shared<MessageT>(); RETURN_IF(!message::ParseFromString(*msg_str, msg.get())); listener(msg, msg_info); }; Dispatcher::AddListener<std::string>(self_attr, opposite_attr, listener_adapter); AddSubscriber(self_attr); } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_DISPATCHER_RTPS_DISPATCHER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_transport_dispatcher_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "dispatcher", srcs = ["dispatcher.cc"], hdrs = ["dispatcher.h"], deps = [ "//cyber/common", "//cyber/message:message_traits", "//cyber/proto:role_attributes_cc_proto", "//cyber/transport/message:listener_handler", "//cyber/transport/message:message_info", ], ) cc_test( name = "dispatcher_test", size = "small", srcs = ["dispatcher_test.cc"], deps = [ "//cyber:cyber_core", "//cyber/proto:unit_test_cc_proto", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "intra_dispatcher", srcs = ["intra_dispatcher.cc"], hdrs = ["intra_dispatcher.h"], deps = [ ":dispatcher", "//cyber/message:message_traits", "//cyber/proto:role_attributes_cc_proto", ], ) cc_test( name = "intra_dispatcher_test", size = "small", srcs = ["intra_dispatcher_test.cc"], deps = [ "//cyber:cyber_core", "//cyber/proto:unit_test_cc_proto", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "rtps_dispatcher", srcs = ["rtps_dispatcher.cc"], hdrs = ["rtps_dispatcher.h"], deps = [ ":dispatcher", "//cyber/message:message_traits", "//cyber/proto:role_attributes_cc_proto", "//cyber/transport/rtps:attributes_filler", "//cyber/transport/rtps:participant", "//cyber/transport/rtps:sub_listener", ], ) cc_test( name = "rtps_dispatcher_test", size = "small", srcs = ["rtps_dispatcher_test.cc"], deps = [ "//cyber:cyber_core", "//cyber/proto:unit_test_cc_proto", "@com_google_googletest//:gtest", ], ) cc_library( name = "shm_dispatcher", srcs = ["shm_dispatcher.cc"], hdrs = ["shm_dispatcher.h"], deps = [ ":dispatcher", "//cyber/message:message_traits", "//cyber/proto:proto_desc_cc_proto", "//cyber/scheduler:scheduler_factory", "//cyber/transport/shm:notifier_factory", "//cyber/transport/shm:readable_info", "//cyber/transport/shm:segment_factory", ], ) cc_test( name = "shm_dispatcher_test", size = "small", srcs = ["shm_dispatcher_test.cc"], deps = [ "//cyber:cyber_core", "//cyber/proto:unit_test_cc_proto", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/dispatcher.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/transport/dispatcher/dispatcher.h" namespace apollo { namespace cyber { namespace transport { Dispatcher::Dispatcher() : is_shutdown_(false) {} Dispatcher::~Dispatcher() { Shutdown(); } void Dispatcher::Shutdown() { is_shutdown_.store(true); ADEBUG << "Shutdown"; } bool Dispatcher::HasChannel(uint64_t channel_id) { return msg_listeners_.Has(channel_id); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/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/transport/dispatcher/dispatcher.h" #include <memory> #include <vector> #include "gtest/gtest.h" #include "cyber/common/util.h" #include "cyber/proto/unit_test.pb.h" #include "cyber/transport/common/identity.h" namespace apollo { namespace cyber { namespace transport { class DispatcherTest : public ::testing::Test { protected: DispatcherTest() : attr_num_(100) { for (int i = 0; i < attr_num_; ++i) { auto channel_name = "channel_" + std::to_string(i); RoleAttributes attr; attr.set_channel_name(channel_name); attr.set_channel_id(common::Hash(channel_name)); Identity self_id; attr.set_id(self_id.HashValue()); self_attrs_.emplace_back(attr); Identity oppo_id; attr.set_id(oppo_id.HashValue()); oppo_attrs_.emplace_back(attr); } } virtual ~DispatcherTest() { self_attrs_.clear(); oppo_attrs_.clear(); dispatcher_.Shutdown(); } virtual void SetUp() { for (int i = 0; i < attr_num_; ++i) { dispatcher_.AddListener<proto::Chatter>( self_attrs_[i], [](const std::shared_ptr<proto::Chatter>&, const MessageInfo&) {}); dispatcher_.AddListener<proto::Chatter>( self_attrs_[i], oppo_attrs_[i], [](const std::shared_ptr<proto::Chatter>&, const MessageInfo&) {}); } } virtual void TearDown() { for (int i = 0; i < attr_num_; ++i) { dispatcher_.RemoveListener<proto::Chatter>(self_attrs_[i]); dispatcher_.RemoveListener<proto::Chatter>(self_attrs_[i], oppo_attrs_[i]); } } int attr_num_; Dispatcher dispatcher_; std::vector<RoleAttributes> self_attrs_; std::vector<RoleAttributes> oppo_attrs_; }; TEST_F(DispatcherTest, shutdown) { dispatcher_.Shutdown(); } TEST_F(DispatcherTest, add_and_remove_listener) { RoleAttributes self_attr; self_attr.set_channel_name("add_listener"); self_attr.set_channel_id(common::Hash("add_listener")); Identity self_id; self_attr.set_id(self_id.HashValue()); RoleAttributes oppo_attr; oppo_attr.set_channel_name("add_listener"); oppo_attr.set_channel_id(common::Hash("add_listener")); Identity oppo_id; oppo_attr.set_id(oppo_id.HashValue()); dispatcher_.RemoveListener<proto::Chatter>(self_attr); dispatcher_.RemoveListener<proto::Chatter>(self_attr, oppo_attr); dispatcher_.AddListener<proto::Chatter>( self_attr, [](const std::shared_ptr<proto::Chatter>&, const MessageInfo&) { AINFO << "I'm listener a."; }); EXPECT_TRUE(dispatcher_.HasChannel(common::Hash("add_listener"))); dispatcher_.AddListener<proto::Chatter>( self_attr, [](const std::shared_ptr<proto::Chatter>&, const MessageInfo&) { AINFO << "I'm listener b."; }); dispatcher_.RemoveListener<proto::Chatter>(self_attr); dispatcher_.Shutdown(); dispatcher_.AddListener<proto::Chatter>( self_attr, oppo_attr, [](const std::shared_ptr<proto::Chatter>&, const MessageInfo&) { AINFO << "I'm listener c."; }); dispatcher_.AddListener<proto::Chatter>( self_attr, oppo_attr, [](const std::shared_ptr<proto::Chatter>&, const MessageInfo&) { AINFO << "I'm listener d."; }); dispatcher_.RemoveListener<proto::Chatter>(self_attr, oppo_attr); } TEST_F(DispatcherTest, has_channel) { for (int i = 0; i < attr_num_; ++i) { auto channel_name = "channel_" + std::to_string(i); EXPECT_TRUE(dispatcher_.HasChannel(common::Hash(channel_name))); } EXPECT_FALSE(dispatcher_.HasChannel(common::Hash("has_channel"))); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/intra_dispatcher.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/transport/dispatcher/intra_dispatcher.h" namespace apollo { namespace cyber { namespace transport { IntraDispatcher::IntraDispatcher() { chain_.reset(new ChannelChain()); } IntraDispatcher::~IntraDispatcher() {} } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/dispatcher/shm_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_TRANSPORT_DISPATCHER_SHM_DISPATCHER_H_ #define CYBER_TRANSPORT_DISPATCHER_SHM_DISPATCHER_H_ #include <cstring> #include <memory> #include <string> #include <thread> #include <unordered_map> #include "cyber/base/atomic_rw_lock.h" #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "cyber/message/message_traits.h" #include "cyber/transport/dispatcher/dispatcher.h" #include "cyber/transport/shm/notifier_factory.h" #include "cyber/transport/shm/segment_factory.h" namespace apollo { namespace cyber { namespace transport { class ShmDispatcher; using ShmDispatcherPtr = ShmDispatcher*; using apollo::cyber::base::AtomicRWLock; using apollo::cyber::base::ReadLockGuard; using apollo::cyber::base::WriteLockGuard; class ShmDispatcher : public Dispatcher { public: // key: channel_id using SegmentContainer = std::unordered_map<uint64_t, SegmentPtr>; virtual ~ShmDispatcher(); void Shutdown() override; template <typename MessageT> void AddListener(const RoleAttributes& self_attr, const MessageListener<MessageT>& listener); template <typename MessageT> void AddListener(const RoleAttributes& self_attr, const RoleAttributes& opposite_attr, const MessageListener<MessageT>& listener); private: void AddSegment(const RoleAttributes& self_attr); void ReadMessage(uint64_t channel_id, uint32_t block_index); void OnMessage(uint64_t channel_id, const std::shared_ptr<ReadableBlock>& rb, const MessageInfo& msg_info); void ThreadFunc(); bool Init(); uint64_t host_id_; SegmentContainer segments_; std::unordered_map<uint64_t, uint32_t> previous_indexes_; AtomicRWLock segments_lock_; std::thread thread_; NotifierPtr notifier_; DECLARE_SINGLETON(ShmDispatcher) }; template <typename MessageT> void ShmDispatcher::AddListener(const RoleAttributes& self_attr, const MessageListener<MessageT>& listener) { // FIXME: make it more clean auto listener_adapter = [listener](const std::shared_ptr<ReadableBlock>& rb, const MessageInfo& msg_info) { auto msg = std::make_shared<MessageT>(); RETURN_IF(!message::ParseFromArray( rb->buf, static_cast<int>(rb->block->msg_size()), msg.get())); listener(msg, msg_info); }; Dispatcher::AddListener<ReadableBlock>(self_attr, listener_adapter); AddSegment(self_attr); } template <typename MessageT> void ShmDispatcher::AddListener(const RoleAttributes& self_attr, const RoleAttributes& opposite_attr, const MessageListener<MessageT>& listener) { // FIXME: make it more clean auto listener_adapter = [listener](const std::shared_ptr<ReadableBlock>& rb, const MessageInfo& msg_info) { auto msg = std::make_shared<MessageT>(); RETURN_IF(!message::ParseFromArray( rb->buf, static_cast<int>(rb->block->msg_size()), msg.get())); listener(msg, msg_info); }; Dispatcher::AddListener<ReadableBlock>(self_attr, opposite_attr, listener_adapter); AddSegment(self_attr); } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_DISPATCHER_SHM_DISPATCHER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/message/message_info.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/transport/message/message_info.h" #include <cstring> #include "cyber/common/log.h" namespace apollo { namespace cyber { namespace transport { const std::size_t MessageInfo::kSize = 2 * ID_SIZE + sizeof(uint64_t); MessageInfo::MessageInfo() : sender_id_(false), spare_id_(false) {} MessageInfo::MessageInfo(const Identity& sender_id, uint64_t seq_num) : sender_id_(sender_id), seq_num_(seq_num), spare_id_(false) {} MessageInfo::MessageInfo(const Identity& sender_id, uint64_t seq_num, const Identity& spare_id) : sender_id_(sender_id), seq_num_(seq_num), spare_id_(spare_id) {} MessageInfo::MessageInfo(const MessageInfo& another) : sender_id_(another.sender_id_), channel_id_(another.channel_id_), seq_num_(another.seq_num_), spare_id_(another.spare_id_) {} MessageInfo::~MessageInfo() {} MessageInfo& MessageInfo::operator=(const MessageInfo& another) { if (this != &another) { sender_id_ = another.sender_id_; channel_id_ = another.channel_id_; seq_num_ = another.seq_num_; spare_id_ = another.spare_id_; } return *this; } bool MessageInfo::operator==(const MessageInfo& another) const { return sender_id_ == another.sender_id_ && channel_id_ == another.channel_id_ && seq_num_ == another.seq_num_ && spare_id_ == another.spare_id_; } bool MessageInfo::operator!=(const MessageInfo& another) const { return !(*this == another); } bool MessageInfo::SerializeTo(std::string* dst) const { RETURN_VAL_IF_NULL(dst, false); dst->assign(sender_id_.data(), ID_SIZE); dst->append(reinterpret_cast<const char*>(&seq_num_), sizeof(seq_num_)); dst->append(spare_id_.data(), ID_SIZE); return true; } bool MessageInfo::SerializeTo(char* dst, std::size_t len) const { if (dst == nullptr || len < kSize) { return false; } char* ptr = dst; std::memcpy(ptr, sender_id_.data(), ID_SIZE); ptr += ID_SIZE; std::memcpy(ptr, reinterpret_cast<const char*>(&seq_num_), sizeof(seq_num_)); ptr += sizeof(seq_num_); std::memcpy(ptr, spare_id_.data(), ID_SIZE); return true; } bool MessageInfo::DeserializeFrom(const std::string& src) { return DeserializeFrom(src.data(), src.size()); } bool MessageInfo::DeserializeFrom(const char* src, std::size_t len) { RETURN_VAL_IF_NULL(src, false); if (len != kSize) { AWARN << "src size mismatch, given[" << len << "] target[" << kSize << "]"; return false; } char* ptr = const_cast<char*>(src); sender_id_.set_data(ptr); ptr += ID_SIZE; std::memcpy(reinterpret_cast<char*>(&seq_num_), ptr, sizeof(seq_num_)); ptr += sizeof(seq_num_); spare_id_.set_data(ptr); return true; } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/message/message_info_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. *****************************************************************************/ /* note that the frame code of the following is Generated by script */ #include "cyber/transport/message/message_info.h" #include <memory> #include <utility> #include "gtest/gtest.h" #include "cyber/transport/common/identity.h" namespace apollo { namespace cyber { namespace transport { TEST(MessageInfoTest, test) { Identity id, id2, id3; MessageInfo msgInfo(id, 123); MessageInfo msgInfoX; msgInfo = msgInfo; msgInfoX = msgInfo; msgInfo.set_spare_id(id3); EXPECT_NE(msgInfo, msgInfoX); msgInfo.set_sender_id(id2); EXPECT_NE(msgInfo, msgInfoX); msgInfo.set_seq_num(789); EXPECT_NE(msgInfo, msgInfoX); msgInfo.set_channel_id(123); EXPECT_NE(msgInfo, msgInfoX); MessageInfo msgInfo2(msgInfo); EXPECT_EQ(msgInfo.sender_id(), msgInfo2.sender_id()); EXPECT_EQ(msgInfo.seq_num(), msgInfo2.seq_num()); EXPECT_EQ(msgInfo.spare_id(), msgInfo2.spare_id()); EXPECT_EQ(msgInfo, msgInfo2); std::string msgStr, msgStr2; EXPECT_TRUE(msgInfo.SerializeTo(&msgStr)); msgStr2.resize(msgStr.size()); EXPECT_FALSE(msgInfo.SerializeTo(const_cast<char*>(msgStr2.data()), 2)); EXPECT_TRUE( msgInfo.SerializeTo(const_cast<char*>(msgStr2.data()), msgStr2.size())); EXPECT_EQ(msgStr, msgStr2); MessageInfo msgInfo3, msgInfo4; EXPECT_TRUE(msgInfo3.DeserializeFrom(msgStr)); EXPECT_FALSE(msgInfo4.DeserializeFrom(msgStr2.data(), 2)); EXPECT_TRUE(msgInfo4.DeserializeFrom(msgStr2.data(), msgStr2.size())); EXPECT_EQ(msgInfo3, msgInfo4); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/message/message_info.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_TRANSPORT_MESSAGE_MESSAGE_INFO_H_ #define CYBER_TRANSPORT_MESSAGE_MESSAGE_INFO_H_ #include <cstddef> #include <cstdint> #include <string> #include "cyber/transport/common/identity.h" namespace apollo { namespace cyber { namespace transport { class MessageInfo { public: MessageInfo(); MessageInfo(const Identity& sender_id, uint64_t seq_num); MessageInfo(const Identity& sender_id, uint64_t seq_num, const Identity& spare_id); MessageInfo(const MessageInfo& another); virtual ~MessageInfo(); MessageInfo& operator=(const MessageInfo& another); bool operator==(const MessageInfo& another) const; bool operator!=(const MessageInfo& another) const; bool SerializeTo(std::string* dst) const; bool SerializeTo(char* dst, std::size_t len) const; bool DeserializeFrom(const std::string& src); bool DeserializeFrom(const char* src, std::size_t len); // getter and setter const Identity& sender_id() const { return sender_id_; } void set_sender_id(const Identity& sender_id) { sender_id_ = sender_id; } uint64_t channel_id() const { return channel_id_; } void set_channel_id(uint64_t channel_id) { channel_id_ = channel_id; } uint64_t seq_num() const { return seq_num_; } void set_seq_num(uint64_t seq_num) { seq_num_ = seq_num; } const Identity& spare_id() const { return spare_id_; } void set_spare_id(const Identity& spare_id) { spare_id_ = spare_id; } static const std::size_t kSize; private: Identity sender_id_; uint64_t channel_id_ = 0; uint64_t seq_num_ = 0; Identity spare_id_; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_MESSAGE_MESSAGE_INFO_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/message/message_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 <cstring> #include <memory> #include <string> #include <vector> #include "gtest/gtest.h" #include "cyber/common/global_data.h" #include "cyber/message/raw_message.h" #include "cyber/transport/message/history.h" #include "cyber/transport/message/history_attributes.h" #include "cyber/transport/message/listener_handler.h" #include "cyber/transport/message/message_info.h" namespace apollo { namespace cyber { namespace transport { using apollo::cyber::message::RawMessage; TEST(MessageInfoTest, message_info_test) { char buff[ID_SIZE]; memset(buff, 0, sizeof(buff)); Identity sender_id; std::strncpy(buff, "sender", sizeof(buff)); sender_id.set_data(buff); Identity spare_id; std::strncpy(buff, "spare", sizeof(buff)); spare_id.set_data(buff); Identity sender_id2; std::strncpy(buff, "sender2", sizeof(buff)); sender_id2.set_data(buff); Identity spare_id2; std::strncpy(buff, "spare2", sizeof(buff)); spare_id2.set_data(buff); MessageInfo info1(sender_id, 0, spare_id); std::strncpy(buff, "sender", sizeof(buff)); EXPECT_EQ(0, memcmp(buff, info1.sender_id().data(), ID_SIZE)); std::strncpy(buff, "spare", sizeof(buff)); EXPECT_EQ(0, memcmp(buff, info1.spare_id().data(), ID_SIZE)); EXPECT_EQ(0, info1.seq_num()); MessageInfo info2(info1); MessageInfo info3(sender_id, 1, spare_id); MessageInfo info4(sender_id, 1); info4.set_seq_num(2); EXPECT_EQ(2, info4.seq_num()); EXPECT_EQ(info1, info2); EXPECT_FALSE(info2 == info3); info3 = info3; info3 = info2; EXPECT_EQ(info1, info3); info1.set_sender_id(sender_id); info1.set_spare_id(spare_id); info1.set_sender_id(sender_id2); EXPECT_FALSE(info1 == info2); info1.set_sender_id(sender_id); info1.set_spare_id(spare_id2); EXPECT_FALSE(info1 == info2); std::string str; EXPECT_TRUE(info1.SerializeTo(&str)); EXPECT_NE(std::string(""), str); EXPECT_TRUE(info2.DeserializeFrom(str)); EXPECT_EQ(info1, info2); EXPECT_FALSE(info2.DeserializeFrom("error")); } TEST(HistoryTest, history_test) { char buff[ID_SIZE]; memset(buff, 0, sizeof(buff)); Identity sender_id; std::strncpy(buff, "sender", sizeof(buff)); sender_id.set_data(buff); Identity spare_id; std::strncpy(buff, "spare", sizeof(buff)); spare_id.set_data(buff); MessageInfo message_info(sender_id, 0, spare_id); HistoryAttributes attr; History<RawMessage> history(attr); MessageInfo info; auto message = std::shared_ptr<RawMessage>(new RawMessage); history.Disable(); history.Add(message, message_info); EXPECT_EQ(0, history.GetSize()); history.Enable(); history.Add(message, message_info); EXPECT_EQ(1, history.GetSize()); message_info.set_seq_num(1); int depth = 10; HistoryAttributes attr2(proto::QosHistoryPolicy::HISTORY_KEEP_LAST, depth); History<RawMessage> history2(attr2); EXPECT_EQ(depth, history2.depth()); EXPECT_EQ(1000, history2.max_depth()); history2.Enable(); for (int i = 0; i < depth + 1; i++) { message_info.set_seq_num(i); history2.Add(message, message_info); } std::vector<History<RawMessage>::CachedMessage> messages; history2.GetCachedMessage(nullptr); history2.GetCachedMessage(&messages); EXPECT_EQ(depth, messages.size()); HistoryAttributes attr3(proto::QosHistoryPolicy::HISTORY_KEEP_ALL, depth); History<RawMessage> history3(attr3); EXPECT_EQ(1000, history3.depth()); HistoryAttributes attr4(proto::QosHistoryPolicy::HISTORY_KEEP_LAST, 1024); History<RawMessage> history4(attr4); EXPECT_EQ(1000, history4.depth()); } TEST(ListenerHandlerTest, listener_handler_test) { char buff[ID_SIZE]; memset(buff, 0, sizeof(buff)); Identity sender_id; std::strncpy(buff, "sender", sizeof(buff)); sender_id.set_data(buff); Identity spare_id; std::strncpy(buff, "spare", sizeof(buff)); spare_id.set_data(buff); MessageInfo message_info(sender_id, 0, spare_id); auto message = std::shared_ptr<RawMessage>(new RawMessage); int call_count = 0; ListenerHandler<RawMessage>::Listener listener = [&call_count](const std::shared_ptr<RawMessage>& message, const MessageInfo& message_info) { ++call_count; AINFO << "Got Message from " << message_info.sender_id().data() << ", sequence_num: " << message_info.seq_num() << ", to spare: " << message_info.spare_id().data(); }; uint64_t self_id = 123; uint64_t opposite_id = 456; ListenerHandler<RawMessage> listener_handler; EXPECT_TRUE(listener_handler.IsRawMessage()); listener_handler.Run(message, message_info); EXPECT_EQ(0, call_count); listener_handler.Connect(self_id, listener); listener_handler.Connect(self_id, opposite_id, listener); listener_handler.Connect(self_id, opposite_id, listener); listener_handler.Connect(self_id, message_info.spare_id().HashValue(), listener); listener_handler.Run(message, message_info); EXPECT_EQ(1, call_count); Identity sender_id2; std::strncpy(buff, "YOU", sizeof(buff)); sender_id2.set_data(buff); message_info.set_sender_id(sender_id2); listener_handler.Run(message, message_info); EXPECT_EQ(2, call_count); listener_handler.Disconnect(789); listener_handler.Disconnect(self_id); listener_handler.Disconnect(self_id, 789); listener_handler.Disconnect(self_id, opposite_id); listener_handler.Disconnect(self_id, opposite_id); listener_handler.Run(message, message_info); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/message/history.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_TRANSPORT_MESSAGE_HISTORY_H_ #define CYBER_TRANSPORT_MESSAGE_HISTORY_H_ #include <cstdint> #include <list> #include <memory> #include <mutex> #include <vector> #include "cyber/common/global_data.h" #include "cyber/transport/message/history_attributes.h" #include "cyber/transport/message/message_info.h" namespace apollo { namespace cyber { namespace transport { template <typename MessageT> class History { public: using MessagePtr = std::shared_ptr<MessageT>; struct CachedMessage { CachedMessage(const MessagePtr& message, const MessageInfo& message_info) : msg(message), msg_info(message_info) {} MessagePtr msg; MessageInfo msg_info; }; explicit History(const HistoryAttributes& attr); virtual ~History(); void Enable() { enabled_ = true; } void Disable() { enabled_ = false; } void Add(const MessagePtr& msg, const MessageInfo& msg_info); void Clear(); void GetCachedMessage(std::vector<CachedMessage>* msgs) const; size_t GetSize() const; uint32_t depth() const { return depth_; } uint32_t max_depth() const { return max_depth_; } private: bool enabled_; uint32_t depth_; uint32_t max_depth_; std::list<CachedMessage> msgs_; mutable std::mutex msgs_mutex_; }; template <typename MessageT> History<MessageT>::History(const HistoryAttributes& attr) : enabled_(false), max_depth_(1000) { auto& global_conf = common::GlobalData::Instance()->Config(); if (global_conf.has_transport_conf() && global_conf.transport_conf().has_resource_limit()) { max_depth_ = global_conf.transport_conf().resource_limit().max_history_depth(); } if (attr.history_policy == proto::QosHistoryPolicy::HISTORY_KEEP_ALL) { depth_ = max_depth_; } else { depth_ = attr.depth; if (depth_ > max_depth_) { depth_ = max_depth_; } } } template <typename MessageT> History<MessageT>::~History() { Clear(); } template <typename MessageT> void History<MessageT>::Add(const MessagePtr& msg, const MessageInfo& msg_info) { if (!enabled_) { return; } std::lock_guard<std::mutex> lock(msgs_mutex_); msgs_.emplace_back(msg, msg_info); while (msgs_.size() > depth_) { msgs_.pop_front(); } } template <typename MessageT> void History<MessageT>::Clear() { std::lock_guard<std::mutex> lock(msgs_mutex_); msgs_.clear(); } template <typename MessageT> void History<MessageT>::GetCachedMessage( std::vector<CachedMessage>* msgs) const { if (msgs == nullptr) { return; } std::lock_guard<std::mutex> lock(msgs_mutex_); msgs->reserve(msgs_.size()); msgs->insert(msgs->begin(), msgs_.begin(), msgs_.end()); } template <typename MessageT> size_t History<MessageT>::GetSize() const { std::lock_guard<std::mutex> lock(msgs_mutex_); return msgs_.size(); } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_MESSAGE_HISTORY_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/message/history_attributes.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_TRANSPORT_MESSAGE_HISTORY_ATTRIBUTES_H_ #define CYBER_TRANSPORT_MESSAGE_HISTORY_ATTRIBUTES_H_ #include <cstdint> #include "cyber/proto/qos_profile.pb.h" namespace apollo { namespace cyber { namespace transport { struct HistoryAttributes { HistoryAttributes() : history_policy(proto::QosHistoryPolicy::HISTORY_KEEP_LAST), depth(1000) {} HistoryAttributes(const proto::QosHistoryPolicy& qos_history_policy, uint32_t history_depth) : history_policy(qos_history_policy), depth(history_depth) {} proto::QosHistoryPolicy history_policy; uint32_t depth; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_MESSAGE_HISTORY_ATTRIBUTES_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/message/listener_handler.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_TRANSPORT_MESSAGE_LISTENER_HANDLER_H_ #define CYBER_TRANSPORT_MESSAGE_LISTENER_HANDLER_H_ #include <functional> #include <memory> #include <string> #include <unordered_map> #include "cyber/base/atomic_rw_lock.h" #include "cyber/base/signal.h" #include "cyber/common/log.h" #include "cyber/message/message_traits.h" #include "cyber/message/raw_message.h" #include "cyber/transport/message/message_info.h" namespace apollo { namespace cyber { namespace transport { using apollo::cyber::base::AtomicRWLock; using apollo::cyber::base::ReadLockGuard; using apollo::cyber::base::WriteLockGuard; class ListenerHandlerBase; using ListenerHandlerBasePtr = std::shared_ptr<ListenerHandlerBase>; class ListenerHandlerBase { public: ListenerHandlerBase() {} virtual ~ListenerHandlerBase() {} virtual void Disconnect(uint64_t self_id) = 0; virtual void Disconnect(uint64_t self_id, uint64_t oppo_id) = 0; inline bool IsRawMessage() const { return is_raw_message_; } virtual void RunFromString(const std::string& str, const MessageInfo& msg_info) = 0; protected: bool is_raw_message_ = false; }; template <typename MessageT> class ListenerHandler : public ListenerHandlerBase { public: using Message = std::shared_ptr<MessageT>; using MessageSignal = base::Signal<const Message&, const MessageInfo&>; using Listener = std::function<void(const Message&, const MessageInfo&)>; using MessageConnection = base::Connection<const Message&, const MessageInfo&>; using ConnectionMap = std::unordered_map<uint64_t, MessageConnection>; ListenerHandler() {} virtual ~ListenerHandler() {} void Connect(uint64_t self_id, const Listener& listener); void Connect(uint64_t self_id, uint64_t oppo_id, const Listener& listener); void Disconnect(uint64_t self_id) override; void Disconnect(uint64_t self_id, uint64_t oppo_id) override; void Run(const Message& msg, const MessageInfo& msg_info); void RunFromString(const std::string& str, const MessageInfo& msg_info) override; private: using SignalPtr = std::shared_ptr<MessageSignal>; using MessageSignalMap = std::unordered_map<uint64_t, SignalPtr>; // used for self_id MessageSignal signal_; ConnectionMap signal_conns_; // key: self_id // used for self_id and oppo_id MessageSignalMap signals_; // key: oppo_id // key: oppo_id std::unordered_map<uint64_t, ConnectionMap> signals_conns_; base::AtomicRWLock rw_lock_; }; template <> inline ListenerHandler<message::RawMessage>::ListenerHandler() { is_raw_message_ = true; } template <typename MessageT> void ListenerHandler<MessageT>::Connect(uint64_t self_id, const Listener& listener) { auto connection = signal_.Connect(listener); if (!connection.IsConnected()) { return; } WriteLockGuard<AtomicRWLock> lock(rw_lock_); signal_conns_[self_id] = connection; } template <typename MessageT> void ListenerHandler<MessageT>::Connect(uint64_t self_id, uint64_t oppo_id, const Listener& listener) { WriteLockGuard<AtomicRWLock> lock(rw_lock_); if (signals_.find(oppo_id) == signals_.end()) { signals_[oppo_id] = std::make_shared<MessageSignal>(); } auto connection = signals_[oppo_id]->Connect(listener); if (!connection.IsConnected()) { AWARN << oppo_id << " " << self_id << " connect failed!"; return; } if (signals_conns_.find(oppo_id) == signals_conns_.end()) { signals_conns_[oppo_id] = ConnectionMap(); } signals_conns_[oppo_id][self_id] = connection; } template <typename MessageT> void ListenerHandler<MessageT>::Disconnect(uint64_t self_id) { WriteLockGuard<AtomicRWLock> lock(rw_lock_); if (signal_conns_.find(self_id) == signal_conns_.end()) { return; } signal_conns_[self_id].Disconnect(); signal_conns_.erase(self_id); } template <typename MessageT> void ListenerHandler<MessageT>::Disconnect(uint64_t self_id, uint64_t oppo_id) { WriteLockGuard<AtomicRWLock> lock(rw_lock_); if (signals_conns_.find(oppo_id) == signals_conns_.end()) { return; } if (signals_conns_[oppo_id].find(self_id) == signals_conns_[oppo_id].end()) { return; } signals_conns_[oppo_id][self_id].Disconnect(); signals_conns_[oppo_id].erase(self_id); } template <typename MessageT> void ListenerHandler<MessageT>::Run(const Message& msg, const MessageInfo& msg_info) { signal_(msg, msg_info); uint64_t oppo_id = msg_info.sender_id().HashValue(); ReadLockGuard<AtomicRWLock> lock(rw_lock_); if (signals_.find(oppo_id) == signals_.end()) { return; } (*signals_[oppo_id])(msg, msg_info); } template <typename MessageT> void ListenerHandler<MessageT>::RunFromString(const std::string& str, const MessageInfo& msg_info) { auto msg = std::make_shared<MessageT>(); if (message::ParseFromHC(str.data(), static_cast<int>(str.size()), msg.get())) { Run(msg, msg_info); } else { AWARN << "Failed to parse message. Content: " << str; } } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_MESSAGE_LISTENER_HANDLER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/message/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_transport_message_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "history_attributes", hdrs = ["history_attributes.h"], deps = [ "//cyber/proto:qos_profile_cc_proto", ], ) cc_library( name = "history", hdrs = ["history.h"], deps = [ ":history_attributes", ], ) cc_library( name = "listener_handler", hdrs = ["listener_handler.h"], deps = [ ":message_info", "//cyber/base:signal", "//cyber/message:message_traits", "//cyber/message:raw_message", ], ) cc_library( name = "message_info", srcs = ["message_info.cc"], hdrs = ["message_info.h"], deps = [ "//cyber/common:log", "//cyber/transport/common:identity", ], ) cc_test( name = "message_info_test", size = "small", srcs = ["message_info_test.cc"], deps = [ "//cyber:cyber_core", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_test( name = "message_test", size = "small", srcs = ["message_test.cc"], deps = [ "//cyber:cyber_core", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cpplint()
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/rtps/underlay_message_type.cc
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /*! * @file UnderlayMessageTypes.cpp * This header file contains the implementation of the serialization functions. * * This file was generated by the tool fastcdrgen. */ #include "cyber/transport/rtps/underlay_message_type.h" #include "fastcdr/Cdr.h" #include "fastcdr/FastBuffer.h" #include "cyber/common/log.h" namespace apollo { namespace cyber { namespace transport { UnderlayMessageType::UnderlayMessageType() { setName("UnderlayMessage"); m_typeSize = (uint32_t)UnderlayMessage::getMaxCdrSerializedSize() + 4 /*encapsulation*/; m_isGetKeyDefined = UnderlayMessage::isKeyDefined(); m_keyBuffer = (unsigned char*)malloc(UnderlayMessage::getKeyMaxCdrSerializedSize() > 16 ? UnderlayMessage::getKeyMaxCdrSerializedSize() : 16); } UnderlayMessageType::~UnderlayMessageType() { if (m_keyBuffer != nullptr) { free(m_keyBuffer); } } bool UnderlayMessageType::serialize(void* data, SerializedPayload_t* payload) { UnderlayMessage* p_type = reinterpret_cast<UnderlayMessage*>(data); eprosima::fastcdr::FastBuffer fastbuffer( reinterpret_cast<char*>(payload->data), payload->max_size); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser( fastbuffer, eprosima::fastcdr::Cdr::DEFAULT_ENDIAN, eprosima::fastcdr::Cdr::DDS_CDR); // Object that serializes the data. payload->encapsulation = ser.endianness() == eprosima::fastcdr::Cdr::BIG_ENDIANNESS ? CDR_BE : CDR_LE; // Serialize encapsulation ser.serialize_encapsulation(); p_type->serialize(ser); // Serialize the object: payload->length = (uint32_t)ser.getSerializedDataLength(); // Get the serialized length return true; } bool UnderlayMessageType::deserialize(SerializedPayload_t* payload, void* data) { UnderlayMessage* p_type = reinterpret_cast<UnderlayMessage*>( data); // Convert DATA to pointer of your type eprosima::fastcdr::FastBuffer fastbuffer( reinterpret_cast<char*>(payload->data), payload->length); // Object that manages the raw buffer. eprosima::fastcdr::Cdr deser( fastbuffer, eprosima::fastcdr::Cdr::DEFAULT_ENDIAN, eprosima::fastcdr::Cdr::DDS_CDR); // Object that deserializes the data. // Deserialize encapsulation. deser.read_encapsulation(); payload->encapsulation = deser.endianness() == eprosima::fastcdr::Cdr::BIG_ENDIANNESS ? CDR_BE : CDR_LE; p_type->deserialize(deser); // Deserialize the object: return true; } std::function<uint32_t()> UnderlayMessageType::getSerializedSizeProvider( void* data) { return [data]() -> uint32_t { return (uint32_t)type::getCdrSerializedSize( *static_cast<UnderlayMessage*>(data)) + 4 /*encapsulation*/; }; } void* UnderlayMessageType::createData() { return reinterpret_cast<void*>(new UnderlayMessage()); } void UnderlayMessageType::deleteData(void* data) { delete (reinterpret_cast<UnderlayMessage*>(data)); } bool UnderlayMessageType::getKey(void* data, InstanceHandle_t* handle) { RETURN_VAL_IF((!m_isGetKeyDefined), false); UnderlayMessage* p_type = reinterpret_cast<UnderlayMessage*>(data); eprosima::fastcdr::FastBuffer fastbuffer( reinterpret_cast<char*>(m_keyBuffer), UnderlayMessage::getKeyMaxCdrSerializedSize()); // Object that manages // the raw buffer. eprosima::fastcdr::Cdr ser( fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that // serializes the // data. p_type->serializeKey(ser); if (UnderlayMessage::getKeyMaxCdrSerializedSize() > 16) { m_md5.init(); m_md5.update(m_keyBuffer, (unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); for (uint8_t i = 0; i < 16; ++i) { handle->value[i] = m_md5.digest[i]; } } else { for (uint8_t i = 0; i < 16; ++i) { handle->value[i] = m_keyBuffer[i]; } } return true; } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/rtps/participant.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_TRANSPORT_RTPS_PARTICIPANT_H_ #define CYBER_TRANSPORT_RTPS_PARTICIPANT_H_ #include <atomic> #include <memory> #include <mutex> #include <string> #include "cyber/transport/rtps/underlay_message_type.h" #include "fastrtps/Domain.h" #include "fastrtps/attributes/ParticipantAttributes.h" #include "fastrtps/participant/Participant.h" #include "fastrtps/participant/ParticipantListener.h" #include "fastrtps/rtps/common/Locator.h" namespace apollo { namespace cyber { namespace transport { class Participant; using ParticipantPtr = std::shared_ptr<Participant>; class Participant { public: Participant(const std::string& name, int send_port, eprosima::fastrtps::ParticipantListener* listener = nullptr); virtual ~Participant(); void Shutdown(); eprosima::fastrtps::Participant* fastrtps_participant(); bool is_shutdown() const { return shutdown_.load(); } private: void CreateFastRtpsParticipant( const std::string& name, int send_port, eprosima::fastrtps::ParticipantListener* listener); std::atomic<bool> shutdown_; std::string name_; int send_port_; eprosima::fastrtps::ParticipantListener* listener_; UnderlayMessageType type_; eprosima::fastrtps::Participant* fastrtps_participant_; std::mutex mutex_; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_RTPS_PARTICIPANT_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/rtps/participant.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/transport/rtps/participant.h" #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/proto/transport_conf.pb.h" namespace apollo { namespace cyber { namespace transport { Participant::Participant(const std::string& name, int send_port, eprosima::fastrtps::ParticipantListener* listener) : shutdown_(false), name_(name), send_port_(send_port), listener_(listener), fastrtps_participant_(nullptr) {} Participant::~Participant() {} void Participant::Shutdown() { if (shutdown_.exchange(true)) { return; } std::lock_guard<std::mutex> lk(mutex_); if (fastrtps_participant_ != nullptr) { eprosima::fastrtps::Domain::removeParticipant(fastrtps_participant_); fastrtps_participant_ = nullptr; listener_ = nullptr; } } eprosima::fastrtps::Participant* Participant::fastrtps_participant() { if (shutdown_.load()) { return nullptr; } std::lock_guard<std::mutex> lk(mutex_); if (fastrtps_participant_ != nullptr) { return fastrtps_participant_; } CreateFastRtpsParticipant(name_, send_port_, listener_); return fastrtps_participant_; } void Participant::CreateFastRtpsParticipant( const std::string& name, int send_port, eprosima::fastrtps::ParticipantListener* listener) { uint32_t domain_id = 80; const char* val = ::getenv("CYBER_DOMAIN_ID"); if (val != nullptr) { try { domain_id = std::stoi(val); } catch (const std::exception& e) { AERROR << "convert domain_id error " << e.what(); return; } } auto part_attr_conf = std::make_shared<proto::RtpsParticipantAttr>(); auto& global_conf = common::GlobalData::Instance()->Config(); if (global_conf.has_transport_conf() && global_conf.transport_conf().has_participant_attr()) { part_attr_conf->CopyFrom(global_conf.transport_conf().participant_attr()); } eprosima::fastrtps::ParticipantAttributes attr; attr.rtps.defaultSendPort = send_port; attr.rtps.port.domainIDGain = static_cast<uint16_t>(part_attr_conf->domain_id_gain()); attr.rtps.port.portBase = static_cast<uint16_t>(part_attr_conf->port_base()); attr.rtps.use_IP6_to_send = false; attr.rtps.builtin.use_SIMPLE_RTPSParticipantDiscoveryProtocol = true; attr.rtps.builtin.use_SIMPLE_EndpointDiscoveryProtocol = true; attr.rtps.builtin.m_simpleEDP.use_PublicationReaderANDSubscriptionWriter = true; attr.rtps.builtin.m_simpleEDP.use_PublicationWriterANDSubscriptionReader = true; attr.rtps.builtin.domainId = domain_id; /** * The user should set the lease_duration and the announcement_period with * values that differ in at least 30%. Values too close to each other may * cause the failure of the writer liveliness assertion in networks with high * latency or with lots of communication errors. */ attr.rtps.builtin.leaseDuration.seconds = part_attr_conf->lease_duration(); attr.rtps.builtin.leaseDuration_announcementperiod.seconds = part_attr_conf->announcement_period(); attr.rtps.setName(name.c_str()); std::string ip_env("127.0.0.1"); const char* ip_val = ::getenv("CYBER_IP"); if (ip_val != nullptr) { ip_env = ip_val; if (ip_env.empty()) { AERROR << "invalid CYBER_IP (an empty string)"; return; } } ADEBUG << "cyber ip: " << ip_env; eprosima::fastrtps::rtps::Locator_t locator; locator.port = 0; RETURN_IF(!locator.set_IP4_address(ip_env)); locator.kind = LOCATOR_KIND_UDPv4; attr.rtps.defaultUnicastLocatorList.push_back(locator); attr.rtps.defaultOutLocatorList.push_back(locator); attr.rtps.builtin.metatrafficUnicastLocatorList.push_back(locator); locator.set_IP4_address(239, 255, 0, 1); attr.rtps.builtin.metatrafficMulticastLocatorList.push_back(locator); fastrtps_participant_ = eprosima::fastrtps::Domain::createParticipant(attr, listener); RETURN_IF_NULL(fastrtps_participant_); eprosima::fastrtps::Domain::registerType(fastrtps_participant_, &type_); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/rtps/underlay_message.cc
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /*! * @file UnderlayMessage.cpp * This source file contains the definition of the described types in the IDL *file. * * This file was generated by the tool gen. */ #include "cyber/transport/rtps/underlay_message.h" #include "fastcdr/exceptions/BadParamException.h" namespace apollo { namespace cyber { namespace transport { UnderlayMessage::UnderlayMessage() { m_timestamp = 0; m_seq = 0; } UnderlayMessage::~UnderlayMessage() {} UnderlayMessage::UnderlayMessage(const UnderlayMessage& x) { m_timestamp = x.m_timestamp; m_seq = x.m_seq; m_data = x.m_data; m_datatype = x.m_datatype; } UnderlayMessage::UnderlayMessage(UnderlayMessage&& x) { m_timestamp = x.m_timestamp; m_seq = x.m_seq; m_data = std::move(x.m_data); m_datatype = std::move(x.m_datatype); } UnderlayMessage& UnderlayMessage::operator=(const UnderlayMessage& x) { m_timestamp = x.m_timestamp; m_seq = x.m_seq; m_data = x.m_data; m_datatype = x.m_datatype; return *this; } UnderlayMessage& UnderlayMessage::operator=(UnderlayMessage&& x) { m_timestamp = x.m_timestamp; m_seq = x.m_seq; m_data = std::move(x.m_data); m_datatype = std::move(x.m_datatype); return *this; } size_t UnderlayMessage::getMaxCdrSerializedSize(size_t current_alignment) { size_t initial_alignment = current_alignment; current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4) + 255 + 1; current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4) + 255 + 1; return current_alignment - initial_alignment; } size_t UnderlayMessage::getCdrSerializedSize(const UnderlayMessage& data, size_t current_alignment) { size_t initial_alignment = current_alignment; current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4); current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4) + data.data().size() + 1; current_alignment += 4 + eprosima::fastcdr::Cdr::alignment(current_alignment, 4) + data.datatype().size() + 1; return current_alignment - initial_alignment; } void UnderlayMessage::serialize(eprosima::fastcdr::Cdr& scdr) const { scdr << m_timestamp; scdr << m_seq; scdr << m_data; scdr << m_datatype; } void UnderlayMessage::deserialize(eprosima::fastcdr::Cdr& dcdr) { dcdr >> m_timestamp; dcdr >> m_seq; dcdr >> m_data; dcdr >> m_datatype; } size_t UnderlayMessage::getKeyMaxCdrSerializedSize(size_t current_alignment) { size_t current_align = current_alignment; return current_align; } bool UnderlayMessage::isKeyDefined() { return false; } void UnderlayMessage::serializeKey(eprosima::fastcdr::Cdr& scdr) const { (void)scdr; } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/rtps/underlay_message_type.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_TRANSPORT_RTPS_UNDERLAY_MESSAGE_TYPE_H_ #define CYBER_TRANSPORT_RTPS_UNDERLAY_MESSAGE_TYPE_H_ #include "cyber/transport/rtps/underlay_message.h" #include "fastrtps/TopicDataType.h" namespace apollo { namespace cyber { namespace transport { /*! * @brief This class represents the TopicDataType of the type UnderlayMessage * defined by the user in the IDL file. * @ingroup UNDERLAYMESSAGE */ class UnderlayMessageType : public eprosima::fastrtps::TopicDataType { public: using type = UnderlayMessage; UnderlayMessageType(); virtual ~UnderlayMessageType(); bool serialize(void* data, SerializedPayload_t* payload); bool deserialize(SerializedPayload_t* payload, void* data); std::function<uint32_t()> getSerializedSizeProvider(void* data); bool getKey(void* data, InstanceHandle_t* ihandle); void* createData(); void deleteData(void* data); MD5 m_md5; unsigned char* m_keyBuffer; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_RTPS_UNDERLAY_MESSAGE_TYPE_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/rtps/underlay_message.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_TRANSPORT_RTPS_UNDERLAY_MESSAGE_H_ #define CYBER_TRANSPORT_RTPS_UNDERLAY_MESSAGE_H_ #include <cstdint> #include <array> #include <string> #include <utility> #include <vector> #include "fastcdr/Cdr.h" namespace apollo { namespace cyber { namespace transport { /*! * @brief This class represents the structure UnderlayMessage defined by the * user in the IDL file. * @ingroup UnderlayMessage */ class UnderlayMessage { public: /*! * @brief Default constructor. */ UnderlayMessage(); /*! * @brief Default destructor. */ ~UnderlayMessage(); /*! * @brief Copy constructor. * @param x Reference to the object UnderlayMessage that will be copied. */ UnderlayMessage(const UnderlayMessage& x); /*! * @brief Move constructor. * @param x Reference to the object UnderlayMessage that will be copied. */ UnderlayMessage(UnderlayMessage&& x); /*! * @brief Copy assignment. * @param x Reference to the object UnderlayMessage that will be copied. */ UnderlayMessage& operator=(const UnderlayMessage& x); /*! * @brief Move assignment. * @param x Reference to the object UnderlayMessage that will be copied. */ UnderlayMessage& operator=(UnderlayMessage&& x); /*! * @brief This function sets a value in member timestamp * @param _timestamp New value for member timestamp */ inline void timestamp(int32_t _timestamp) { m_timestamp = _timestamp; } /*! * @brief This function returns the value of member timestamp * @return Value of member timestamp */ inline int32_t timestamp() const { return m_timestamp; } /*! * @brief This function returns a reference to member timestamp * @return Reference to member timestamp */ inline int32_t& timestamp() { return m_timestamp; } /*! * @brief This function sets a value in member seq * @param _seq New value for member seq */ inline void seq(int32_t _seq) { m_seq = _seq; } /*! * @brief This function returns the value of member seq * @return Value of member seq */ inline int32_t seq() const { return m_seq; } /*! * @brief This function returns a reference to member seq * @return Reference to member seq */ inline int32_t& seq() { return m_seq; } /*! * @brief This function copies the value in member data * @param _data New value to be copied in member data */ inline void data(const std::string& _data) { m_data = _data; } /*! * @brief This function moves the value in member data * @param _data New value to be moved in member data */ inline void data(std::string&& _data) { m_data = std::move(_data); } /*! * @brief This function returns a constant reference to member data * @return Constant reference to member data */ inline const std::string& data() const { return m_data; } /*! * @brief This function returns a reference to member data * @return Reference to member data */ inline std::string& data() { return m_data; } /*! * @brief This function copies the value in member datatype * @param _datatype New value to be copied in member datatype */ inline void datatype(const std::string& _datatype) { m_datatype = _datatype; } /*! * @brief This function moves the value in member datatype * @param _datatype New value to be moved in member datatype */ inline void datatype(std::string&& _datatype) { m_datatype = std::move(_datatype); } /*! * @brief This function returns a constant reference to member datatype * @return Constant reference to member datatype */ inline const std::string& datatype() const { return m_datatype; } /*! * @brief This function returns a reference to member datatype * @return Reference to member datatype */ inline std::string& datatype() { return m_datatype; } /*! * @brief This function returns the maximum serialized size of an object * depending on the buffer alignment. * @param current_alignment Buffer alignment. * @return Maximum serialized size. */ static size_t getMaxCdrSerializedSize(size_t current_alignment = 0); /*! * @brief This function returns the serialized size of a data depending on the * buffer alignment. * @param data Data which is calculated its serialized size. * @param current_alignment Buffer alignment. * @return Serialized size. */ static size_t getCdrSerializedSize(const UnderlayMessage& data, size_t current_alignment = 0); /*! * @brief This function serializes an object using CDR serialization. * @param cdr CDR serialization object. */ void serialize(eprosima::fastcdr::Cdr& cdr) const; // NOLINT /*! * @brief This function deserializes an object using CDR serialization. * @param cdr CDR serialization object. */ void deserialize(eprosima::fastcdr::Cdr& cdr); // NOLINT /*! * @brief This function returns the maximum serialized size of the Key of an * object * depending on the buffer alignment. * @param current_alignment Buffer alignment. * @return Maximum serialized size. */ static size_t getKeyMaxCdrSerializedSize(size_t current_alignment = 0); /*! * @brief This function tells you if the Key has been defined for this type */ static bool isKeyDefined(); /*! * @brief This function serializes the key members of an object using CDR * serialization. * @param cdr CDR serialization object. */ void serializeKey(eprosima::fastcdr::Cdr& cdr) const; // NOLINT private: int32_t m_timestamp; int32_t m_seq; std::string m_data; std::string m_datatype; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_RTPS_UNDERLAY_MESSAGE_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/rtps/sub_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_TRANSPORT_RTPS_SUB_LISTENER_H_ #define CYBER_TRANSPORT_RTPS_SUB_LISTENER_H_ #include <functional> #include <iostream> #include <memory> #include <mutex> #include <string> #include "cyber/transport/message/message_info.h" #include "cyber/transport/rtps/underlay_message.h" #include "cyber/transport/rtps/underlay_message_type.h" #include "fastrtps/Domain.h" #include "fastrtps/subscriber/SampleInfo.h" #include "fastrtps/subscriber/Subscriber.h" #include "fastrtps/subscriber/SubscriberListener.h" namespace apollo { namespace cyber { namespace transport { class SubListener; using SubListenerPtr = std::shared_ptr<SubListener>; class SubListener : public eprosima::fastrtps::SubscriberListener { public: using NewMsgCallback = std::function<void( uint64_t channel_id, const std::shared_ptr<std::string>& msg_str, const MessageInfo& msg_info)>; explicit SubListener(const NewMsgCallback& callback); virtual ~SubListener(); void onNewDataMessage(eprosima::fastrtps::Subscriber* sub); void onSubscriptionMatched(eprosima::fastrtps::Subscriber* sub, eprosima::fastrtps::MatchingInfo& info); // NOLINT private: NewMsgCallback callback_; MessageInfo msg_info_; std::mutex mutex_; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_RTPS_SUB_LISTENER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/rtps/attributes_filler.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_TRANSPORT_RTPS_ATTRIBUTES_FILLER_H_ #define CYBER_TRANSPORT_RTPS_ATTRIBUTES_FILLER_H_ #include <string> #include "cyber/proto/qos_profile.pb.h" #include "fastrtps/attributes/PublisherAttributes.h" #include "fastrtps/attributes/SubscriberAttributes.h" namespace apollo { namespace cyber { namespace transport { using proto::QosDurabilityPolicy; using proto::QosHistoryPolicy; using proto::QosProfile; using proto::QosReliabilityPolicy; class AttributesFiller { public: AttributesFiller(); virtual ~AttributesFiller(); static bool FillInPubAttr(const std::string& channel_name, const QosProfile& qos, eprosima::fastrtps::PublisherAttributes* pub_attr); static bool FillInSubAttr(const std::string& channel_name, const QosProfile& qos, eprosima::fastrtps::SubscriberAttributes* sub_attr); }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_RTPS_ATTRIBUTES_FILLER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/rtps/rtps_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 <string> #include <utility> #include "fastcdr/Cdr.h" #include "fastcdr/exceptions/BadParamException.h" #include "gtest/gtest.h" #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/transport/qos/qos_profile_conf.h" #include "cyber/transport/rtps/attributes_filler.h" #include "cyber/transport/rtps/participant.h" #include "cyber/transport/rtps/underlay_message.h" #include "cyber/transport/rtps/underlay_message_type.h" namespace apollo { namespace cyber { namespace transport { TEST(AttributesFillerTest, fill_in_pub_attr_test) { QosProfile qos; AttributesFiller filler; eprosima::fastrtps::PublisherAttributes attrs; qos.set_history(QosHistoryPolicy::HISTORY_KEEP_LAST); qos.set_durability(QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); qos.set_reliability(QosReliabilityPolicy::RELIABILITY_BEST_EFFORT); qos.set_mps(32); filler.FillInPubAttr("channel", qos, &attrs); EXPECT_EQ(eprosima::fastrtps::KEEP_LAST_HISTORY_QOS, attrs.topic.historyQos.kind); EXPECT_EQ(eprosima::fastrtps::TRANSIENT_LOCAL_DURABILITY_QOS, attrs.qos.m_durability.kind); EXPECT_EQ(eprosima::fastrtps::BEST_EFFORT_RELIABILITY_QOS, attrs.qos.m_reliability.kind); AINFO << "heartbeat period: " << attrs.times.heartbeatPeriod.seconds << ", " << attrs.times.heartbeatPeriod.fraction; qos.set_depth(1024); attrs.topic.historyQos.depth = 512; filler.FillInPubAttr("channel", qos, &attrs); AINFO << qos.depth() << ", " << QosProfileConf::QOS_HISTORY_DEPTH_SYSTEM_DEFAULT << ", " << attrs.topic.historyQos.depth; EXPECT_EQ(qos.depth(), attrs.topic.historyQos.depth); qos.set_history(QosHistoryPolicy::HISTORY_KEEP_ALL); qos.set_durability(QosDurabilityPolicy::DURABILITY_VOLATILE); qos.set_reliability(QosReliabilityPolicy::RELIABILITY_RELIABLE); qos.set_mps(65); filler.FillInPubAttr("channel", qos, &attrs); EXPECT_EQ(eprosima::fastrtps::KEEP_ALL_HISTORY_QOS, attrs.topic.historyQos.kind); EXPECT_EQ(eprosima::fastrtps::VOLATILE_DURABILITY_QOS, attrs.qos.m_durability.kind); EXPECT_EQ(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS, attrs.qos.m_reliability.kind); AINFO << "heartbeat period: " << attrs.times.heartbeatPeriod.seconds << ", " << attrs.times.heartbeatPeriod.fraction; qos.set_history(QosHistoryPolicy::HISTORY_SYSTEM_DEFAULT); qos.set_durability(QosDurabilityPolicy::DURABILITY_SYSTEM_DEFAULT); qos.set_reliability(QosReliabilityPolicy::RELIABILITY_SYSTEM_DEFAULT); qos.set_mps(1025); filler.FillInPubAttr("channel", qos, &attrs); EXPECT_EQ(eprosima::fastrtps::KEEP_ALL_HISTORY_QOS, attrs.topic.historyQos.kind); EXPECT_EQ(eprosima::fastrtps::VOLATILE_DURABILITY_QOS, attrs.qos.m_durability.kind); EXPECT_EQ(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS, attrs.qos.m_reliability.kind); AINFO << "heartbeat period: " << attrs.times.heartbeatPeriod.seconds << ", " << attrs.times.heartbeatPeriod.fraction; qos.set_mps(0); filler.FillInPubAttr("channel", qos, &attrs); AINFO << "heartbeat period: " << attrs.times.heartbeatPeriod.seconds << ", " << attrs.times.heartbeatPeriod.fraction; } TEST(AttributesFillerTest, fill_in_sub_attr_test) { QosProfile qos; AttributesFiller filler; eprosima::fastrtps::SubscriberAttributes attrs; qos.set_history(QosHistoryPolicy::HISTORY_KEEP_LAST); qos.set_durability(QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL); qos.set_reliability(QosReliabilityPolicy::RELIABILITY_BEST_EFFORT); qos.set_mps(32); filler.FillInSubAttr("channel", qos, &attrs); EXPECT_EQ(eprosima::fastrtps::KEEP_LAST_HISTORY_QOS, attrs.topic.historyQos.kind); EXPECT_EQ(eprosima::fastrtps::TRANSIENT_LOCAL_DURABILITY_QOS, attrs.qos.m_durability.kind); EXPECT_EQ(eprosima::fastrtps::BEST_EFFORT_RELIABILITY_QOS, attrs.qos.m_reliability.kind); qos.set_depth(1024); attrs.topic.historyQos.depth = 512; filler.FillInSubAttr("channel", qos, &attrs); EXPECT_EQ(qos.depth(), attrs.topic.historyQos.depth); qos.set_history(QosHistoryPolicy::HISTORY_KEEP_ALL); qos.set_durability(QosDurabilityPolicy::DURABILITY_VOLATILE); qos.set_reliability(QosReliabilityPolicy::RELIABILITY_RELIABLE); qos.set_mps(65); filler.FillInSubAttr("channel", qos, &attrs); EXPECT_EQ(eprosima::fastrtps::KEEP_ALL_HISTORY_QOS, attrs.topic.historyQos.kind); EXPECT_EQ(eprosima::fastrtps::VOLATILE_DURABILITY_QOS, attrs.qos.m_durability.kind); EXPECT_EQ(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS, attrs.qos.m_reliability.kind); qos.set_history(QosHistoryPolicy::HISTORY_SYSTEM_DEFAULT); qos.set_durability(QosDurabilityPolicy::DURABILITY_SYSTEM_DEFAULT); qos.set_reliability(QosReliabilityPolicy::RELIABILITY_SYSTEM_DEFAULT); qos.set_mps(1025); filler.FillInSubAttr("channel", qos, &attrs); EXPECT_EQ(eprosima::fastrtps::KEEP_ALL_HISTORY_QOS, attrs.topic.historyQos.kind); EXPECT_EQ(eprosima::fastrtps::VOLATILE_DURABILITY_QOS, attrs.qos.m_durability.kind); EXPECT_EQ(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS, attrs.qos.m_reliability.kind); } TEST(ParticipantTest, participant_test) { eprosima::fastrtps::ParticipantListener listener; eprosima::fastrtps::ParticipantListener listener1; } TEST(UnderlayMessageTest, underlay_message_test) { UnderlayMessage message; message.timestamp(1024); int32_t& t = message.timestamp(); t = 256; EXPECT_EQ(256, message.timestamp()); message.seq(1024); int32_t& seq = message.seq(); seq = 256; EXPECT_EQ(256, message.seq()); message.data("data"); std::string& data = message.data(); data = "data string"; EXPECT_EQ(data, message.data()); message.data(std::forward<std::string>("data forward")); EXPECT_EQ("data forward", message.data()); message.datatype("datatype"); std::string& datatype = message.datatype(); datatype = "datatype string"; EXPECT_EQ(datatype, message.datatype()); message.datatype("datatype assign"); EXPECT_EQ("datatype assign", message.datatype()); message.datatype(std::forward<std::string>("datatype forward")); EXPECT_EQ("datatype forward", message.datatype()); const UnderlayMessage const_message(message); std::string data1 = const_message.data(); std::string datatype1 = const_message.datatype(); EXPECT_EQ(256, const_message.timestamp()); EXPECT_EQ(256, const_message.seq()); EXPECT_EQ("data forward", const_message.data()); EXPECT_EQ("datatype forward", const_message.datatype()); UnderlayMessage message2; message2 = message; EXPECT_EQ(256, message2.timestamp()); EXPECT_EQ(256, message2.seq()); EXPECT_EQ("data forward", message2.data()); EXPECT_EQ("datatype forward", message2.datatype()); UnderlayMessage message3; message3 = std::forward<UnderlayMessage>(message2); EXPECT_EQ(256, message3.timestamp()); EXPECT_EQ(256, message3.seq()); EXPECT_EQ("data forward", message3.data()); EXPECT_EQ("datatype forward", message3.datatype()); UnderlayMessage message4(message3); EXPECT_EQ(256, message4.timestamp()); EXPECT_EQ(256, message4.seq()); EXPECT_EQ("data forward", message4.data()); EXPECT_EQ("datatype forward", message4.datatype()); UnderlayMessage message5(std::forward<UnderlayMessage>(message4)); EXPECT_EQ(256, message5.timestamp()); EXPECT_EQ(256, message5.seq()); EXPECT_EQ("data forward", message5.data()); EXPECT_EQ("datatype forward", message5.datatype()); EXPECT_EQ("", message4.data()); EXPECT_EQ("", message4.datatype()); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/rtps/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_transport_rtps_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "attributes_filler", srcs = ["attributes_filler.cc"], hdrs = ["attributes_filler.h"], deps = [ "//cyber/common:log", "//cyber/transport/qos", "@fastrtps", ], ) cc_library( name = "underlay_message", srcs = ["underlay_message.cc"], hdrs = ["underlay_message.h"], deps = [ "//cyber/common:log", "@fastrtps", ], ) cc_library( name = "participant", srcs = ["participant.cc"], hdrs = ["participant.h"], deps = [ ":underlay_message", ":underlay_message_type", "//cyber/common:global_data", ], ) cc_library( name = "sub_listener", srcs = ["sub_listener.cc"], hdrs = ["sub_listener.h"], deps = [ ":underlay_message", ":underlay_message_type", "//cyber/transport/message:message_info", ], ) cc_library( name = "underlay_message_type", srcs = ["underlay_message_type.cc"], hdrs = ["underlay_message_type.h"], deps = [ ":underlay_message", "@fastrtps", ], ) cc_test( name = "rtps_test", size = "small", srcs = ["rtps_test.cc"], deps = [ "//cyber:cyber_core", "@com_google_googletest//:gtest_main", "@fastrtps", ], ) cpplint()
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/rtps/sub_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/transport/rtps/sub_listener.h" #include "cyber/common/log.h" #include "cyber/common/util.h" namespace apollo { namespace cyber { namespace transport { SubListener::SubListener(const NewMsgCallback& callback) : callback_(callback) {} SubListener::~SubListener() {} void SubListener::onNewDataMessage(eprosima::fastrtps::Subscriber* sub) { RETURN_IF_NULL(sub); RETURN_IF_NULL(callback_); std::lock_guard<std::mutex> lock(mutex_); // fetch channel name auto channel_id = common::Hash(sub->getAttributes().topic.getTopicName()); eprosima::fastrtps::SampleInfo_t m_info; UnderlayMessage m; RETURN_IF(!sub->takeNextData(reinterpret_cast<void*>(&m), &m_info)); RETURN_IF(m_info.sampleKind != eprosima::fastrtps::ALIVE); // fetch MessageInfo char* ptr = reinterpret_cast<char*>(&m_info.related_sample_identity.writer_guid()); Identity sender_id(false); sender_id.set_data(ptr); msg_info_.set_sender_id(sender_id); Identity spare_id(false); spare_id.set_data(ptr + ID_SIZE); msg_info_.set_spare_id(spare_id); uint64_t seq_num = ((int64_t)m_info.related_sample_identity.sequence_number().high) << 32 | m_info.related_sample_identity.sequence_number().low; msg_info_.set_seq_num(seq_num); // fetch message string std::shared_ptr<std::string> msg_str = std::make_shared<std::string>(m.data()); // callback callback_(channel_id, msg_str, msg_info_); } void SubListener::onSubscriptionMatched( eprosima::fastrtps::Subscriber* sub, eprosima::fastrtps::MatchingInfo& info) { (void)sub; (void)info; } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/rtps/attributes_filler.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/transport/rtps/attributes_filler.h" #include <limits> #include "cyber/common/log.h" #include "cyber/transport/qos/qos_profile_conf.h" namespace apollo { namespace cyber { namespace transport { AttributesFiller::AttributesFiller() {} AttributesFiller::~AttributesFiller() {} bool AttributesFiller::FillInPubAttr( const std::string& channel_name, const QosProfile& qos, eprosima::fastrtps::PublisherAttributes* pub_attr) { RETURN_VAL_IF_NULL(pub_attr, false); pub_attr->topic.topicName = channel_name; pub_attr->topic.topicDataType = "UnderlayMessage"; pub_attr->topic.topicKind = eprosima::fastrtps::NO_KEY; switch (qos.history()) { case QosHistoryPolicy::HISTORY_KEEP_LAST: pub_attr->topic.historyQos.kind = eprosima::fastrtps::KEEP_LAST_HISTORY_QOS; break; case QosHistoryPolicy::HISTORY_KEEP_ALL: pub_attr->topic.historyQos.kind = eprosima::fastrtps::KEEP_ALL_HISTORY_QOS; break; default: break; } switch (qos.durability()) { case QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL: pub_attr->qos.m_durability.kind = eprosima::fastrtps::TRANSIENT_LOCAL_DURABILITY_QOS; break; case QosDurabilityPolicy::DURABILITY_VOLATILE: pub_attr->qos.m_durability.kind = eprosima::fastrtps::VOLATILE_DURABILITY_QOS; break; default: break; } switch (qos.reliability()) { case QosReliabilityPolicy::RELIABILITY_BEST_EFFORT: pub_attr->qos.m_reliability.kind = eprosima::fastrtps::BEST_EFFORT_RELIABILITY_QOS; break; case QosReliabilityPolicy::RELIABILITY_RELIABLE: pub_attr->qos.m_reliability.kind = eprosima::fastrtps::RELIABLE_RELIABILITY_QOS; break; default: break; } if (qos.depth() != QosProfileConf::QOS_HISTORY_DEPTH_SYSTEM_DEFAULT) { pub_attr->topic.historyQos.depth = static_cast<int32_t>(qos.depth()); } // ensure the history depth is at least the requested queue size if (pub_attr->topic.historyQos.depth < 0) { return false; } // transform messages per second to rtps heartbeat // set default heartbeat period pub_attr->times.heartbeatPeriod.seconds = 1; pub_attr->times.heartbeatPeriod.fraction = 0; if (qos.mps() != 0) { uint64_t mps = qos.mps(); // adapt heartbeat period if (mps > 1024) { mps = 1024; } else if (mps < 64) { mps = 64; } uint64_t fractions = (256ull << 32) / mps; uint32_t fraction = fractions & 0xffffffff; int32_t seconds = static_cast<int32_t>(fractions >> 32); pub_attr->times.heartbeatPeriod.seconds = seconds; pub_attr->times.heartbeatPeriod.fraction = fraction; } pub_attr->qos.m_publishMode.kind = eprosima::fastrtps::ASYNCHRONOUS_PUBLISH_MODE; pub_attr->historyMemoryPolicy = eprosima::fastrtps::DYNAMIC_RESERVE_MEMORY_MODE; pub_attr->topic.resourceLimitsQos.max_samples = 10000; return true; } bool AttributesFiller::FillInSubAttr( const std::string& channel_name, const QosProfile& qos, eprosima::fastrtps::SubscriberAttributes* sub_attr) { RETURN_VAL_IF_NULL(sub_attr, false); sub_attr->topic.topicName = channel_name; sub_attr->topic.topicDataType = "UnderlayMessage"; sub_attr->topic.topicKind = eprosima::fastrtps::NO_KEY; switch (qos.history()) { case QosHistoryPolicy::HISTORY_KEEP_LAST: sub_attr->topic.historyQos.kind = eprosima::fastrtps::KEEP_LAST_HISTORY_QOS; break; case QosHistoryPolicy::HISTORY_KEEP_ALL: sub_attr->topic.historyQos.kind = eprosima::fastrtps::KEEP_ALL_HISTORY_QOS; break; default: break; } switch (qos.durability()) { case QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL: sub_attr->qos.m_durability.kind = eprosima::fastrtps::TRANSIENT_LOCAL_DURABILITY_QOS; break; case QosDurabilityPolicy::DURABILITY_VOLATILE: sub_attr->qos.m_durability.kind = eprosima::fastrtps::VOLATILE_DURABILITY_QOS; break; default: break; } switch (qos.reliability()) { case QosReliabilityPolicy::RELIABILITY_BEST_EFFORT: sub_attr->qos.m_reliability.kind = eprosima::fastrtps::BEST_EFFORT_RELIABILITY_QOS; break; case QosReliabilityPolicy::RELIABILITY_RELIABLE: sub_attr->qos.m_reliability.kind = eprosima::fastrtps::RELIABLE_RELIABILITY_QOS; break; default: break; } if (qos.depth() != QosProfileConf::QOS_HISTORY_DEPTH_SYSTEM_DEFAULT) { sub_attr->topic.historyQos.depth = static_cast<int32_t>(qos.depth()); } // ensure the history depth is at least the requested queue size if (sub_attr->topic.historyQos.depth < 0) { return false; } sub_attr->historyMemoryPolicy = eprosima::fastrtps::DYNAMIC_RESERVE_MEMORY_MODE; sub_attr->topic.resourceLimitsQos.max_samples = 10000; return true; } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/common/endpoint_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/transport/common/endpoint.h" #include "gtest/gtest.h" #include "cyber/common/global_data.h" namespace apollo { namespace cyber { namespace transport { TEST(EndpointTest, construction) { proto::RoleAttributes role; { Endpoint e0(role); const proto::RoleAttributes& erole = e0.attributes(); EXPECT_EQ(erole.host_name(), common::GlobalData::Instance()->HostName()); EXPECT_EQ(erole.process_id(), common::GlobalData::Instance()->ProcessId()); EXPECT_EQ(erole.id(), e0.id().HashValue()); } { role.set_host_name("123"); role.set_process_id(54321); role.set_id(123); Endpoint e0(role); const proto::RoleAttributes& erole = e0.attributes(); EXPECT_EQ(erole.host_name(), "123"); EXPECT_EQ(erole.process_id(), 54321); EXPECT_NE(erole.id(), e0.id().HashValue()); auto id = std::string(e0.id().data(), ID_SIZE); EXPECT_NE(std::string("endpoint"), id); } } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/common/endpoint.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_TRANSPORT_COMMON_ENDPOINT_H_ #define CYBER_TRANSPORT_COMMON_ENDPOINT_H_ #include <memory> #include <string> #include "cyber/proto/role_attributes.pb.h" #include "cyber/transport/common/identity.h" namespace apollo { namespace cyber { namespace transport { class Endpoint; using EndpointPtr = std::shared_ptr<Endpoint>; using proto::RoleAttributes; class Endpoint { public: explicit Endpoint(const RoleAttributes& attr); virtual ~Endpoint(); const Identity& id() const { return id_; } const RoleAttributes& attributes() const { return attr_; } protected: bool enabled_; Identity id_; RoleAttributes attr_; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_COMMON_ENDPOINT_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/common/identity.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/transport/common/identity.h" #include <uuid/uuid.h> #include "cyber/common/util.h" namespace apollo { namespace cyber { namespace transport { Identity::Identity(bool need_generate) : hash_value_(0) { std::memset(data_, 0, ID_SIZE); if (need_generate) { uuid_t uuid; uuid_generate(uuid); std::memcpy(data_, uuid, ID_SIZE); Update(); } } Identity::Identity(const Identity& rhs) { std::memcpy(data_, rhs.data_, ID_SIZE); hash_value_ = rhs.hash_value_; } Identity::~Identity() {} Identity& Identity::operator=(const Identity& rhs) { if (this != &rhs) { std::memcpy(data_, rhs.data_, ID_SIZE); hash_value_ = rhs.hash_value_; } return *this; } bool Identity::operator==(const Identity& rhs) const { return std::memcmp(data_, rhs.data_, ID_SIZE) == 0; } bool Identity::operator!=(const Identity& rhs) const { return std::memcmp(data_, rhs.data_, ID_SIZE) != 0; } std::string Identity::ToString() const { return std::to_string(hash_value_); } size_t Identity::Length() const { return ID_SIZE; } uint64_t Identity::HashValue() const { return hash_value_; } void Identity::Update() { hash_value_ = common::Hash(std::string(data_, ID_SIZE)); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/common/endpoint.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/transport/common/endpoint.h" #include "cyber/common/global_data.h" namespace apollo { namespace cyber { namespace transport { Endpoint::Endpoint(const RoleAttributes& attr) : enabled_(false), id_(), attr_(attr) { if (!attr_.has_host_name()) { attr_.set_host_name(common::GlobalData::Instance()->HostName()); } if (!attr_.has_process_id()) { attr_.set_process_id(common::GlobalData::Instance()->ProcessId()); } if (!attr_.has_id()) { attr_.set_id(id_.HashValue()); } } Endpoint::~Endpoint() {} } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/common/identity.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_TRANSPORT_COMMON_IDENTITY_H_ #define CYBER_TRANSPORT_COMMON_IDENTITY_H_ #include <cstdint> #include <cstring> #include <string> namespace apollo { namespace cyber { namespace transport { constexpr uint8_t ID_SIZE = 8; class Identity { public: explicit Identity(bool need_generate = true); Identity(const Identity& another); virtual ~Identity(); Identity& operator=(const Identity& another); bool operator==(const Identity& another) const; bool operator!=(const Identity& another) const; std::string ToString() const; size_t Length() const; uint64_t HashValue() const; const char* data() const { return data_; } void set_data(const char* data) { if (data == nullptr) { return; } std::memcpy(data_, data, sizeof(data_)); Update(); } private: void Update(); char data_[ID_SIZE]; uint64_t hash_value_; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_COMMON_IDENTITY_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/common/identity_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/transport/common/identity.h" #include "gtest/gtest.h" namespace apollo { namespace cyber { namespace transport { TEST(IdentityTest, testConstructFalse) { Identity it(false); EXPECT_EQ(it.HashValue(), static_cast<uint64_t>(0)); EXPECT_EQ(it.ToString(), "0"); } TEST(IdentityTest, testConstructTrue) { Identity it(true); EXPECT_NE(it.HashValue(), static_cast<uint64_t>(0)); EXPECT_NE(it.ToString(), "0"); } TEST(IdentityTest, testIdentityEqual) { Identity id1; Identity id2; Identity id3; EXPECT_NE(id1, id2); EXPECT_NE(id2, id3); EXPECT_NE(id1, id3); EXPECT_NE(id1.HashValue(), id3.HashValue()); id2 = id2; EXPECT_NE(id2, id3); id2 = id3; EXPECT_EQ(id2, id3); Identity id4(id1); EXPECT_EQ(id1, id4); EXPECT_EQ(id1.ToString(), id4.ToString()); EXPECT_EQ(id1.HashValue(), id4.HashValue()); } TEST(IdentityTest, testOperatorEqual) { Identity it(true); Identity it1(false); it1 = it; EXPECT_EQ(it.HashValue(), it1.HashValue()); EXPECT_EQ(it.ToString(), it1.ToString()); EXPECT_EQ(it1.Length(), it.Length()); it.set_data(nullptr); Identity it2; it2.set_data(it.data()); EXPECT_EQ(it2.HashValue(), it1.HashValue()); EXPECT_EQ(it2.ToString(), it1.ToString()); EXPECT_EQ(it1.Length(), it2.Length()); } } // namespace transport } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/common/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_transport_common_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "endpoint", srcs = ["endpoint.cc"], hdrs = ["endpoint.h"], deps = [ ":identity", "//cyber/common:global_data", "//cyber/proto:role_attributes_cc_proto", ], ) cc_test( name = "endpoint_test", size = "small", srcs = ["endpoint_test.cc"], deps = [ "//cyber:cyber_core", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "identity", srcs = ["identity.cc"], hdrs = ["identity.h"], deps = [ "//cyber/common:util", "@uuid", ], ) cc_test( name = "identity_test", size = "small", srcs = ["identity_test.cc"], deps = [ "//cyber:cyber_core", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/receiver/hybrid_receiver.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_TRANSPORT_RECEIVER_HYBRID_RECEIVER_H_ #define CYBER_TRANSPORT_RECEIVER_HYBRID_RECEIVER_H_ #include <map> #include <memory> #include <set> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "cyber/common/global_data.h" #include "cyber/common/log.h" #include "cyber/common/types.h" #include "cyber/proto/role_attributes.pb.h" #include "cyber/service_discovery/role/role.h" #include "cyber/task/task.h" #include "cyber/time/time.h" #include "cyber/transport/receiver/intra_receiver.h" #include "cyber/transport/receiver/rtps_receiver.h" #include "cyber/transport/receiver/shm_receiver.h" #include "cyber/transport/rtps/participant.h" namespace apollo { namespace cyber { namespace transport { using apollo::cyber::proto::OptionalMode; using apollo::cyber::proto::QosDurabilityPolicy; using apollo::cyber::proto::RoleAttributes; template <typename M> class HybridReceiver : public Receiver<M> { public: using HistoryPtr = std::shared_ptr<History<M>>; using ReceiverPtr = std::shared_ptr<Receiver<M>>; using ReceiverContainer = std::unordered_map<OptionalMode, ReceiverPtr, std::hash<int>>; using TransmitterContainer = std::unordered_map<OptionalMode, std::unordered_map<uint64_t, RoleAttributes>, std::hash<int>>; using CommunicationModePtr = std::shared_ptr<proto::CommunicationMode>; using MappingTable = std::unordered_map<Relation, OptionalMode, std::hash<int>>; HybridReceiver(const RoleAttributes& attr, const typename Receiver<M>::MessageListener& msg_listener, const ParticipantPtr& participant); virtual ~HybridReceiver(); void Enable() override; void Disable() override; void Enable(const RoleAttributes& opposite_attr) override; void Disable(const RoleAttributes& opposite_attr) override; private: void InitMode(); void ObtainConfig(); void InitHistory(); void InitReceivers(); void ClearReceivers(); void InitTransmitters(); void ClearTransmitters(); void ReceiveHistoryMsg(const RoleAttributes& opposite_attr); void ThreadFunc(const RoleAttributes& opposite_attr); Relation GetRelation(const RoleAttributes& opposite_attr); HistoryPtr history_; ReceiverContainer receivers_; TransmitterContainer transmitters_; std::mutex mutex_; CommunicationModePtr mode_; MappingTable mapping_table_; ParticipantPtr participant_; }; template <typename M> HybridReceiver<M>::HybridReceiver( const RoleAttributes& attr, const typename Receiver<M>::MessageListener& msg_listener, const ParticipantPtr& participant) : Receiver<M>(attr, msg_listener), history_(nullptr), participant_(participant) { InitMode(); ObtainConfig(); InitHistory(); InitReceivers(); InitTransmitters(); } template <typename M> HybridReceiver<M>::~HybridReceiver() { ClearTransmitters(); ClearReceivers(); } template <typename M> void HybridReceiver<M>::Enable() { std::lock_guard<std::mutex> lock(mutex_); for (auto& item : receivers_) { item.second->Enable(); } } template <typename M> void HybridReceiver<M>::Disable() { std::lock_guard<std::mutex> lock(mutex_); for (auto& item : receivers_) { item.second->Disable(); } } template <typename M> void HybridReceiver<M>::Enable(const RoleAttributes& opposite_attr) { auto relation = GetRelation(opposite_attr); RETURN_IF(relation == NO_RELATION); uint64_t id = opposite_attr.id(); std::lock_guard<std::mutex> lock(mutex_); if (transmitters_[mapping_table_[relation]].count(id) == 0) { transmitters_[mapping_table_[relation]].insert( std::make_pair(id, opposite_attr)); receivers_[mapping_table_[relation]]->Enable(opposite_attr); ReceiveHistoryMsg(opposite_attr); } } template <typename M> void HybridReceiver<M>::Disable(const RoleAttributes& opposite_attr) { auto relation = GetRelation(opposite_attr); RETURN_IF(relation == NO_RELATION); uint64_t id = opposite_attr.id(); std::lock_guard<std::mutex> lock(mutex_); if (transmitters_[mapping_table_[relation]].count(id) > 0) { transmitters_[mapping_table_[relation]].erase(id); receivers_[mapping_table_[relation]]->Disable(opposite_attr); } } template <typename M> void HybridReceiver<M>::InitMode() { mode_ = std::make_shared<proto::CommunicationMode>(); mapping_table_[SAME_PROC] = mode_->same_proc(); mapping_table_[DIFF_PROC] = mode_->diff_proc(); mapping_table_[DIFF_HOST] = mode_->diff_host(); } template <typename M> void HybridReceiver<M>::ObtainConfig() { auto& global_conf = common::GlobalData::Instance()->Config(); if (!global_conf.has_transport_conf()) { return; } if (!global_conf.transport_conf().has_communication_mode()) { return; } mode_->CopyFrom(global_conf.transport_conf().communication_mode()); mapping_table_[SAME_PROC] = mode_->same_proc(); mapping_table_[DIFF_PROC] = mode_->diff_proc(); mapping_table_[DIFF_HOST] = mode_->diff_host(); } template <typename M> void HybridReceiver<M>::InitHistory() { HistoryAttributes history_attr(this->attr_.qos_profile().history(), this->attr_.qos_profile().depth()); history_ = std::make_shared<History<M>>(history_attr); if (this->attr_.qos_profile().durability() == QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL) { history_->Enable(); } } template <typename M> void HybridReceiver<M>::InitReceivers() { std::set<OptionalMode> modes; modes.insert(mode_->same_proc()); modes.insert(mode_->diff_proc()); modes.insert(mode_->diff_host()); auto listener = std::bind(&HybridReceiver<M>::OnNewMessage, this, std::placeholders::_1, std::placeholders::_2); for (auto& mode : modes) { switch (mode) { case OptionalMode::INTRA: receivers_[mode] = std::make_shared<IntraReceiver<M>>(this->attr_, listener); break; case OptionalMode::SHM: receivers_[mode] = std::make_shared<ShmReceiver<M>>(this->attr_, listener); break; default: receivers_[mode] = std::make_shared<RtpsReceiver<M>>(this->attr_, listener); break; } } } template <typename M> void HybridReceiver<M>::ClearReceivers() { receivers_.clear(); } template <typename M> void HybridReceiver<M>::InitTransmitters() { std::unordered_map<uint64_t, RoleAttributes> empty; for (auto& item : receivers_) { transmitters_[item.first] = empty; } } template <typename M> void HybridReceiver<M>::ClearTransmitters() { for (auto& item : transmitters_) { for (auto& upper_reach : item.second) { receivers_[item.first]->Disable(upper_reach.second); } } transmitters_.clear(); } template <typename M> void HybridReceiver<M>::ReceiveHistoryMsg(const RoleAttributes& opposite_attr) { // check qos if (opposite_attr.qos_profile().durability() != QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL) { return; } auto attr = opposite_attr; cyber::Async(&HybridReceiver<M>::ThreadFunc, this, attr); } template <typename M> void HybridReceiver<M>::ThreadFunc(const RoleAttributes& opposite_attr) { std::string channel_name = std::to_string(opposite_attr.id()) + std::to_string(this->attr_.id()); uint64_t channel_id = common::GlobalData::RegisterChannel(channel_name); RoleAttributes attr(this->attr_); attr.set_channel_name(channel_name); attr.set_channel_id(channel_id); attr.mutable_qos_profile()->CopyFrom(opposite_attr.qos_profile()); volatile bool is_msg_arrived = false; auto listener = [&](const std::shared_ptr<M>& msg, const MessageInfo& msg_info, const RoleAttributes& attr) { is_msg_arrived = true; this->OnNewMessage(msg, msg_info); }; auto receiver = std::make_shared<RtpsReceiver<M>>(attr, listener); receiver->Enable(); do { if (is_msg_arrived) { is_msg_arrived = false; } cyber::USleep(1000000); } while (is_msg_arrived); receiver->Disable(); ADEBUG << "recv threadfunc exit."; } template <typename M> Relation HybridReceiver<M>::GetRelation(const RoleAttributes& opposite_attr) { if (opposite_attr.channel_name() != this->attr_.channel_name()) { return NO_RELATION; } if (opposite_attr.host_ip() != this->attr_.host_ip()) { return DIFF_HOST; } if (opposite_attr.process_id() != this->attr_.process_id()) { return DIFF_PROC; } return SAME_PROC; } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_RECEIVER_HYBRID_RECEIVER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/receiver/intra_receiver.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_TRANSPORT_RECEIVER_INTRA_RECEIVER_H_ #define CYBER_TRANSPORT_RECEIVER_INTRA_RECEIVER_H_ #include "cyber/common/log.h" #include "cyber/transport/dispatcher/intra_dispatcher.h" #include "cyber/transport/receiver/receiver.h" namespace apollo { namespace cyber { namespace transport { template <typename M> class IntraReceiver : public Receiver<M> { public: IntraReceiver(const RoleAttributes& attr, const typename Receiver<M>::MessageListener& msg_listener); virtual ~IntraReceiver(); void Enable() override; void Disable() override; void Enable(const RoleAttributes& opposite_attr) override; void Disable(const RoleAttributes& opposite_attr) override; private: IntraDispatcherPtr dispatcher_; }; template <typename M> IntraReceiver<M>::IntraReceiver( const RoleAttributes& attr, const typename Receiver<M>::MessageListener& msg_listener) : Receiver<M>(attr, msg_listener) { dispatcher_ = IntraDispatcher::Instance(); } template <typename M> IntraReceiver<M>::~IntraReceiver() { Disable(); } template <typename M> void IntraReceiver<M>::Enable() { if (this->enabled_) { return; } dispatcher_->AddListener<M>( this->attr_, std::bind(&IntraReceiver<M>::OnNewMessage, this, std::placeholders::_1, std::placeholders::_2)); this->enabled_ = true; } template <typename M> void IntraReceiver<M>::Disable() { if (!this->enabled_) { return; } dispatcher_->RemoveListener<M>(this->attr_); this->enabled_ = false; } template <typename M> void IntraReceiver<M>::Enable(const RoleAttributes& opposite_attr) { dispatcher_->AddListener<M>( this->attr_, opposite_attr, std::bind(&IntraReceiver<M>::OnNewMessage, this, std::placeholders::_1, std::placeholders::_2)); } template <typename M> void IntraReceiver<M>::Disable(const RoleAttributes& opposite_attr) { dispatcher_->RemoveListener<M>(this->attr_, opposite_attr); } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_RECEIVER_INTRA_RECEIVER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/receiver/shm_receiver.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_TRANSPORT_RECEIVER_SHM_RECEIVER_H_ #define CYBER_TRANSPORT_RECEIVER_SHM_RECEIVER_H_ #include <functional> #include "cyber/common/log.h" #include "cyber/transport/dispatcher/shm_dispatcher.h" #include "cyber/transport/receiver/receiver.h" namespace apollo { namespace cyber { namespace transport { template <typename M> class ShmReceiver : public Receiver<M> { public: ShmReceiver(const RoleAttributes& attr, const typename Receiver<M>::MessageListener& msg_listener); virtual ~ShmReceiver(); void Enable() override; void Disable() override; void Enable(const RoleAttributes& opposite_attr) override; void Disable(const RoleAttributes& opposite_attr) override; private: ShmDispatcherPtr dispatcher_; }; template <typename M> ShmReceiver<M>::ShmReceiver( const RoleAttributes& attr, const typename Receiver<M>::MessageListener& msg_listener) : Receiver<M>(attr, msg_listener) { dispatcher_ = ShmDispatcher::Instance(); } template <typename M> ShmReceiver<M>::~ShmReceiver() { Disable(); } template <typename M> void ShmReceiver<M>::Enable() { if (this->enabled_) { return; } dispatcher_->AddListener<M>( this->attr_, std::bind(&ShmReceiver<M>::OnNewMessage, this, std::placeholders::_1, std::placeholders::_2)); this->enabled_ = true; } template <typename M> void ShmReceiver<M>::Disable() { if (!this->enabled_) { return; } dispatcher_->RemoveListener<M>(this->attr_); this->enabled_ = false; } template <typename M> void ShmReceiver<M>::Enable(const RoleAttributes& opposite_attr) { dispatcher_->AddListener<M>( this->attr_, opposite_attr, std::bind(&ShmReceiver<M>::OnNewMessage, this, std::placeholders::_1, std::placeholders::_2)); } template <typename M> void ShmReceiver<M>::Disable(const RoleAttributes& opposite_attr) { dispatcher_->RemoveListener<M>(this->attr_, opposite_attr); } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_RECEIVER_SHM_RECEIVER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/receiver/receiver.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_TRANSPORT_RECEIVER_RECEIVER_H_ #define CYBER_TRANSPORT_RECEIVER_RECEIVER_H_ #include <functional> #include <memory> #include "cyber/transport/common/endpoint.h" #include "cyber/transport/message/history.h" #include "cyber/transport/message/message_info.h" namespace apollo { namespace cyber { namespace transport { template <typename M> class Receiver : public Endpoint { public: using MessagePtr = std::shared_ptr<M>; using MessageListener = std::function<void( const MessagePtr&, const MessageInfo&, const RoleAttributes&)>; Receiver(const RoleAttributes& attr, const MessageListener& msg_listener); virtual ~Receiver(); virtual void Enable() = 0; virtual void Disable() = 0; virtual void Enable(const RoleAttributes& opposite_attr) = 0; virtual void Disable(const RoleAttributes& opposite_attr) = 0; protected: void OnNewMessage(const MessagePtr& msg, const MessageInfo& msg_info); MessageListener msg_listener_; }; template <typename M> Receiver<M>::Receiver(const RoleAttributes& attr, const MessageListener& msg_listener) : Endpoint(attr), msg_listener_(msg_listener) {} template <typename M> Receiver<M>::~Receiver() {} template <typename M> void Receiver<M>::OnNewMessage(const MessagePtr& msg, const MessageInfo& msg_info) { if (msg_listener_ != nullptr) { msg_listener_(msg, msg_info, attr_); } } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_RECEIVER_RECEIVER_H_
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/receiver/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_transport_receiver_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "receiver", deps = [ ":hybrid_receiver", ":intra_receiver", ":rtps_receiver", ":shm_receiver", ], ) cc_library( name = "receiver_interface", hdrs = ["receiver.h"], deps = [ "//cyber/transport/common:endpoint", "//cyber/transport/message:history", "//cyber/transport/message:message_info", ], ) cc_library( name = "hybrid_receiver", hdrs = ["hybrid_receiver.h"], deps = [ ":receiver_interface", ], ) cc_library( name = "intra_receiver", hdrs = ["intra_receiver.h"], deps = [ ":receiver_interface", ], ) cc_library( name = "rtps_receiver", hdrs = ["rtps_receiver.h"], deps = [ ":receiver_interface", ], ) cc_library( name = "shm_receiver", hdrs = ["shm_receiver.h"], deps = [ ":receiver_interface", "//cyber/transport/shm:readable_info", ], ) cpplint()
0
apollo_public_repos/apollo/cyber/transport
apollo_public_repos/apollo/cyber/transport/receiver/rtps_receiver.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_TRANSPORT_RECEIVER_RTPS_RECEIVER_H_ #define CYBER_TRANSPORT_RECEIVER_RTPS_RECEIVER_H_ #include "cyber/common/log.h" #include "cyber/transport/dispatcher/rtps_dispatcher.h" #include "cyber/transport/receiver/receiver.h" namespace apollo { namespace cyber { namespace transport { template <typename M> class RtpsReceiver : public Receiver<M> { public: RtpsReceiver(const RoleAttributes& attr, const typename Receiver<M>::MessageListener& msg_listener); virtual ~RtpsReceiver(); void Enable() override; void Disable() override; void Enable(const RoleAttributes& opposite_attr) override; void Disable(const RoleAttributes& opposite_attr) override; private: RtpsDispatcherPtr dispatcher_; }; template <typename M> RtpsReceiver<M>::RtpsReceiver( const RoleAttributes& attr, const typename Receiver<M>::MessageListener& msg_listener) : Receiver<M>(attr, msg_listener) { dispatcher_ = RtpsDispatcher::Instance(); } template <typename M> RtpsReceiver<M>::~RtpsReceiver() { Disable(); } template <typename M> void RtpsReceiver<M>::Enable() { if (this->enabled_) { return; } dispatcher_->AddListener<M>( this->attr_, std::bind(&RtpsReceiver<M>::OnNewMessage, this, std::placeholders::_1, std::placeholders::_2)); this->enabled_ = true; } template <typename M> void RtpsReceiver<M>::Disable() { if (!this->enabled_) { return; } dispatcher_->RemoveListener<M>(this->attr_); this->enabled_ = false; } template <typename M> void RtpsReceiver<M>::Enable(const RoleAttributes& opposite_attr) { dispatcher_->AddListener<M>( this->attr_, opposite_attr, std::bind(&RtpsReceiver<M>::OnNewMessage, this, std::placeholders::_1, std::placeholders::_2)); } template <typename M> void RtpsReceiver<M>::Disable(const RoleAttributes& opposite_attr) { dispatcher_->RemoveListener<M>(this->attr_, opposite_attr); } } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_RECEIVER_RTPS_RECEIVER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/logger_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/logger/logger.h" #include "gtest/gtest.h" #include "glog/logging.h" #include "cyber/common/log.h" namespace apollo { namespace cyber { namespace logger { TEST(LoggerTest, WriteAndFlush) { Logger logger(google::base::GetLogger(google::INFO)); time_t timep; time(&timep); std::string message = "I0909 99:99:99.999999 99999 logger_test.cc:999] "; message.append(LEFT_BRACKET); message.append("LoggerTest"); message.append(RIGHT_BRACKET); message.append("logger test message\n"); logger.Write(false, timep, message.c_str(), static_cast<int>(message.length())); EXPECT_EQ(logger.LogSize(), 0); // always zero logger.Write(true, timep, message.c_str(), static_cast<int>(message.length())); EXPECT_EQ(logger.LogSize(), 0); // always zero logger.Flush(); } TEST(LoggerTest, SetLoggerToGlog) { google::InitGoogleLogging("LoggerTest2"); google::SetLogDestination(google::ERROR, ""); google::SetLogDestination(google::WARNING, ""); google::SetLogDestination(google::FATAL, ""); Logger* logger = new Logger(google::base::GetLogger(google::INFO)); google::base::SetLogger(FLAGS_minloglevel, logger); ALOG_MODULE("LoggerTest2", INFO) << "test set logger to glog"; ALOG_MODULE("LoggerTest2", WARN) << "test set logger to glog"; ALOG_MODULE("LoggerTest2", ERROR) << "test set logger to glog"; logger = nullptr; google::ShutdownGoogleLogging(); } } // namespace logger } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/log_file_object.cc
// Copyright (c) 1999, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /****************************************************************************** * 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/logger/log_file_object.h" #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <cassert> #include <iomanip> #include <iostream> #include <vector> #include "glog/log_severity.h" #include "cyber/logger/logger_util.h" namespace apollo { namespace cyber { namespace logger { #define PATH_SEPARATOR '/' // Globally disable log writing (if disk is full) static bool stop_writing = false; const char* const LogSeverityNames[NUM_SEVERITIES] = {"INFO", "WARNING", "ERROR", "FATAL"}; LogFileObject::LogFileObject(LogSeverity severity, const char* base_filename) : base_filename_selected_(base_filename != nullptr), base_filename_((base_filename != nullptr) ? base_filename : ""), symlink_basename_("UNKNOWN"), filename_extension_(), file_(NULL), severity_(severity), bytes_since_flush_(0), file_length_(0), rollover_attempt_(kRolloverAttemptFrequency - 1), next_flush_time_(0) { if (base_filename_.empty()) { base_filename_ = "UNKNOWN"; } assert(severity >= 0); assert(severity < NUM_SEVERITIES); } LogFileObject::~LogFileObject() { std::lock_guard<std::mutex> lock(lock_); if (file_ != nullptr) { fclose(file_); file_ = nullptr; } } void LogFileObject::SetBasename(const char* basename) { std::lock_guard<std::mutex> lock(lock_); base_filename_selected_ = true; if (base_filename_ != basename) { // Get rid of old log file since we are changing names if (file_ != nullptr) { fclose(file_); file_ = nullptr; rollover_attempt_ = kRolloverAttemptFrequency - 1; } base_filename_ = basename; } } void LogFileObject::SetExtension(const char* ext) { std::lock_guard<std::mutex> lock(lock_); if (filename_extension_ != ext) { // Get rid of old log file since we are changing names if (file_ != nullptr) { fclose(file_); file_ = nullptr; rollover_attempt_ = kRolloverAttemptFrequency - 1; } filename_extension_ = ext; } } void LogFileObject::SetSymlinkBasename(const char* symlink_basename) { std::lock_guard<std::mutex> lock(lock_); symlink_basename_ = symlink_basename; } void LogFileObject::Flush() { std::lock_guard<std::mutex> lock(lock_); FlushUnlocked(); } void LogFileObject::FlushUnlocked() { if (file_ != nullptr) { fflush(file_); bytes_since_flush_ = 0; } // Figure out when we are due for another flush. const int64 next = (FLAGS_logbufsecs * static_cast<int64>(1000000)); // in usec next_flush_time_ = CycleClock_Now() + UsecToCycles(next); } bool LogFileObject::CreateLogfile(const string& time_pid_string) { string string_filename = base_filename_ + filename_extension_ + time_pid_string; const char* filename = string_filename.c_str(); int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, FLAGS_logfile_mode); if (fd == -1) { return false; } // Mark the file close-on-exec. We don't really care if this fails fcntl(fd, F_SETFD, FD_CLOEXEC); file_ = fdopen(fd, "a"); // Make a FILE*. if (file_ == nullptr) { // Man, we're screwed! close(fd); unlink(filename); // Erase the half-baked evidence: an unusable log file return false; } // We try to create a symlink called <program_name>.<severity>, // which is easier to use. (Every time we create a new logfile, // we destroy the old symlink and create a new one, so it always // points to the latest logfile.) If it fails, we're sad but it's // no error. if (!symlink_basename_.empty()) { // take directory from filename const char* slash = strrchr(filename, PATH_SEPARATOR); const string linkname = symlink_basename_ + '.' + LogSeverityNames[severity_]; string linkpath; if (slash) { linkpath = string(filename, slash - filename + 1); // get dirname } linkpath += linkname; unlink(linkpath.c_str()); // delete old one if it exists // We must have unistd.h. // Make the symlink be relative (in the same dir) so that if the // entire log directory gets relocated the link is still valid. const char* linkdest = slash ? (slash + 1) : filename; if (symlink(linkdest, linkpath.c_str()) != 0) { // silently ignore failures AINFO << "symlink failed."; } // Make an additional link to the log file in a place specified by // FLAGS_log_link, if indicated if (!FLAGS_log_link.empty()) { linkpath = FLAGS_log_link + "/" + linkname; unlink(linkpath.c_str()); // delete old one if it exists if (symlink(filename, linkpath.c_str()) != 0) { // silently ignore failures } } } return true; // Everything worked } void LogFileObject::Write(bool force_flush, time_t timestamp, const char* message, int message_len) { std::lock_guard<std::mutex> lock(lock_); // We don't log if the base_name_ is "" (which means "don't write") if (base_filename_selected_ && base_filename_.empty()) { return; } if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() || PidHasChanged()) { if (file_ != nullptr) { fclose(file_); } file_ = nullptr; file_length_ = bytes_since_flush_ = 0; rollover_attempt_ = kRolloverAttemptFrequency - 1; } // If there's no destination file, make one before outputting if (file_ == nullptr) { // Try to rollover the log file every 32 log messages. The only time // this could matter would be when we have trouble creating the log // file. If that happens, we'll lose lots of log messages, of course! if (++rollover_attempt_ != kRolloverAttemptFrequency) { return; } rollover_attempt_ = 0; struct ::tm tm_time; localtime_r(&timestamp, &tm_time); // The logfile's filename will have the date/time & pid in it ostringstream time_pid_stream; time_pid_stream.fill('0'); time_pid_stream << 1900 + tm_time.tm_year << setw(2) << 1 + tm_time.tm_mon << setw(2) << tm_time.tm_mday << '-' << setw(2) << tm_time.tm_hour << setw(2) << tm_time.tm_min << setw(2) << tm_time.tm_sec << '.' << GetMainThreadPid(); const string& time_pid_string = time_pid_stream.str(); // base filename always selected. if (base_filename_selected_) { if (!CreateLogfile(time_pid_string)) { perror("Could not create log file"); fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n", time_pid_string.c_str()); return; } } // Write a header message into the log file ostringstream file_header_stream; file_header_stream.fill('0'); file_header_stream << "Log file created at: " << 1900 + tm_time.tm_year << '/' << setw(2) << 1 + tm_time.tm_mon << '/' << setw(2) << tm_time.tm_mday << ' ' << setw(2) << tm_time.tm_hour << ':' << setw(2) << tm_time.tm_min << ':' << setw(2) << tm_time.tm_sec << '\n' << "Running on machine: " << hostname() << '\n' << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu " << "threadid file:line] msg" << '\n'; const string& file_header_string = file_header_stream.str(); const int header_len = static_cast<int>(file_header_string.size()); if (file_ == nullptr) { return; } fwrite(file_header_string.data(), 1, header_len, file_); file_length_ += header_len; bytes_since_flush_ += header_len; } // Write to LOG file if (!stop_writing) { // fwrite() doesn't return an error when the disk is full, for // messages that are less than 4096 bytes. When the disk is full, // it returns the message length for messages that are less than // 4096 bytes. fwrite() returns 4096 for message lengths that are // greater than 4096, thereby indicating an error. errno = 0; fwrite(message, 1, message_len, file_); if (FLAGS_stop_logging_if_full_disk && errno == ENOSPC) { // disk full, stop writing to disk stop_writing = true; // until the disk is return; } else { file_length_ += message_len; bytes_since_flush_ += message_len; } } else { if (CycleClock_Now() >= next_flush_time_) { stop_writing = false; // check to see if disk has free space. } return; // no need to flush } // See important msgs *now*. Also, flush logs at least every 10^6 chars, // or every "FLAGS_logbufsecs" seconds. if (force_flush || (bytes_since_flush_ >= 1000000) || (CycleClock_Now() >= next_flush_time_)) { FlushUnlocked(); } } /* static */ const string& LogFileObject::hostname() { if (hostname_.empty()) { GetHostName(&hostname_); if (hostname_.empty()) { hostname_ = "(unknown)"; } } return hostname_; } } // namespace logger } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/logger_util.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. *****************************************************************************/ /** * @file */ #ifndef CYBER_LOGGER_LOGGER_UTIL_H_ #define CYBER_LOGGER_LOGGER_UTIL_H_ #include <sys/stat.h> #include <sys/time.h> #include <sys/utsname.h> #include <unistd.h> #include <cstdint> #include <cstdlib> #include <ctime> #include <string> #include <vector> #include "cyber/common/global_data.h" namespace apollo { namespace cyber { namespace logger { inline int64_t CycleClock_Now() { struct timeval tv; gettimeofday(&tv, nullptr); return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec; } inline int64_t UsecToCycles(int64_t usec) { return usec; } static inline void GetHostName(std::string* hostname) { struct utsname buf; if (0 != uname(&buf)) { // ensure null termination on failure *buf.nodename = '\0'; } *hostname = buf.nodename; } int32_t GetMainThreadPid(); bool PidHasChanged(); inline int32_t MaxLogSize() { return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1); } inline void FindModuleName(std::string* log_message, std::string* module_name) { auto lpos = log_message->find(LEFT_BRACKET); if (lpos != std::string::npos) { auto rpos = log_message->find(RIGHT_BRACKET, lpos); if (rpos != std::string::npos) { module_name->assign(*log_message, lpos + 1, rpos - lpos - 1); auto cut_length = rpos - lpos + 1; log_message->erase(lpos, cut_length); } } if (module_name->empty()) { CHECK_NOTNULL(common::GlobalData::Instance()); *module_name = common::GlobalData::Instance()->ProcessGroup(); } } } // namespace logger } // namespace cyber } // namespace apollo #endif // CYBER_LOGGER_LOGGER_UTIL_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/logger_util.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/logger/logger_util.h" #include <sys/stat.h> #include <sys/time.h> #include <sys/utsname.h> #include <unistd.h> #include <cstdint> #include <cstdlib> #include <ctime> #include <string> #include <vector> #include "glog/logging.h" namespace apollo { namespace cyber { namespace logger { static int32_t g_main_thread_pid = getpid(); int32_t GetMainThreadPid() { return g_main_thread_pid; } bool PidHasChanged() { int32_t pid = getpid(); if (g_main_thread_pid == pid) { return false; } g_main_thread_pid = pid; return true; } } // namespace logger } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/async_logger_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/logger/async_logger.h" #include "gtest/gtest.h" #include "glog/logging.h" #include "cyber/common/log.h" namespace apollo { namespace cyber { namespace logger { TEST(AsyncLoggerTest, WriteAndFlush) { AsyncLogger logger(google::base::GetLogger(google::INFO)); // write in stop state time_t timep; time(&timep); std::string message = "I0909 99:99:99.999999 99999 logger_test.cc:999] "; message.append(LEFT_BRACKET); message.append("AsyncLoggerTest"); message.append(RIGHT_BRACKET); message.append("async logger test message\n"); logger.Write(false, timep, message.c_str(), static_cast<int>(message.length())); EXPECT_EQ(logger.LogSize(), 0); // always zero // write in start state logger.Start(); logger.Write(true, timep, message.c_str(), static_cast<int>(message.length())); EXPECT_EQ(logger.LogSize(), 0); // always zero // flush logger.Flush(); EXPECT_EQ(logger.LogSize(), 0); // always zero logger.Stop(); } TEST(AsyncLoggerTest, SetLoggerToGlog) { google::InitGoogleLogging("AsyncLoggerTest2"); google::SetLogDestination(google::ERROR, ""); google::SetLogDestination(google::WARNING, ""); google::SetLogDestination(google::FATAL, ""); AsyncLogger logger(google::base::GetLogger(google::INFO)); google::base::SetLogger(FLAGS_minloglevel, &logger); logger.Start(); ALOG_MODULE("AsyncLoggerTest2", INFO) << "test set async logger to glog"; ALOG_MODULE("AsyncLoggerTest2", WARN) << "test set async logger to glog"; ALOG_MODULE("AsyncLoggerTest2", ERROR) << "test set async logger to glog"; logger.Stop(); google::ShutdownGoogleLogging(); } } // namespace logger } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/async_logger.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/logger/async_logger.h" #include <cstdlib> #include <string> #include <thread> #include <unordered_map> #include "cyber/base/macros.h" #include "cyber/logger/logger_util.h" namespace apollo { namespace cyber { namespace logger { static const std::unordered_map<char, int> log_level_map = { {'F', 3}, {'E', 2}, {'W', 1}, {'I', 0}}; AsyncLogger::AsyncLogger(google::base::Logger* wrapped) : wrapped_(wrapped) { active_buf_.reset(new std::deque<Msg>()); flushing_buf_.reset(new std::deque<Msg>()); } AsyncLogger::~AsyncLogger() { Stop(); } void AsyncLogger::Start() { CHECK_EQ(state_.load(std::memory_order_acquire), INITTED); state_.store(RUNNING, std::memory_order_release); log_thread_ = std::thread(&AsyncLogger::RunThread, this); // std::cout << "Async Logger Start!" << std::endl; } void AsyncLogger::Stop() { state_.store(STOPPED, std::memory_order_release); if (log_thread_.joinable()) { log_thread_.join(); } FlushBuffer(active_buf_); ACHECK(active_buf_->empty()); ACHECK(flushing_buf_->empty()); // std::cout << "Async Logger Stop!" << std::endl; } void AsyncLogger::Write(bool force_flush, time_t timestamp, const char* message, int message_len) { if (cyber_unlikely(state_.load(std::memory_order_acquire) != RUNNING)) { // std::cout << "Async Logger not running!" << std::endl; return; } if (message_len > 0) { auto msg_str = std::string(message, message_len); while (flag_.test_and_set(std::memory_order_acquire)) { cpu_relax(); } active_buf_->emplace_back(timestamp, std::move(msg_str), log_level_map.at(message[0])); flag_.clear(std::memory_order_release); } if (force_flush && timestamp == 0 && message && message_len == 0) { Stop(); } } void AsyncLogger::Flush() { for (auto& module_logger : module_logger_map_) { module_logger.second->Flush(); } } uint32_t AsyncLogger::LogSize() { return wrapped_->LogSize(); } void AsyncLogger::RunThread() { while (state_ == RUNNING) { while (flag_.test_and_set(std::memory_order_acquire)) { cpu_relax(); } active_buf_.swap(flushing_buf_); flag_.clear(std::memory_order_release); FlushBuffer(flushing_buf_); if (active_buf_->size() < 800) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } } void AsyncLogger::FlushBuffer(const std::unique_ptr<std::deque<Msg>>& buffer) { std::string module_name = ""; while (!buffer->empty()) { auto& msg = buffer->front(); FindModuleName(&(msg.message), &module_name); if (module_logger_map_.find(module_name) == module_logger_map_.end()) { std::string file_name = module_name + ".log.INFO."; if (!FLAGS_log_dir.empty()) { file_name = FLAGS_log_dir + "/" + file_name; } module_logger_map_[module_name].reset( new LogFileObject(google::INFO, file_name.c_str())); module_logger_map_[module_name]->SetSymlinkBasename(module_name.c_str()); } const bool force_flush = msg.level > 0; module_logger_map_.find(module_name) ->second->Write(force_flush, msg.ts, msg.message.data(), static_cast<int>(msg.message.size())); buffer->pop_front(); } Flush(); } } // namespace logger } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/async_logger.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_LOGGER_ASYNC_LOGGER_H_ #define CYBER_LOGGER_ASYNC_LOGGER_H_ #include <atomic> #include <condition_variable> #include <cstdint> #include <ctime> #include <deque> #include <iostream> #include <memory> #include <mutex> #include <string> #include <thread> #include <unordered_map> #include <utility> #include <vector> #include "glog/logging.h" #include "cyber/common/macros.h" #include "cyber/logger/log_file_object.h" namespace apollo { namespace cyber { namespace logger { /** * @class AsyncLogger * @brief . * Wrapper for a glog Logger which asynchronously writes log messages. * This class starts a new thread responsible for forwarding the messages * to the logger, and performs double buffering. Writers append to the * current buffer and then wake up the logger thread. The logger swaps in * a new buffer and writes any accumulated messages to the wrapped * Logger. * * This double-buffering design dramatically improves performance, especially * for logging messages which require flushing the underlying file (i.e WARNING * and above for default). The flush can take a couple of milliseconds, and in * some cases can even block for hundreds of milliseconds or more. With the * double-buffered approach, threads can proceed with useful work while the IO * thread blocks. * * The semantics provided by this wrapper are slightly weaker than the default * glog semantics. By default, glog will immediately (synchronously) flush * WARNING * and above to the underlying file, whereas here we are deferring that flush to * a separate thread. This means that a crash just after a 'LOG_WARN' would * may be missing the message in the logs, but the perf benefit is probably * worth it. We do take care that a glog FATAL message flushes all buffered log * messages before exiting. * * @warning The logger limits the total amount of buffer space, so if the * underlying log blocks for too long, eventually the threads generating the log * messages will block as well. This prevents runaway memory usage. */ class AsyncLogger : public google::base::Logger { public: explicit AsyncLogger(google::base::Logger* wrapped); ~AsyncLogger(); /** * @brief start the async logger */ void Start(); /** * @brief Stop the thread. Flush() and Write() must not be called after this. * NOTE: this is currently only used in tests: in real life, we enable async * logging once when the program starts and then never disable it. * REQUIRES: Start() must have been called. */ void Stop(); /** * @brief Write a message to the log. Start() must have been called. * * @param force_flush is set by the GLog library based on the configured * '--logbuflevel' flag. * Any messages logged at the configured level or higher result in * 'force_flush' being set to true, indicating that the message should be * immediately written to the log rather than buffered in memory. * @param timestamp is the time of write a message * @param message is the info to be written * @param message_len is the length of message */ void Write(bool force_flush, time_t timestamp, const char* message, int message_len) override; /** * @brief Flush any buffered messages. */ void Flush() override; /** * @brief Get the current LOG file size. * The return value is an approximate value since some * logged data may not have been flushed to disk yet. * * @return the log file size */ uint32_t LogSize() override; /** * @brief get the log thead * * @return the pointer of log thread */ std::thread* LogThread() { return &log_thread_; } private: // A buffered message. // // TODO(todd): using std::string for buffered messages is convenient but not // as efficient as it could be. It's better to make the buffers just be // Arenas and allocate both the message data and Msg struct from them, forming // a linked list. struct Msg { time_t ts; std::string message; int32_t level; Msg() : ts(0), message(), level(google::INFO) {} Msg(time_t ts, std::string&& message, int32_t level) : ts(ts), message(std::move(message)), level(level) {} Msg(const Msg& rsh) { ts = rsh.ts; message = rsh.message; level = rsh.level; } Msg(Msg&& rsh) { ts = rsh.ts; message = rsh.message; level = rsh.level; } Msg& operator=(Msg&& rsh) { ts = rsh.ts; message = std::move(rsh.message); level = rsh.level; return *this; } Msg& operator=(const Msg& rsh) { ts = rsh.ts; message = rsh.message; level = rsh.level; return *this; } }; void RunThread(); void FlushBuffer(const std::unique_ptr<std::deque<Msg>>& msg); google::base::Logger* const wrapped_; std::thread log_thread_; // Count of how many times the writer thread has flushed the buffers. // 64 bits should be enough to never worry about overflow. std::atomic<uint64_t> flush_count_ = {0}; // Count of how many times the writer thread has dropped the log messages. // 64 bits should be enough to never worry about overflow. uint64_t drop_count_ = 0; // The buffer to which application threads append new log messages. std::unique_ptr<std::deque<Msg>> active_buf_; // The buffer currently being flushed by the logger thread, cleared // after a successful flush. std::unique_ptr<std::deque<Msg>> flushing_buf_; // Trigger for the logger thread to stop. enum State { INITTED, RUNNING, STOPPED }; std::atomic<State> state_ = {INITTED}; std::atomic_flag flag_ = ATOMIC_FLAG_INIT; std::unordered_map<std::string, std::unique_ptr<LogFileObject>> module_logger_map_; DISALLOW_COPY_AND_ASSIGN(AsyncLogger); }; } // namespace logger } // namespace cyber } // namespace apollo #endif // CYBER_LOGGER_ASYNC_LOGGER_H_
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/logger.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/logger/logger.h" #include <cstdlib> #include <string> #include <unordered_map> #include <utility> #include "glog/logging.h" #include "cyber/logger/log_file_object.h" #include "cyber/logger/logger_util.h" namespace apollo { namespace cyber { namespace logger { static std::unordered_map<std::string, LogFileObject*> moduleLoggerMap; Logger::Logger(google::base::Logger* wrapped) : wrapped_(wrapped) {} Logger::~Logger() { for (auto itr = moduleLoggerMap.begin(); itr != moduleLoggerMap.end(); ++itr) { delete itr->second; } moduleLoggerMap.clear(); } void Logger::Write(bool force_flush, time_t timestamp, const char* message, int message_len) { std::string log_message = std::string(message, message_len); std::string module_name; // set the same bracket as the bracket in log.h FindModuleName(&log_message, &module_name); LogFileObject* fileobject = nullptr; { std::lock_guard<std::mutex> lock(mutex_); if (moduleLoggerMap.find(module_name) != moduleLoggerMap.end()) { fileobject = moduleLoggerMap[module_name]; } else { std::string file_name = module_name + ".log.INFO."; if (!FLAGS_log_dir.empty()) { file_name = FLAGS_log_dir + "/" + file_name; } fileobject = new LogFileObject(google::INFO, file_name.c_str()); fileobject->SetSymlinkBasename(module_name.c_str()); moduleLoggerMap[module_name] = fileobject; } } if (fileobject) { fileobject->Write(force_flush, timestamp, log_message.c_str(), static_cast<int>(log_message.size())); } } void Logger::Flush() { wrapped_->Flush(); } uint32_t Logger::LogSize() { return wrapped_->LogSize(); } } // namespace logger } // namespace cyber } // namespace apollo
0
apollo_public_repos/apollo/cyber
apollo_public_repos/apollo/cyber/logger/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) filegroup( name = "cyber_logger_hdrs", srcs = glob([ "*.h", ]), ) cc_library( name = "logger", srcs = ["logger.cc"], hdrs = ["logger.h"], deps = [ "//cyber/common", "//cyber/logger:log_file_object", ], alwayslink =True, ) cc_test( name = "logger_test", size = "small", srcs = ["logger_test.cc"], deps = [ "//cyber", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_library( name = "async_logger", srcs = ["async_logger.cc"], hdrs = ["async_logger.h"], deps = [ "//cyber/base:macros", "//cyber/common", "//cyber/logger:log_file_object", ], ) cc_test( name = "async_logger_test", size = "small", srcs = ["async_logger_test.cc"], deps = [ "//cyber", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_library( name = "log_file_object", srcs = ["log_file_object.cc"], hdrs = ["log_file_object.h"], deps = [ "//cyber:binary", "//cyber/common:log", "//cyber/logger:logger_util", ], ) cc_test( name = "log_file_object_test", size = "small", srcs = ["log_file_object_test.cc"], deps = [ "//cyber", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_library( name = "logger_util", srcs = ["logger_util.cc"], hdrs = ["logger_util.h"], deps = [ "//cyber/common:global_data", ], ) cc_test( name = "logger_util_test", size = "small", srcs = ["logger_util_test.cc"], deps = [ "//cyber", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cpplint()
0