repo_id
stringlengths 19
138
| file_path
stringlengths 32
200
| content
stringlengths 1
12.9M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/blocker/intra_writer.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_BLOCKER_INTRA_WRITER_H_
#define CYBER_BLOCKER_INTRA_WRITER_H_
#include <memory>
#include "cyber/blocker/blocker_manager.h"
#include "cyber/node/writer.h"
namespace apollo {
namespace cyber {
namespace blocker {
template <typename MessageT>
class IntraWriter : public apollo::cyber::Writer<MessageT> {
public:
using MessagePtr = std::shared_ptr<MessageT>;
using BlockerManagerPtr = std::shared_ptr<BlockerManager>;
explicit IntraWriter(const proto::RoleAttributes& attr);
virtual ~IntraWriter();
bool Init() override;
void Shutdown() override;
bool Write(const MessageT& msg) override;
bool Write(const MessagePtr& msg_ptr) override;
private:
BlockerManagerPtr blocker_manager_;
};
template <typename MessageT>
IntraWriter<MessageT>::IntraWriter(const proto::RoleAttributes& attr)
: Writer<MessageT>(attr) {}
template <typename MessageT>
IntraWriter<MessageT>::~IntraWriter() {
Shutdown();
}
template <typename MessageT>
bool IntraWriter<MessageT>::Init() {
{
std::lock_guard<std::mutex> g(this->lock_);
if (this->init_) {
return true;
}
blocker_manager_ = BlockerManager::Instance();
blocker_manager_->GetOrCreateBlocker<MessageT>(
BlockerAttr(this->role_attr_.channel_name()));
this->init_ = true;
}
return true;
}
template <typename MessageT>
void IntraWriter<MessageT>::Shutdown() {
{
std::lock_guard<std::mutex> g(this->lock_);
if (!this->init_) {
return;
}
this->init_ = false;
}
blocker_manager_ = nullptr;
}
template <typename MessageT>
bool IntraWriter<MessageT>::Write(const MessageT& msg) {
if (!WriterBase::IsInit()) {
return false;
}
return blocker_manager_->Publish<MessageT>(this->role_attr_.channel_name(),
msg);
}
template <typename MessageT>
bool IntraWriter<MessageT>::Write(const MessagePtr& msg_ptr) {
if (!WriterBase::IsInit()) {
return false;
}
return blocker_manager_->Publish<MessageT>(this->role_attr_.channel_name(),
msg_ptr);
}
} // namespace blocker
} // namespace cyber
} // namespace apollo
#endif // CYBER_BLOCKER_INTRA_WRITER_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/blocker/blocker_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/blocker/blocker.h"
#include <memory>
#include "gtest/gtest.h"
#include "cyber/proto/unit_test.pb.h"
namespace apollo {
namespace cyber {
namespace blocker {
using apollo::cyber::proto::UnitTest;
TEST(BlockerTest, constructor) {
BlockerAttr attr(10, "channel");
Blocker<UnitTest> blocker(attr);
EXPECT_EQ(blocker.capacity(), 10);
EXPECT_EQ(blocker.channel_name(), "channel");
blocker.set_capacity(20);
EXPECT_EQ(blocker.capacity(), 20);
}
TEST(BlockerTest, set_capacity) {
BlockerAttr attr(0, "channel");
Blocker<UnitTest> blocker(attr);
EXPECT_EQ(blocker.capacity(), 0);
UnitTest msg;
msg.set_class_name("BlockerTest");
msg.set_case_name("publish");
blocker.Publish(msg);
blocker.set_capacity(2);
EXPECT_EQ(blocker.capacity(), 2);
blocker.Publish(msg);
blocker.Publish(msg);
blocker.Publish(msg);
blocker.set_capacity(1);
EXPECT_EQ(blocker.capacity(), 1);
}
TEST(BlockerTest, publish) {
BlockerAttr attr(10, "channel");
Blocker<UnitTest> blocker(attr);
auto msg1 = std::make_shared<UnitTest>();
msg1->set_class_name("BlockerTest");
msg1->set_case_name("publish_1");
UnitTest msg2;
msg2.set_class_name("BlockerTest");
msg2.set_case_name("publish_2");
EXPECT_TRUE(blocker.IsPublishedEmpty());
blocker.Publish(msg1);
blocker.Publish(msg2);
EXPECT_FALSE(blocker.IsPublishedEmpty());
EXPECT_TRUE(blocker.IsObservedEmpty());
blocker.Observe();
EXPECT_FALSE(blocker.IsObservedEmpty());
auto& latest_observed_msg = blocker.GetLatestObserved();
EXPECT_EQ(latest_observed_msg.class_name(), "BlockerTest");
EXPECT_EQ(latest_observed_msg.case_name(), "publish_2");
auto latest_observed_msg_ptr = blocker.GetLatestObservedPtr();
EXPECT_EQ(latest_observed_msg_ptr->class_name(), "BlockerTest");
EXPECT_EQ(latest_observed_msg_ptr->case_name(), "publish_2");
auto latest_published_ptr = blocker.GetLatestPublishedPtr();
EXPECT_EQ(latest_published_ptr->class_name(), "BlockerTest");
EXPECT_EQ(latest_published_ptr->case_name(), "publish_2");
blocker.ClearPublished();
blocker.ClearObserved();
EXPECT_TRUE(blocker.IsPublishedEmpty());
EXPECT_TRUE(blocker.IsObservedEmpty());
}
TEST(BlockerTest, subscribe) {
BlockerAttr attr(10, "channel");
Blocker<UnitTest> blocker(attr);
auto received_msg = std::make_shared<UnitTest>();
bool res = blocker.Subscribe(
"BlockerTest1", [&received_msg](const std::shared_ptr<UnitTest>& msg) {
received_msg->CopyFrom(*msg);
});
EXPECT_TRUE(res);
auto msg1 = std::make_shared<UnitTest>();
msg1->set_class_name("BlockerTest");
msg1->set_case_name("publish_1");
blocker.Publish(msg1);
EXPECT_EQ(received_msg->class_name(), msg1->class_name());
EXPECT_EQ(received_msg->case_name(), msg1->case_name());
res = blocker.Subscribe(
"BlockerTest1", [&received_msg](const std::shared_ptr<UnitTest>& msg) {
received_msg->CopyFrom(*msg);
});
EXPECT_FALSE(res);
}
} // namespace blocker
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/blocker/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "cyber_blocker_hdrs",
srcs = glob([
"*.h",
]),
)
cc_library(
name = "blocker_manager",
srcs = ["blocker_manager.cc"],
hdrs = ["blocker_manager.h"],
deps = [
":blocker",
],
)
cc_test(
name = "blocker_manager_test",
size = "small",
srcs = ["blocker_manager_test.cc"],
deps = [
"//cyber",
"//cyber/proto:unit_test_cc_proto",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "blocker",
hdrs = ["blocker.h"],
)
cc_test(
name = "blocker_test",
size = "small",
srcs = ["blocker_test.cc"],
deps = [
"//cyber",
"//cyber/proto:unit_test_cc_proto",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "intra_reader",
hdrs = ["intra_reader.h"],
deps = [
":blocker_manager",
],
)
cc_library(
name = "intra_writer",
hdrs = ["intra_writer.h"],
deps = [
":blocker_manager",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/blocker/intra_reader.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_BLOCKER_INTRA_READER_H_
#define CYBER_BLOCKER_INTRA_READER_H_
#include <functional>
#include <list>
#include <memory>
#include "cyber/blocker/blocker_manager.h"
#include "cyber/common/log.h"
#include "cyber/node/reader.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
namespace blocker {
template <typename MessageT>
class IntraReader : public apollo::cyber::Reader<MessageT> {
public:
using MessagePtr = std::shared_ptr<MessageT>;
using Callback = std::function<void(const std::shared_ptr<MessageT>&)>;
using Iterator =
typename std::list<std::shared_ptr<MessageT>>::const_iterator;
IntraReader(const proto::RoleAttributes& attr, const Callback& callback);
virtual ~IntraReader();
bool Init() override;
void Shutdown() override;
void ClearData() override;
void Observe() override;
bool Empty() const override;
bool HasReceived() const override;
void Enqueue(const std::shared_ptr<MessageT>& msg) override;
void SetHistoryDepth(const uint32_t& depth) override;
uint32_t GetHistoryDepth() const override;
std::shared_ptr<MessageT> GetLatestObserved() const override;
std::shared_ptr<MessageT> GetOldestObserved() const override;
Iterator Begin() const override;
Iterator End() const override;
private:
void OnMessage(const MessagePtr& msg_ptr);
Callback msg_callback_;
};
template <typename MessageT>
IntraReader<MessageT>::IntraReader(const proto::RoleAttributes& attr,
const Callback& callback)
: Reader<MessageT>(attr), msg_callback_(callback) {}
template <typename MessageT>
IntraReader<MessageT>::~IntraReader() {
Shutdown();
}
template <typename MessageT>
bool IntraReader<MessageT>::Init() {
if (this->init_.exchange(true)) {
return true;
}
return BlockerManager::Instance()->Subscribe<MessageT>(
this->role_attr_.channel_name(), this->role_attr_.qos_profile().depth(),
this->role_attr_.node_name(),
std::bind(&IntraReader<MessageT>::OnMessage, this,
std::placeholders::_1));
}
template <typename MessageT>
void IntraReader<MessageT>::Shutdown() {
if (!this->init_.exchange(false)) {
return;
}
BlockerManager::Instance()->Unsubscribe<MessageT>(
this->role_attr_.channel_name(), this->role_attr_.node_name());
}
template <typename MessageT>
void IntraReader<MessageT>::ClearData() {
auto blocker = BlockerManager::Instance()->GetBlocker<MessageT>(
this->role_attr_.channel_name());
if (blocker != nullptr) {
blocker->ClearObserved();
blocker->ClearPublished();
}
}
template <typename MessageT>
void IntraReader<MessageT>::Observe() {
auto blocker = BlockerManager::Instance()->GetBlocker<MessageT>(
this->role_attr_.channel_name());
if (blocker != nullptr) {
blocker->Observe();
}
}
template <typename MessageT>
bool IntraReader<MessageT>::Empty() const {
auto blocker = BlockerManager::Instance()->GetBlocker<MessageT>(
this->role_attr_.channel_name());
if (blocker != nullptr) {
return blocker->IsObservedEmpty();
}
return true;
}
template <typename MessageT>
bool IntraReader<MessageT>::HasReceived() const {
auto blocker = BlockerManager::Instance()->GetBlocker<MessageT>(
this->role_attr_.channel_name());
if (blocker != nullptr) {
return !blocker->IsPublishedEmpty();
}
return false;
}
template <typename MessageT>
void IntraReader<MessageT>::Enqueue(const std::shared_ptr<MessageT>& msg) {
BlockerManager::Instance()->Publish<MessageT>(this->role_attr_.channel_name(),
msg);
}
template <typename MessageT>
void IntraReader<MessageT>::SetHistoryDepth(const uint32_t& depth) {
auto blocker = BlockerManager::Instance()->GetBlocker<MessageT>(
this->role_attr_.channel_name());
if (blocker != nullptr) {
blocker->set_capacity(depth);
}
}
template <typename MessageT>
uint32_t IntraReader<MessageT>::GetHistoryDepth() const {
auto blocker = BlockerManager::Instance()->GetBlocker<MessageT>(
this->role_attr_.channel_name());
if (blocker != nullptr) {
return static_cast<uint32_t>(blocker->capacity());
}
return 0;
}
template <typename MessageT>
std::shared_ptr<MessageT> IntraReader<MessageT>::GetLatestObserved() const {
auto blocker = BlockerManager::Instance()->GetBlocker<MessageT>(
this->role_attr_.channel_name());
if (blocker != nullptr) {
return blocker->GetLatestObservedPtr();
}
return nullptr;
}
template <typename MessageT>
std::shared_ptr<MessageT> IntraReader<MessageT>::GetOldestObserved() const {
auto blocker = BlockerManager::Instance()->GetBlocker<MessageT>(
this->role_attr_.channel_name());
if (blocker != nullptr) {
return blocker->GetOldestObservedPtr();
}
return nullptr;
}
template <typename MessageT>
auto IntraReader<MessageT>::Begin() const -> Iterator {
auto blocker = BlockerManager::Instance()->GetBlocker<MessageT>(
this->role_attr_.channel_name());
ACHECK(blocker != nullptr);
return blocker->ObservedBegin();
}
template <typename MessageT>
auto IntraReader<MessageT>::End() const -> Iterator {
auto blocker = BlockerManager::Instance()->GetBlocker<MessageT>(
this->role_attr_.channel_name());
ACHECK(blocker != nullptr);
return blocker->ObservedEnd();
}
template <typename MessageT>
void IntraReader<MessageT>::OnMessage(const MessagePtr& msg_ptr) {
this->second_to_lastest_recv_time_sec_ = this->latest_recv_time_sec_;
this->latest_recv_time_sec_ = apollo::cyber::Time::Now().ToSecond();
if (msg_callback_ != nullptr) {
msg_callback_(msg_ptr);
}
}
} // namespace blocker
} // namespace cyber
} // namespace apollo
#endif // CYBER_BLOCKER_INTRA_READER_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/io/poller.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_IO_POLLER_H_
#define CYBER_IO_POLLER_H_
#include <atomic>
#include <list>
#include <memory>
#include <mutex>
#include <thread>
#include <unordered_map>
#include <vector>
#include "cyber/base/atomic_rw_lock.h"
#include "cyber/common/macros.h"
#include "cyber/io/poll_data.h"
namespace apollo {
namespace cyber {
namespace io {
class Poller {
public:
using RequestPtr = std::shared_ptr<PollRequest>;
using RequestMap = std::unordered_map<int, RequestPtr>;
using CtrlParamMap = std::unordered_map<int, PollCtrlParam>;
virtual ~Poller();
void Shutdown();
bool Register(const PollRequest& req);
bool Unregister(const PollRequest& req);
private:
bool Init();
void Clear();
void Poll(int timeout_ms);
void ThreadFunc();
void HandleChanges();
int GetTimeoutMs();
void Notify();
int epoll_fd_ = -1;
std::thread thread_;
std::atomic<bool> is_shutdown_ = {true};
int pipe_fd_[2] = {-1, -1};
std::mutex pipe_mutex_;
RequestMap requests_;
CtrlParamMap ctrl_params_;
base::AtomicRWLock poll_data_lock_;
const int kPollSize = 32;
const int kPollTimeoutMs = 100;
DECLARE_SINGLETON(Poller)
};
} // namespace io
} // namespace cyber
} // namespace apollo
#endif // CYBER_IO_POLLER_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/io/poller_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/io/poller.h"
#include <fcntl.h>
#include <unistd.h>
#include <thread>
#include "gtest/gtest.h"
#include "cyber/init.h"
namespace apollo {
namespace cyber {
namespace io {
TEST(PollerTest, operation) {
auto poller = Poller::Instance();
ASSERT_NE(poller, nullptr);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// invalid input
PollRequest request;
EXPECT_FALSE(poller->Register(request));
int pipe_fd[2] = {-1, -1};
ASSERT_EQ(pipe(pipe_fd), 0);
ASSERT_EQ(fcntl(pipe_fd[0], F_SETFL, O_NONBLOCK), 0);
ASSERT_EQ(fcntl(pipe_fd[1], F_SETFL, O_NONBLOCK), 0);
// invalid input, callback is nullptr
request.fd = pipe_fd[0];
request.events = EPOLLIN | EPOLLET;
request.timeout_ms = 0;
EXPECT_FALSE(poller->Register(request));
// timeout_ms is 0
PollResponse response(123);
request.callback = [&response](const PollResponse& rsp) { response = rsp; };
EXPECT_TRUE(poller->Register(request));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
EXPECT_EQ(response.events, 0);
// timeout_ms is 50
response.events = 123;
request.timeout_ms = 50;
EXPECT_TRUE(poller->Register(request));
std::this_thread::sleep_for(std::chrono::milliseconds(20));
EXPECT_EQ(response.events, 123);
std::this_thread::sleep_for(std::chrono::milliseconds(35));
EXPECT_EQ(response.events, 0);
// timeout_ms is 200
response.events = 123;
request.timeout_ms = 200;
EXPECT_TRUE(poller->Register(request));
std::this_thread::sleep_for(std::chrono::milliseconds(20));
EXPECT_EQ(response.events, 123);
char msg = 'C';
ssize_t res = 0;
int try_num = 3;
do {
--try_num;
res = write(pipe_fd[1], &msg, 1);
} while (res <= 0 && try_num >= 0);
std::this_thread::sleep_for(std::chrono::milliseconds(5));
EXPECT_NE(response.events & EPOLLIN, 0);
EXPECT_TRUE(poller->Unregister(request));
EXPECT_FALSE(poller->Unregister(request));
request.callback = nullptr;
EXPECT_FALSE(poller->Unregister(request));
request.fd = -1;
EXPECT_FALSE(poller->Unregister(request));
poller->Shutdown();
request.fd = pipe_fd[0];
request.events = EPOLLIN | EPOLLET;
request.timeout_ms = 0;
request.callback = [](const PollResponse&) {};
// poller has been shutdown
EXPECT_FALSE(poller->Register(request));
EXPECT_FALSE(poller->Unregister(request));
close(pipe_fd[0]);
close(pipe_fd[1]);
}
} // namespace io
} // namespace cyber
} // namespace apollo
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
apollo::cyber::Init(argv[0]);
return RUN_ALL_TESTS();
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/io/poller.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/io/poller.h"
#include <fcntl.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <csignal>
#include <cstring>
#include "cyber/common/log.h"
#include "cyber/scheduler/scheduler_factory.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
namespace io {
using base::AtomicRWLock;
using base::ReadLockGuard;
using base::WriteLockGuard;
Poller::Poller() {
if (!Init()) {
AERROR << "Poller init failed!";
Clear();
}
}
Poller::~Poller() { Shutdown(); }
void Poller::Shutdown() {
if (is_shutdown_.exchange(true)) {
return;
}
Clear();
}
bool Poller::Register(const PollRequest& req) {
if (is_shutdown_.load()) {
return false;
}
if (req.fd < 0 || req.callback == nullptr) {
AERROR << "input is invalid";
return false;
}
PollCtrlParam ctrl_param{};
ctrl_param.fd = req.fd;
ctrl_param.event.data.fd = req.fd;
ctrl_param.event.events = req.events;
{
WriteLockGuard<AtomicRWLock> lck(poll_data_lock_);
if (requests_.count(req.fd) == 0) {
ctrl_param.operation = EPOLL_CTL_ADD;
requests_[req.fd] = std::make_shared<PollRequest>();
} else {
ctrl_param.operation = EPOLL_CTL_MOD;
}
*requests_[req.fd] = req;
ctrl_params_[ctrl_param.fd] = ctrl_param;
}
Notify();
return true;
}
bool Poller::Unregister(const PollRequest& req) {
if (is_shutdown_.load()) {
return false;
}
if (req.fd < 0 || req.callback == nullptr) {
AERROR << "input is invalid";
return false;
}
{
WriteLockGuard<AtomicRWLock> lck(poll_data_lock_);
auto size = requests_.erase(req.fd);
if (size == 0) {
AERROR << "unregister failed, can't find fd: " << req.fd;
return false;
}
PollCtrlParam ctrl_param;
ctrl_param.operation = EPOLL_CTL_DEL;
ctrl_param.fd = req.fd;
ctrl_params_[ctrl_param.fd] = ctrl_param;
}
Notify();
return true;
}
bool Poller::Init() {
epoll_fd_ = epoll_create(kPollSize);
if (epoll_fd_ < 0) {
AERROR << "epoll create failed, " << strerror(errno);
return false;
}
// create pipe, and set nonblock
if (pipe(pipe_fd_) == -1) {
AERROR << "create pipe failed, " << strerror(errno);
return false;
}
if (fcntl(pipe_fd_[0], F_SETFL, O_NONBLOCK) == -1) {
AERROR << "set nonblock failed, " << strerror(errno);
return false;
}
if (fcntl(pipe_fd_[1], F_SETFL, O_NONBLOCK) == -1) {
AERROR << "set nonblock failed, " << strerror(errno);
return false;
}
// add pipe[0] to epoll
auto request = std::make_shared<PollRequest>();
request->fd = pipe_fd_[0];
request->events = EPOLLIN;
request->timeout_ms = -1;
request->callback = [this](const PollResponse&) {
char c = 0;
while (read(pipe_fd_[0], &c, 1) > 0) {
}
};
requests_[request->fd] = request;
PollCtrlParam ctrl_param{};
ctrl_param.operation = EPOLL_CTL_ADD;
ctrl_param.fd = pipe_fd_[0];
ctrl_param.event.data.fd = pipe_fd_[0];
ctrl_param.event.events = EPOLLIN;
ctrl_params_[ctrl_param.fd] = ctrl_param;
is_shutdown_.store(false);
thread_ = std::thread(&Poller::ThreadFunc, this);
scheduler::Instance()->SetInnerThreadAttr("io_poller", &thread_);
return true;
}
void Poller::Clear() {
if (thread_.joinable()) {
thread_.join();
}
if (epoll_fd_ >= 0) {
close(epoll_fd_);
epoll_fd_ = -1;
}
if (pipe_fd_[0] >= 0) {
close(pipe_fd_[0]);
pipe_fd_[0] = -1;
}
if (pipe_fd_[1] >= 0) {
close(pipe_fd_[1]);
pipe_fd_[1] = -1;
}
{
WriteLockGuard<AtomicRWLock> lck(poll_data_lock_);
requests_.clear();
ctrl_params_.clear();
}
}
void Poller::Poll(int timeout_ms) {
epoll_event evt[kPollSize];
auto before_time_ns = Time::Now().ToNanosecond();
int ready_num = epoll_wait(epoll_fd_, evt, kPollSize, timeout_ms);
auto after_time_ns = Time::Now().ToNanosecond();
int interval_ms =
static_cast<int>((after_time_ns - before_time_ns) / 1000000);
if (interval_ms == 0) {
interval_ms = 1;
}
std::unordered_map<int, PollResponse> responses;
{
ReadLockGuard<AtomicRWLock> lck(poll_data_lock_);
for (auto& item : requests_) {
auto& request = item.second;
if (ctrl_params_.count(request->fd) != 0) {
continue;
}
if (request->timeout_ms > 0) {
request->timeout_ms -= interval_ms;
if (request->timeout_ms < 0) {
request->timeout_ms = 0;
}
}
if (request->timeout_ms == 0) {
responses[item.first] = PollResponse();
request->timeout_ms = -1;
}
}
}
if (ready_num > 0) {
for (int i = 0; i < ready_num; ++i) {
int fd = evt[i].data.fd;
uint32_t events = evt[i].events;
responses[fd] = PollResponse(events);
}
}
for (auto& item : responses) {
int fd = item.first;
auto& response = item.second;
ReadLockGuard<AtomicRWLock> lck(poll_data_lock_);
auto search = requests_.find(fd);
if (search != requests_.end()) {
search->second->timeout_ms = -1;
search->second->callback(response);
}
}
if (ready_num < 0) {
if (errno != EINTR) {
AERROR << "epoll wait failed, " << strerror(errno);
}
}
}
void Poller::ThreadFunc() {
// block all signals in this thread
sigset_t signal_set;
sigfillset(&signal_set);
pthread_sigmask(SIG_BLOCK, &signal_set, nullptr);
while (!is_shutdown_.load()) {
HandleChanges();
int timeout_ms = GetTimeoutMs();
ADEBUG << "this poll timeout ms: " << timeout_ms;
Poll(timeout_ms);
}
}
void Poller::HandleChanges() {
CtrlParamMap local_params;
{
ReadLockGuard<AtomicRWLock> lck(poll_data_lock_);
if (ctrl_params_.empty()) {
return;
}
local_params.swap(ctrl_params_);
}
for (auto& pair : local_params) {
auto& item = pair.second;
ADEBUG << "epoll ctl, op[" << item.operation << "] fd[" << item.fd
<< "] events[" << item.event.events << "]";
if (epoll_ctl(epoll_fd_, item.operation, item.fd, &item.event) != 0 &&
errno != EBADF) {
AERROR << "epoll ctl failed, " << strerror(errno);
}
}
}
// min heap can be used to optimize
int Poller::GetTimeoutMs() {
int timeout_ms = kPollTimeoutMs;
ReadLockGuard<AtomicRWLock> lck(poll_data_lock_);
for (auto& item : requests_) {
auto& req = item.second;
if (req->timeout_ms >= 0 && req->timeout_ms < timeout_ms) {
timeout_ms = req->timeout_ms;
}
}
return timeout_ms;
}
void Poller::Notify() {
std::unique_lock<std::mutex> lock(pipe_mutex_, std::try_to_lock);
if (!lock.owns_lock()) {
return;
}
char msg = 'C';
if (write(pipe_fd_[1], &msg, 1) < 0) {
AWARN << "notify failed, " << strerror(errno);
}
}
} // namespace io
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/io/poll_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_IO_POLL_HANDLER_H_
#define CYBER_IO_POLL_HANDLER_H_
#include <atomic>
#include <memory>
#include "cyber/croutine/croutine.h"
#include "cyber/io/poll_data.h"
namespace apollo {
namespace cyber {
namespace io {
class PollHandler {
public:
explicit PollHandler(int fd);
virtual ~PollHandler() = default;
bool Block(int timeout_ms, bool is_read);
bool Unblock();
int fd() const { return fd_; }
void set_fd(int fd) { fd_ = fd; }
private:
bool Check(int timeout_ms);
void Fill(int timeout_ms, bool is_read);
void ResponseCallback(const PollResponse& rsp);
int fd_;
PollRequest request_;
PollResponse response_;
std::atomic<bool> is_read_;
std::atomic<bool> is_blocking_;
croutine::CRoutine* routine_;
};
} // namespace io
} // namespace cyber
} // namespace apollo
#endif // CYBER_IO_POLL_HANDLER_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/io/poll_handler.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/io/poll_handler.h"
#include "cyber/common/log.h"
#include "cyber/io/poller.h"
#include "cyber/scheduler/scheduler_factory.h"
namespace apollo {
namespace cyber {
namespace io {
using croutine::CRoutine;
using croutine::RoutineState;
PollHandler::PollHandler(int fd)
: fd_(fd), is_read_(false), is_blocking_(false), routine_(nullptr) {}
bool PollHandler::Block(int timeout_ms, bool is_read) {
if (!Check(timeout_ms)) {
return false;
}
if (is_blocking_.exchange(true)) {
AINFO << "poll handler is blocking.";
return false;
}
Fill(timeout_ms, is_read);
if (!Poller::Instance()->Register(request_)) {
is_blocking_.store(false);
return false;
}
routine_->Yield(RoutineState::IO_WAIT);
bool result = false;
uint32_t target_events = is_read ? EPOLLIN : EPOLLOUT;
if (response_.events & target_events) {
result = true;
}
is_blocking_.store(false);
return result;
}
bool PollHandler::Unblock() {
is_blocking_.store(false);
return Poller::Instance()->Unregister(request_);
}
bool PollHandler::Check(int timeout_ms) {
if (timeout_ms == 0) {
AINFO << "timeout[" << timeout_ms
<< "] must be larger than zero or less than zero.";
return false;
}
if (fd_ < 0) {
AERROR << "invalid fd[" << fd_ << "]";
return false;
}
routine_ = CRoutine::GetCurrentRoutine();
if (routine_ == nullptr) {
AERROR << "routine nullptr, please use IO in routine context.";
return false;
}
return true;
}
void PollHandler::Fill(int timeout_ms, bool is_read) {
is_read_.store(is_read);
request_.fd = fd_;
request_.events = EPOLLET | EPOLLONESHOT;
if (is_read) {
request_.events |= EPOLLIN;
} else {
request_.events |= EPOLLOUT;
}
request_.timeout_ms = timeout_ms;
request_.callback =
std::bind(&PollHandler::ResponseCallback, this, std::placeholders::_1);
}
void PollHandler::ResponseCallback(const PollResponse& rsp) {
if (!is_blocking_.load() || routine_ == nullptr) {
return;
}
response_ = rsp;
if (routine_->state() == RoutineState::IO_WAIT) {
scheduler::Instance()->NotifyTask(routine_->id());
}
}
} // namespace io
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/io/session.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_IO_SESSION_H_
#define CYBER_IO_SESSION_H_
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <memory>
#include "cyber/io/poll_handler.h"
namespace apollo {
namespace cyber {
namespace io {
class Session {
public:
using SessionPtr = std::shared_ptr<Session>;
using PollHandlerPtr = std::unique_ptr<PollHandler>;
Session();
explicit Session(int fd);
virtual ~Session() = default;
int Socket(int domain, int type, int protocol);
int Listen(int backlog);
int Bind(const struct sockaddr *addr, socklen_t addrlen);
SessionPtr Accept(struct sockaddr *addr, socklen_t *addrlen);
int Connect(const struct sockaddr *addr, socklen_t addrlen);
int Close();
// timeout_ms < 0, keep trying until the operation is successfully
// timeout_ms == 0, try once
// timeout_ms > 0, keep trying while there is still time left
ssize_t Recv(void *buf, size_t len, int flags, int timeout_ms = -1);
ssize_t RecvFrom(void *buf, size_t len, int flags, struct sockaddr *src_addr,
socklen_t *addrlen, int timeout_ms = -1);
ssize_t Send(const void *buf, size_t len, int flags, int timeout_ms = -1);
ssize_t SendTo(const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen,
int timeout_ms = -1);
ssize_t Read(void *buf, size_t count, int timeout_ms = -1);
ssize_t Write(const void *buf, size_t count, int timeout_ms = -1);
int fd() const { return fd_; }
private:
void set_fd(int fd) {
fd_ = fd;
poll_handler_->set_fd(fd);
}
int fd_;
PollHandlerPtr poll_handler_;
};
} // namespace io
} // namespace cyber
} // namespace apollo
#endif // CYBER_IO_SESSION_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/io/session.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/io/session.h"
#include "cyber/common/log.h"
namespace apollo {
namespace cyber {
namespace io {
Session::Session() : Session(-1) {}
Session::Session(int fd) : fd_(fd), poll_handler_(nullptr) {
poll_handler_.reset(new PollHandler(fd_));
}
int Session::Socket(int domain, int type, int protocol) {
if (fd_ != -1) {
AINFO << "session has hold a valid fd[" << fd_ << "]";
return -1;
}
int sock_fd = socket(domain, type | SOCK_NONBLOCK, protocol);
if (sock_fd != -1) {
set_fd(sock_fd);
}
return sock_fd;
}
int Session::Listen(int backlog) {
ACHECK(fd_ != -1);
return listen(fd_, backlog);
}
int Session::Bind(const struct sockaddr *addr, socklen_t addrlen) {
ACHECK(fd_ != -1);
ACHECK(addr != nullptr);
return bind(fd_, addr, addrlen);
}
auto Session::Accept(struct sockaddr *addr, socklen_t *addrlen) -> SessionPtr {
ACHECK(fd_ != -1);
int sock_fd = accept4(fd_, addr, addrlen, SOCK_NONBLOCK);
while (sock_fd == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
poll_handler_->Block(-1, true);
sock_fd = accept4(fd_, addr, addrlen, SOCK_NONBLOCK);
}
if (sock_fd == -1) {
return nullptr;
}
return std::make_shared<Session>(sock_fd);
}
int Session::Connect(const struct sockaddr *addr, socklen_t addrlen) {
ACHECK(fd_ != -1);
int optval;
socklen_t optlen = sizeof(optval);
int res = connect(fd_, addr, addrlen);
if (res == -1 && errno == EINPROGRESS) {
poll_handler_->Block(-1, false);
getsockopt(fd_, SOL_SOCKET, SO_ERROR, reinterpret_cast<void *>(&optval),
&optlen);
if (optval == 0) {
res = 0;
} else {
errno = optval;
}
}
return res;
}
int Session::Close() {
ACHECK(fd_ != -1);
poll_handler_->Unblock();
int res = close(fd_);
fd_ = -1;
return res;
}
ssize_t Session::Recv(void *buf, size_t len, int flags, int timeout_ms) {
ACHECK(buf != nullptr);
ACHECK(fd_ != -1);
ssize_t nbytes = recv(fd_, buf, len, flags);
if (timeout_ms == 0) {
return nbytes;
}
while (nbytes == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (poll_handler_->Block(timeout_ms, true)) {
nbytes = recv(fd_, buf, len, flags);
}
if (timeout_ms > 0) {
break;
}
}
return nbytes;
}
ssize_t Session::RecvFrom(void *buf, size_t len, int flags,
struct sockaddr *src_addr, socklen_t *addrlen,
int timeout_ms) {
ACHECK(buf != nullptr);
ACHECK(fd_ != -1);
ssize_t nbytes = recvfrom(fd_, buf, len, flags, src_addr, addrlen);
if (timeout_ms == 0) {
return nbytes;
}
while (nbytes == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (poll_handler_->Block(timeout_ms, true)) {
nbytes = recvfrom(fd_, buf, len, flags, src_addr, addrlen);
}
if (timeout_ms > 0) {
break;
}
}
return nbytes;
}
ssize_t Session::Send(const void *buf, size_t len, int flags, int timeout_ms) {
ACHECK(buf != nullptr);
ACHECK(fd_ != -1);
ssize_t nbytes = send(fd_, buf, len, flags);
if (timeout_ms == 0) {
return nbytes;
}
while ((nbytes == -1) && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (poll_handler_->Block(timeout_ms, false)) {
nbytes = send(fd_, buf, len, flags);
}
if (timeout_ms > 0) {
break;
}
}
return nbytes;
}
ssize_t Session::SendTo(const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen,
int timeout_ms) {
ACHECK(buf != nullptr);
ACHECK(dest_addr != nullptr);
ACHECK(fd_ != -1);
ssize_t nbytes = sendto(fd_, buf, len, flags, dest_addr, addrlen);
if (timeout_ms == 0) {
return nbytes;
}
while ((nbytes == -1) && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (poll_handler_->Block(timeout_ms, false)) {
nbytes = sendto(fd_, buf, len, flags, dest_addr, addrlen);
}
if (timeout_ms > 0) {
break;
}
}
return nbytes;
}
ssize_t Session::Read(void *buf, size_t count, int timeout_ms) {
ACHECK(buf != nullptr);
ACHECK(fd_ != -1);
ssize_t nbytes = read(fd_, buf, count);
if (timeout_ms == 0) {
return nbytes;
}
while ((nbytes == -1) && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (poll_handler_->Block(timeout_ms, true)) {
nbytes = read(fd_, buf, count);
}
if (timeout_ms > 0) {
break;
}
}
return nbytes;
}
ssize_t Session::Write(const void *buf, size_t count, int timeout_ms) {
ACHECK(buf != nullptr);
ACHECK(fd_ != -1);
ssize_t nbytes = write(fd_, buf, count);
if (timeout_ms == 0) {
return nbytes;
}
while ((nbytes == -1) && (errno == EAGAIN || errno == EWOULDBLOCK)) {
if (poll_handler_->Block(timeout_ms, false)) {
nbytes = write(fd_, buf, count);
}
if (timeout_ms > 0) {
break;
}
}
return nbytes;
}
} // namespace io
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/io/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "cyber_io_hdrs",
srcs = glob([
"*.h",
]),
)
cc_library(
name = "io",
deps = [
":poll_data",
":poll_handler",
":poller",
":session",
],
alwayslink = True,
)
cc_library(
name = "poll_data",
hdrs = ["poll_data.h"],
)
cc_library(
name = "poll_handler",
srcs = ["poll_handler.cc"],
hdrs = ["poll_handler.h"],
deps = [
":poll_data",
":poller",
"//cyber/common:log",
"//cyber/croutine",
],
)
cc_library(
name = "poller",
srcs = ["poller.cc"],
hdrs = ["poller.h"],
deps = [
":poll_data",
"//cyber/base:atomic_rw_lock",
"//cyber/common:log",
"//cyber/common:macros",
"//cyber/scheduler:scheduler_factory",
"//cyber/time",
],
)
cc_test(
name = "poller_test",
size = "small",
srcs = ["poller_test.cc"],
deps = [
":poller",
"//cyber:cyber_core",
"@com_google_googletest//:gtest",
],
)
cc_library(
name = "session",
srcs = ["session.cc"],
hdrs = ["session.h"],
deps = [
":poll_handler",
"//cyber/common:log",
],
alwayslink = True,
)
cc_binary(
name = "tcp_echo_client",
srcs = ["example/tcp_echo_client.cc"],
deps = [
"//cyber:cyber_core",
],
)
cc_binary(
name = "tcp_echo_server",
srcs = ["example/tcp_echo_server.cc"],
deps = [
"//cyber:cyber_core",
],
)
cc_binary(
name = "udp_echo_client",
srcs = ["example/udp_echo_client.cc"],
deps = [
"//cyber:cyber_core",
],
)
cc_binary(
name = "udp_echo_server",
srcs = ["example/udp_echo_server.cc"],
deps = [
"//cyber:cyber_core",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/io/poll_data.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_IO_POLL_DATA_H_
#define CYBER_IO_POLL_DATA_H_
#include <sys/epoll.h>
#include <cstdint>
#include <functional>
namespace apollo {
namespace cyber {
namespace io {
struct PollResponse {
explicit PollResponse(uint32_t e = 0) : events(e) {}
uint32_t events;
};
struct PollRequest {
int fd = -1;
uint32_t events = 0;
int timeout_ms = -1;
std::function<void(const PollResponse&)> callback = nullptr;
};
struct PollCtrlParam {
int operation;
int fd;
epoll_event event;
};
} // namespace io
} // namespace cyber
} // namespace apollo
#endif // CYBER_IO_POLL_DATA_H_
| 0
|
apollo_public_repos/apollo/cyber/io
|
apollo_public_repos/apollo/cyber/io/example/tcp_echo_server.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 <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include "cyber/cyber.h"
#include "cyber/init.h"
#include "cyber/io/session.h"
#include "cyber/scheduler/scheduler_factory.h"
#include "cyber/task/task.h"
#include "cyber/time/time.h"
using apollo::cyber::Time;
using apollo::cyber::io::Session;
void Echo(const std::shared_ptr<Session>& session) {
std::vector<char> recv_buffer(2049);
int nbytes = 0;
while ((nbytes = static_cast<int>(
session->Recv(recv_buffer.data(), recv_buffer.size(), 0))) > 0) {
session->Write(recv_buffer.data(), nbytes);
}
if (nbytes == 0) {
std::cout << "client has been closed." << std::endl;
session->Close();
}
if (nbytes < 0) {
std::cout << "receive from client failed." << std::endl;
session->Close();
}
}
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " <server port>" << std::endl;
return -1;
}
apollo::cyber::Init(argv[0]);
uint16_t server_port = static_cast<uint16_t>(atoi(argv[1]));
apollo::cyber::scheduler::Instance()->CreateTask(
[&server_port]() {
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htons(INADDR_ANY);
server_addr.sin_port = htons(server_port);
Session session;
session.Socket(AF_INET, SOCK_STREAM, 0);
if (session.Bind((struct sockaddr*)&server_addr, sizeof(server_addr)) <
0) {
std::cout << "bind to port[" << server_port << "] failed."
<< std::endl;
return;
}
session.Listen(10);
auto conn_session = session.Accept((struct sockaddr*)nullptr, nullptr);
std::cout << "accepted" << std::endl;
auto routine_name =
"connected session" + std::to_string(Time::Now().ToNanosecond());
apollo::cyber::scheduler::Instance()->CreateTask(
std::bind(Echo, conn_session), routine_name);
},
"echo_server");
apollo::cyber::WaitForShutdown();
return 0;
}
| 0
|
apollo_public_repos/apollo/cyber/io
|
apollo_public_repos/apollo/cyber/io/example/udp_echo_client.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 <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include "cyber/cyber.h"
#include "cyber/init.h"
#include "cyber/io/session.h"
#include "cyber/scheduler/scheduler_factory.h"
using apollo::cyber::io::Session;
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " <server port>" << std::endl;
return -1;
}
apollo::cyber::Init(argv[0]);
int server_port = atoi(argv[1]);
apollo::cyber::scheduler::Instance()->CreateTask(
[&server_port]() {
struct sockaddr_in server_addr;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons((uint16_t)server_port);
std::string user_input;
std::vector<char> server_reply(2049);
ssize_t nbytes = 0;
uint32_t count = 0;
Session session;
session.Socket(AF_INET, SOCK_DGRAM, 0);
if (session.Connect((struct sockaddr*)&server_addr,
sizeof(server_addr)) < 0) {
std::cout << "connect to server failed, " << strerror(errno)
<< std::endl;
return;
}
while (true) {
count = 0;
std::cout << "please enter a message (enter Ctrl+C to exit):"
<< std::endl;
std::getline(std::cin, user_input);
if (!apollo::cyber::OK()) {
break;
}
if (user_input.empty()) {
continue;
}
if (session.Send(user_input.c_str(), user_input.length(), 0) < 0) {
std::cout << "send message failed." << std::endl;
return;
}
while ((nbytes = session.Recv(server_reply.data(),
server_reply.size(), 0)) > 0) {
for (auto itr = server_reply.begin();
itr < server_reply.begin() + nbytes; ++itr) {
std::cout << *itr;
}
count += (uint32_t)nbytes;
if (count >= user_input.length()) {
break;
}
}
if (nbytes == 0) {
std::cout << "server has been closed." << std::endl;
session.Close();
return;
}
if (nbytes < 0) {
std::cout << "receive message from server failed." << std::endl;
session.Close();
return;
}
std::cout << std::endl;
}
},
"echo_client");
apollo::cyber::WaitForShutdown();
return 0;
}
| 0
|
apollo_public_repos/apollo/cyber/io
|
apollo_public_repos/apollo/cyber/io/example/tcp_echo_client.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 <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include "cyber/cyber.h"
#include "cyber/init.h"
#include "cyber/io/session.h"
#include "cyber/scheduler/scheduler.h"
using apollo::cyber::io::Session;
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " <server port>" << std::endl;
return -1;
}
apollo::cyber::Init(argv[0]);
int server_port = atoi(argv[1]);
apollo::cyber::scheduler::Instance()->CreateTask(
[&server_port]() {
struct sockaddr_in server_addr;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons((uint16_t)server_port);
std::string user_input;
std::vector<char> server_reply(2049);
ssize_t nbytes = 0;
uint32_t count = 0;
Session session;
session.Socket(AF_INET, SOCK_STREAM, 0);
if (session.Connect((struct sockaddr*)&server_addr,
sizeof(server_addr)) < 0) {
std::cout << "connect to server failed, " << strerror(errno)
<< std::endl;
return;
}
while (true) {
count = 0;
std::cout << "please enter a message (enter Ctrl+C to exit):"
<< std::endl;
std::getline(std::cin, user_input);
if (!apollo::cyber::OK()) {
break;
}
if (user_input.empty()) {
continue;
}
if (session.Send(user_input.c_str(), user_input.length(), 0) < 0) {
std::cout << "send message failed." << std::endl;
return;
}
while ((nbytes = session.Recv(server_reply.data(),
server_reply.size(), 0)) > 0) {
for (auto itr = server_reply.begin();
itr < server_reply.begin() + nbytes; ++itr) {
std::cout << *itr;
}
count += (uint32_t)nbytes;
if (count >= user_input.length()) {
break;
}
}
if (nbytes == 0) {
std::cout << "server has been closed." << std::endl;
session.Close();
return;
}
if (nbytes < 0) {
std::cout << "receive message from server failed." << std::endl;
session.Close();
return;
}
std::cout << std::endl;
}
},
"echo_client");
apollo::cyber::WaitForShutdown();
return 0;
}
| 0
|
apollo_public_repos/apollo/cyber/io
|
apollo_public_repos/apollo/cyber/io/example/udp_echo_server.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 <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include "cyber/cyber.h"
#include "cyber/init.h"
#include "cyber/io/session.h"
#include "cyber/scheduler/scheduler_factory.h"
#include "cyber/task/task.h"
#include "cyber/time/time.h"
using apollo::cyber::Time;
using apollo::cyber::io::Session;
void Echo(const std::shared_ptr<Session>& session) {
struct sockaddr_in client_addr;
std::vector<char> recv_buffer(2049);
int nbytes = 0;
socklen_t sock_len = static_cast<socklen_t>(sizeof(client_addr));
while (true) {
nbytes = static_cast<int>(
session->RecvFrom(recv_buffer.data(), recv_buffer.size(), 0,
(struct sockaddr*)&client_addr, &sock_len));
if (nbytes < 0) {
std::cout << "recv from client failed." << std::endl;
continue;
}
session->SendTo(recv_buffer.data(), nbytes, 0,
(const struct sockaddr*)&client_addr, sock_len);
}
}
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " <server port>" << std::endl;
return -1;
}
apollo::cyber::Init(argv[0]);
uint16_t server_port = static_cast<uint16_t>(atoi(argv[1]));
apollo::cyber::scheduler::Instance()->CreateTask(
[&server_port]() {
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htons(INADDR_ANY);
server_addr.sin_port = htons(server_port);
auto session = std::make_shared<Session>();
session->Socket(AF_INET, SOCK_DGRAM, 0);
if (session->Bind((struct sockaddr*)&server_addr, sizeof(server_addr)) <
0) {
std::cout << "bind to port[" << server_port << "] failed."
<< std::endl;
return;
}
Echo(session);
session->Close();
},
"echo_server");
apollo::cyber::WaitForShutdown();
return 0;
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/scheduler.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Vesched_infoon 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/scheduler/scheduler.h"
#include <sched.h>
#include <utility>
#include "cyber/common/environment.h"
#include "cyber/common/file.h"
#include "cyber/common/global_data.h"
#include "cyber/common/util.h"
#include "cyber/data/data_visitor.h"
#include "cyber/scheduler/processor.h"
#include "cyber/scheduler/processor_context.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::common::GlobalData;
bool Scheduler::CreateTask(const RoutineFactory& factory,
const std::string& name) {
return CreateTask(factory.create_routine(), name, factory.GetDataVisitor());
}
bool Scheduler::CreateTask(std::function<void()>&& func,
const std::string& name,
std::shared_ptr<DataVisitorBase> visitor) {
if (cyber_unlikely(stop_.load())) {
ADEBUG << "scheduler is stoped, cannot create task!";
return false;
}
auto task_id = GlobalData::RegisterTaskName(name);
auto cr = std::make_shared<CRoutine>(func);
cr->set_id(task_id);
cr->set_name(name);
AINFO << "create croutine: " << name;
if (!DispatchTask(cr)) {
return false;
}
if (visitor != nullptr) {
visitor->RegisterNotifyCallback([this, task_id]() {
if (cyber_unlikely(stop_.load())) {
return;
}
this->NotifyProcessor(task_id);
});
}
return true;
}
bool Scheduler::NotifyTask(uint64_t crid) {
if (cyber_unlikely(stop_.load())) {
return true;
}
return NotifyProcessor(crid);
}
void Scheduler::ProcessLevelResourceControl() {
std::vector<int> cpus;
ParseCpuset(process_level_cpuset_, &cpus);
cpu_set_t set;
CPU_ZERO(&set);
for (const auto cpu : cpus) {
CPU_SET(cpu, &set);
}
pthread_setaffinity_np(pthread_self(), sizeof(set), &set);
}
void Scheduler::SetInnerThreadAttr(const std::string& name, std::thread* thr) {
if (thr != nullptr && inner_thr_confs_.find(name) != inner_thr_confs_.end()) {
auto th_conf = inner_thr_confs_[name];
auto cpuset = th_conf.cpuset();
std::vector<int> cpus;
ParseCpuset(cpuset, &cpus);
SetSchedAffinity(thr, cpus, "range");
SetSchedPolicy(thr, th_conf.policy(), th_conf.prio());
}
}
void Scheduler::CheckSchedStatus() {
std::string snap_info;
auto now = Time::Now().ToNanosecond();
for (auto processor : processors_) {
auto snap = processor->ProcSnapshot();
if (snap->execute_start_time.load()) {
auto execute_time = (now - snap->execute_start_time.load()) / 1000000;
snap_info.append(std::to_string(snap->processor_id.load()))
.append(":")
.append(snap->routine_name)
.append(":")
.append(std::to_string(execute_time));
} else {
snap_info.append(std::to_string(snap->processor_id.load()))
.append(":idle");
}
snap_info.append(", ");
}
snap_info.append("timestamp: ").append(std::to_string(now));
AINFO << snap_info;
snap_info.clear();
}
void Scheduler::Shutdown() {
if (cyber_unlikely(stop_.exchange(true))) {
return;
}
for (auto& ctx : pctxs_) {
ctx->Shutdown();
}
std::vector<uint64_t> cr_list;
{
ReadLockGuard<AtomicRWLock> lk(id_cr_lock_);
for (auto& cr : id_cr_) {
cr_list.emplace_back(cr.second->id());
}
}
for (auto& id : cr_list) {
RemoveCRoutine(id);
}
for (auto& processor : processors_) {
processor->Stop();
}
processors_.clear();
pctxs_.clear();
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/scheduler_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.
*****************************************************************************/
#ifndef CYBER_SCHEDULER_SCHEDULER_FACTORY_H_
#define CYBER_SCHEDULER_SCHEDULER_FACTORY_H_
#include "cyber/scheduler/scheduler_factory.h"
#include <atomic>
#include <string>
#include <unordered_map>
#include "cyber/common/environment.h"
#include "cyber/common/file.h"
#include "cyber/common/global_data.h"
#include "cyber/common/util.h"
#include "cyber/scheduler/policy/scheduler_choreography.h"
#include "cyber/scheduler/policy/scheduler_classic.h"
#include "cyber/scheduler/scheduler.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::common::GetAbsolutePath;
using apollo::cyber::common::GetProtoFromFile;
using apollo::cyber::common::GlobalData;
using apollo::cyber::common::PathExists;
using apollo::cyber::common::WorkRoot;
namespace {
std::atomic<Scheduler*> instance = {nullptr};
std::mutex mutex;
} // namespace
Scheduler* Instance() {
Scheduler* obj = instance.load(std::memory_order_acquire);
if (obj == nullptr) {
std::lock_guard<std::mutex> lock(mutex);
obj = instance.load(std::memory_order_relaxed);
if (obj == nullptr) {
std::string policy("classic");
std::string conf("conf/");
conf.append(GlobalData::Instance()->ProcessGroup()).append(".conf");
auto cfg_file = GetAbsolutePath(WorkRoot(), conf);
apollo::cyber::proto::CyberConfig cfg;
if (PathExists(cfg_file) && GetProtoFromFile(cfg_file, &cfg)) {
policy = cfg.scheduler_conf().policy();
} else {
AWARN << "Scheduler conf named " << cfg_file
<< " not found, use default.";
}
if (!policy.compare("classic")) {
obj = new SchedulerClassic();
} else if (!policy.compare("choreography")) {
obj = new SchedulerChoreography();
} else {
AWARN << "Invalid scheduler policy: " << policy;
obj = new SchedulerClassic();
}
instance.store(obj, std::memory_order_release);
}
}
return obj;
}
void CleanUp() {
Scheduler* obj = instance.load(std::memory_order_acquire);
if (obj != nullptr) {
obj->Shutdown();
}
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
#endif // CYBER_SCHEDULER_SCHEDULER_FACTORY_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/processor.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_SCHEDULER_PROCESSOR_H_
#define CYBER_SCHEDULER_PROCESSOR_H_
#include <atomic>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "cyber/proto/scheduler_conf.pb.h"
#include "cyber/croutine/croutine.h"
#include "cyber/scheduler/processor_context.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using croutine::CRoutine;
struct Snapshot {
std::atomic<uint64_t> execute_start_time = {0};
std::atomic<pid_t> processor_id = {0};
std::string routine_name;
};
class Processor {
public:
Processor();
virtual ~Processor();
void Run();
void Stop();
void BindContext(const std::shared_ptr<ProcessorContext>& context);
std::thread* Thread() { return &thread_; }
std::atomic<pid_t>& Tid();
std::shared_ptr<Snapshot> ProcSnapshot() { return snap_shot_; }
private:
std::shared_ptr<ProcessorContext> context_;
std::condition_variable cv_ctx_;
std::once_flag thread_flag_;
std::mutex mtx_ctx_;
std::thread thread_;
std::atomic<pid_t> tid_{-1};
std::atomic<bool> running_{false};
std::shared_ptr<Snapshot> snap_shot_ = std::make_shared<Snapshot>();
};
} // namespace scheduler
} // namespace cyber
} // namespace apollo
#endif // CYBER_SCHEDULER_PROCESSOR_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/scheduler.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_SCHEDULER_SCHEDULER_H_
#define CYBER_SCHEDULER_SCHEDULER_H_
#include <unistd.h>
#include <atomic>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include "cyber/proto/choreography_conf.pb.h"
#include "cyber/base/atomic_hash_map.h"
#include "cyber/base/atomic_rw_lock.h"
#include "cyber/common/log.h"
#include "cyber/common/macros.h"
#include "cyber/common/types.h"
#include "cyber/croutine/croutine.h"
#include "cyber/croutine/routine_factory.h"
#include "cyber/scheduler/common/mutex_wrapper.h"
#include "cyber/scheduler/common/pin_thread.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::base::AtomicHashMap;
using apollo::cyber::base::AtomicRWLock;
using apollo::cyber::base::ReadLockGuard;
using apollo::cyber::croutine::CRoutine;
using apollo::cyber::croutine::RoutineFactory;
using apollo::cyber::data::DataVisitorBase;
using apollo::cyber::proto::InnerThread;
class Processor;
class ProcessorContext;
class Scheduler {
public:
virtual ~Scheduler() {}
static Scheduler* Instance();
bool CreateTask(const RoutineFactory& factory, const std::string& name);
bool CreateTask(std::function<void()>&& func, const std::string& name,
std::shared_ptr<DataVisitorBase> visitor = nullptr);
bool NotifyTask(uint64_t crid);
void Shutdown();
uint32_t TaskPoolSize() { return task_pool_size_; }
virtual bool RemoveTask(const std::string& name) = 0;
void ProcessLevelResourceControl();
void SetInnerThreadAttr(const std::string& name, std::thread* thr);
virtual bool DispatchTask(const std::shared_ptr<CRoutine>&) = 0;
virtual bool NotifyProcessor(uint64_t crid) = 0;
virtual bool RemoveCRoutine(uint64_t crid) = 0;
void CheckSchedStatus();
void SetInnerThreadConfs(
const std::unordered_map<std::string, InnerThread>& confs) {
inner_thr_confs_ = confs;
}
protected:
Scheduler() : stop_(false) {}
AtomicRWLock id_cr_lock_;
AtomicHashMap<uint64_t, MutexWrapper*> id_map_mutex_;
std::mutex cr_wl_mtx_;
std::unordered_map<uint64_t, std::shared_ptr<CRoutine>> id_cr_;
std::vector<std::shared_ptr<ProcessorContext>> pctxs_;
std::vector<std::shared_ptr<Processor>> processors_;
std::unordered_map<std::string, InnerThread> inner_thr_confs_;
std::string process_level_cpuset_;
uint32_t proc_num_ = 0;
uint32_t task_pool_size_ = 0;
std::atomic<bool> stop_;
};
} // namespace scheduler
} // namespace cyber
} // namespace apollo
#endif // CYBER_SCHEDULER_SCHEDULER_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/processor_context.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/scheduler/processor_context.h"
namespace apollo {
namespace cyber {
namespace scheduler {
void ProcessorContext::Shutdown() { stop_.store(true); }
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/processor_context.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_SCHEDULER_POLICY_PROCESSOR_CONTEXT_H_
#define CYBER_SCHEDULER_POLICY_PROCESSOR_CONTEXT_H_
#include <limits>
#include <memory>
#include <mutex>
#include "cyber/base/macros.h"
#include "cyber/croutine/croutine.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using croutine::CRoutine;
class ProcessorContext {
public:
virtual void Shutdown();
virtual std::shared_ptr<CRoutine> NextRoutine() = 0;
virtual void Wait() = 0;
protected:
std::atomic<bool> stop_{false};
};
} // namespace scheduler
} // namespace cyber
} // namespace apollo
#endif // CYBER_SCHEDULER_PROCESSOR_CONTEXT_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/scheduler_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_SCHEDULER_SCHEDULER_FACTORY_H_
#define CYBER_SCHEDULER_SCHEDULER_FACTORY_H_
#include "cyber/common/environment.h"
#include "cyber/common/file.h"
#include "cyber/common/global_data.h"
#include "cyber/common/util.h"
#include "cyber/scheduler/policy/scheduler_choreography.h"
#include "cyber/scheduler/policy/scheduler_classic.h"
#include "cyber/scheduler/scheduler.h"
namespace apollo {
namespace cyber {
namespace scheduler {
Scheduler* Instance();
void CleanUp();
} // namespace scheduler
} // namespace cyber
} // namespace apollo
#endif // CYBER_SCHEDULER_SCHEDULER_FACTORY_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/scheduler_classic_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/scheduler/policy/scheduler_classic.h"
#include "gtest/gtest.h"
#include "cyber/base/for_each.h"
#include "cyber/common/global_data.h"
#include "cyber/cyber.h"
#include "cyber/scheduler/policy/classic_context.h"
#include "cyber/scheduler/processor.h"
#include "cyber/scheduler/scheduler_factory.h"
#include "cyber/task/task.h"
namespace apollo {
namespace cyber {
namespace scheduler {
void func() {}
TEST(SchedulerClassicTest, classic) {
auto processor = std::make_shared<Processor>();
auto ctx = std::make_shared<ClassicContext>();
processor->BindContext(ctx);
std::vector<std::future<void>> res;
// test single routine
auto future = Async([]() {
FOR_EACH(i, 0, 20) { cyber::SleepFor(std::chrono::milliseconds(i)); }
AINFO << "Finish task: single";
});
future.get();
// test multiple routine
FOR_EACH(i, 0, 20) {
res.emplace_back(Async([i]() {
FOR_EACH(time, 0, 30) { cyber::SleepFor(std::chrono::milliseconds(i)); }
}));
AINFO << "Finish task: " << i;
};
for (auto& future : res) {
future.wait_for(std::chrono::milliseconds(1000));
}
res.clear();
ctx->Shutdown();
processor->Stop();
}
TEST(SchedulerClassicTest, sched_classic) {
// read example_sched_classic.conf
GlobalData::Instance()->SetProcessGroup("example_sched_classic");
auto sched1 = dynamic_cast<SchedulerClassic*>(scheduler::Instance());
std::shared_ptr<CRoutine> cr = std::make_shared<CRoutine>(func);
auto task_id = GlobalData::RegisterTaskName("ABC");
cr->set_id(task_id);
cr->set_name("ABC");
EXPECT_TRUE(sched1->DispatchTask(cr));
// dispatch the same task
EXPECT_FALSE(sched1->DispatchTask(cr));
EXPECT_TRUE(sched1->RemoveTask("ABC"));
std::shared_ptr<CRoutine> cr1 = std::make_shared<CRoutine>(func);
cr1->set_id(GlobalData::RegisterTaskName("xxxxxx"));
cr1->set_name("xxxxxx");
EXPECT_TRUE(sched1->DispatchTask(cr1));
auto t = std::thread(func);
sched1->SetInnerThreadAttr("shm", &t);
if (t.joinable()) {
t.join();
}
sched1->Shutdown();
GlobalData::Instance()->SetProcessGroup("not_exist_sched");
auto sched2 = dynamic_cast<SchedulerClassic*>(scheduler::Instance());
std::shared_ptr<CRoutine> cr2 = std::make_shared<CRoutine>(func);
cr2->set_id(GlobalData::RegisterTaskName("sched2"));
cr2->set_name("sched2");
EXPECT_TRUE(sched2->DispatchTask(cr2));
sched2->Shutdown();
GlobalData::Instance()->SetProcessGroup("dreamview_sched");
auto sched3 = dynamic_cast<SchedulerClassic*>(scheduler::Instance());
std::shared_ptr<CRoutine> cr3 = std::make_shared<CRoutine>(func);
cr3->set_id(GlobalData::RegisterTaskName("sched3"));
cr3->set_name("sched3");
EXPECT_TRUE(sched3->DispatchTask(cr3));
sched3->Shutdown();
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
apollo::cyber::Init(argv[0]);
auto res = RUN_ALL_TESTS();
apollo::cyber::Clear();
return res;
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/processor.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/scheduler/processor.h"
#include <sched.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <chrono>
#include "cyber/common/global_data.h"
#include "cyber/common/log.h"
#include "cyber/croutine/croutine.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::common::GlobalData;
Processor::Processor() { running_.store(true); }
Processor::~Processor() { Stop(); }
void Processor::Run() {
tid_.store(static_cast<int>(syscall(SYS_gettid)));
AINFO << "processor_tid: " << tid_;
snap_shot_->processor_id.store(tid_);
while (cyber_likely(running_.load())) {
if (cyber_likely(context_ != nullptr)) {
auto croutine = context_->NextRoutine();
if (croutine) {
snap_shot_->execute_start_time.store(cyber::Time::Now().ToNanosecond());
snap_shot_->routine_name = croutine->name();
croutine->Resume();
croutine->Release();
} else {
snap_shot_->execute_start_time.store(0);
context_->Wait();
}
} else {
std::unique_lock<std::mutex> lk(mtx_ctx_);
cv_ctx_.wait_for(lk, std::chrono::milliseconds(10));
}
}
}
void Processor::Stop() {
if (!running_.exchange(false)) {
return;
}
if (context_) {
context_->Shutdown();
}
cv_ctx_.notify_one();
if (thread_.joinable()) {
thread_.join();
}
}
void Processor::BindContext(const std::shared_ptr<ProcessorContext>& context) {
context_ = context;
std::call_once(thread_flag_,
[this]() { thread_ = std::thread(&Processor::Run, this); });
}
std::atomic<pid_t>& Processor::Tid() {
while (tid_.load() == -1) {
cpu_relax();
}
return tid_;
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "cyber_scheduler_hdrs",
srcs = glob([
"*.h",
"**/*.h"
]),
)
cc_library(
name = "processor",
srcs = ["processor.cc"],
hdrs = ["processor.h"],
deps = [
"//cyber/data",
"//cyber/scheduler:processor_context",
],
)
cc_library(
name = "processor_context",
srcs = ["processor_context.cc"],
hdrs = ["processor_context.h"],
deps = [
"//cyber/croutine",
"//cyber/data",
],
)
cc_library(
name = "scheduler",
srcs = ["scheduler.cc"],
hdrs = ["scheduler.h"],
deps = [
"//cyber/croutine",
"//cyber/scheduler:mutex_wrapper",
"//cyber/scheduler:pin_thread",
"//cyber/scheduler:processor",
],
)
cc_library(
name = "mutex_wrapper",
hdrs = ["common/mutex_wrapper.h"],
)
cc_library(
name = "cv_wrapper",
hdrs = ["common/cv_wrapper.h"],
)
cc_library(
name = "pin_thread",
srcs = ["common/pin_thread.cc"],
hdrs = ["common/pin_thread.h"],
deps = [
"//cyber/common:log",
],
)
cc_library(
name = "scheduler_factory",
srcs = ["scheduler_factory.cc"],
hdrs = ["scheduler_factory.h"],
deps = [
"//cyber/proto:component_conf_cc_proto",
"//cyber/scheduler:scheduler_choreography",
"//cyber/scheduler:scheduler_classic",
],
)
cc_library(
name = "scheduler_choreography",
srcs = ["policy/scheduler_choreography.cc"],
hdrs = ["policy/scheduler_choreography.h"],
deps = [
"//cyber/scheduler",
"//cyber/scheduler:choreography_context",
"//cyber/scheduler:classic_context",
],
)
cc_library(
name = "scheduler_classic",
srcs = ["policy/scheduler_classic.cc"],
hdrs = ["policy/scheduler_classic.h"],
deps = [
"//cyber/scheduler",
"//cyber/scheduler:classic_context",
],
)
cc_library(
name = "choreography_context",
srcs = ["policy/choreography_context.cc"],
hdrs = ["policy/choreography_context.h"],
deps = [
"//cyber/croutine",
"//cyber/proto:choreography_conf_cc_proto",
"//cyber/scheduler:processor",
],
)
cc_library(
name = "classic_context",
srcs = ["policy/classic_context.cc"],
hdrs = ["policy/classic_context.h"],
deps = [
"//cyber/croutine",
"//cyber/proto:classic_conf_cc_proto",
"//cyber/scheduler:cv_wrapper",
"//cyber/scheduler:mutex_wrapper",
"//cyber/scheduler:processor",
],
)
cc_test(
name = "scheduler_test",
size = "small",
srcs = ["scheduler_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "scheduler_classic_test",
size = "small",
srcs = ["scheduler_classic_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "scheduler_choreo_test",
size = "small",
srcs = ["scheduler_choreo_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "processor_test",
size = "small",
srcs = ["processor_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "pin_thread_test",
size = "small",
srcs = ["common/pin_thread_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/processor_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/scheduler/processor.h"
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "cyber/cyber.h"
#include "cyber/scheduler/common/pin_thread.h"
#include "cyber/scheduler/policy/choreography_context.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using scheduler::ChoreographyContext;
using scheduler::Processor;
TEST(ProcessorTest, all) {
auto proc = std::make_shared<Processor>();
auto context = std::make_shared<ChoreographyContext>();
proc->BindContext(context);
std::string affinity = "1to1";
std::vector<int> cpuset;
cpuset.emplace_back(0);
SetSchedAffinity(proc->Thread(), cpuset, affinity, 0);
SetSchedPolicy(proc->Thread(), "SCHED_OTHER", 0, proc->Tid());
auto proc1 = std::make_shared<Processor>();
auto context1 = std::make_shared<ChoreographyContext>();
proc1->BindContext(context1);
affinity = "range";
SetSchedAffinity(proc1->Thread(), cpuset, affinity, 0);
SetSchedPolicy(proc1->Thread(), "SCHED_FIFO", 0, proc1->Tid());
proc->Stop();
proc1->Stop();
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/scheduler_choreo_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 <algorithm>
#include "gtest/gtest.h"
#include "cyber/common/global_data.h"
#include "cyber/cyber.h"
#include "cyber/scheduler/policy/choreography_context.h"
#include "cyber/scheduler/policy/classic_context.h"
#include "cyber/scheduler/policy/scheduler_choreography.h"
#include "cyber/scheduler/processor.h"
#include "cyber/scheduler/scheduler_factory.h"
namespace apollo {
namespace cyber {
namespace scheduler {
void func() {}
TEST(SchedulerChoreoTest, choreo) {
auto processor = std::make_shared<Processor>();
auto ctx = std::make_shared<ChoreographyContext>();
processor->BindContext(ctx);
std::shared_ptr<CRoutine> cr = std::make_shared<CRoutine>(func);
auto task_id = GlobalData::RegisterTaskName("choreo");
cr->set_id(task_id);
EXPECT_TRUE(static_cast<ChoreographyContext*>(ctx.get())->Enqueue(cr));
ctx->Shutdown();
}
TEST(SchedulerChoreoTest, sched_choreo) {
GlobalData::Instance()->SetProcessGroup("example_sched_choreography");
auto sched = dynamic_cast<SchedulerChoreography*>(scheduler::Instance());
cyber::Init("SchedulerChoreoTest");
std::shared_ptr<CRoutine> cr = std::make_shared<CRoutine>(func);
cr->set_id(GlobalData::RegisterTaskName("sched_choreo"));
cr->set_name("sched_choreo");
EXPECT_TRUE(sched->DispatchTask(cr));
std::shared_ptr<CRoutine> cr1 = std::make_shared<CRoutine>(func);
cr1->set_id(GlobalData::RegisterTaskName("sched_choreo1"));
cr1->set_name("sched_choreo1");
cr1->set_processor_id(0);
EXPECT_TRUE(sched->DispatchTask(cr1));
auto& croutines =
ClassicContext::cr_group_[DEFAULT_GROUP_NAME].at(cr->priority());
std::vector<std::string> cr_names;
for (auto& croutine : croutines) {
cr_names.emplace_back(croutine->name());
}
auto itr = std::find(cr_names.begin(), cr_names.end(), cr->name());
EXPECT_NE(itr, cr_names.end());
itr = std::find(cr_names.begin(), cr_names.end(), cr1->name());
EXPECT_EQ(itr, cr_names.end());
sched->RemoveTask(cr->name());
croutines = ClassicContext::cr_group_[DEFAULT_GROUP_NAME].at(cr->priority());
cr_names.clear();
for (auto& croutine : croutines) {
cr_names.emplace_back(croutine->name());
}
itr = std::find(cr_names.begin(), cr_names.end(), cr->name());
EXPECT_EQ(itr, cr_names.end());
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/scheduler/scheduler_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/scheduler/scheduler.h"
#include <string>
#include <thread>
#include "gtest/gtest.h"
#include "cyber/proto/scheduler_conf.pb.h"
#include "cyber/common/global_data.h"
#include "cyber/cyber.h"
#include "cyber/init.h"
#include "cyber/scheduler/processor_context.h"
#include "cyber/scheduler/scheduler_factory.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::proto::InnerThread;
void proc() {}
TEST(SchedulerTest, create_task) {
GlobalData::Instance()->SetProcessGroup("example_sched_classic");
auto sched = Instance();
cyber::Init("scheduler_test");
// read example_sched_classic.conf task 'ABC' prio
std::string croutine_name = "ABC";
EXPECT_TRUE(sched->CreateTask(&proc, croutine_name));
// create a croutine with the same name
EXPECT_FALSE(sched->CreateTask(&proc, croutine_name));
auto task_id = GlobalData::RegisterTaskName(croutine_name);
EXPECT_TRUE(sched->NotifyTask(task_id));
EXPECT_TRUE(sched->RemoveTask(croutine_name));
// remove the same task twice
EXPECT_FALSE(sched->RemoveTask(croutine_name));
// remove a not exist task
EXPECT_FALSE(sched->RemoveTask("driver"));
}
TEST(SchedulerTest, notify_task) {
auto sched = Instance();
cyber::Init("scheduler_test");
std::string name = "croutine";
auto id = GlobalData::RegisterTaskName(name);
// notify task that the id is not exist
EXPECT_FALSE(sched->NotifyTask(id));
EXPECT_TRUE(sched->CreateTask(&proc, name));
EXPECT_TRUE(sched->NotifyTask(id));
}
TEST(SchedulerTest, set_inner_thread_attr) {
auto sched = Instance();
cyber::Init("scheduler_test");
std::thread t = std::thread([]() {});
std::unordered_map<std::string, InnerThread> thread_confs;
InnerThread inner_thread;
inner_thread.set_cpuset("0-1");
inner_thread.set_policy("SCHED_FIFO");
inner_thread.set_prio(10);
thread_confs["inner_thread_test"] = inner_thread;
sched->SetInnerThreadConfs(thread_confs);
sched->SetInnerThreadAttr("inner_thread_test", &t);
std::this_thread::sleep_for(std::chrono::milliseconds(5));
if (t.joinable()) {
t.join();
}
sched->Shutdown();
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/common/pin_thread.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#ifndef CYBER_SCHEDULER_COMMON_PIN_THREAD_H_
#define CYBER_SCHEDULER_COMMON_PIN_THREAD_H_
#include <string>
#include <thread>
#include <vector>
#include "cyber/common/log.h"
namespace apollo {
namespace cyber {
namespace scheduler {
void ParseCpuset(const std::string& str, std::vector<int>* cpuset);
void SetSchedAffinity(std::thread* thread, const std::vector<int>& cpus,
const std::string& affinity, int cpu_id = -1);
void SetSchedPolicy(std::thread* thread, std::string spolicy,
int sched_priority, pid_t tid = -1);
} // namespace scheduler
} // namespace cyber
} // namespace apollo
#endif // CYBER_SCHEDULER_COMMON_PIN_THREAD_H_
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/common/pin_thread.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/scheduler/common/pin_thread.h"
#include <sched.h>
#include <sys/resource.h>
namespace apollo {
namespace cyber {
namespace scheduler {
void ParseCpuset(const std::string& str, std::vector<int>* cpuset) {
std::vector<std::string> lines;
std::stringstream ss(str);
std::string l;
while (getline(ss, l, ',')) {
lines.push_back(l);
}
for (auto line : lines) {
std::stringstream ss(line);
std::vector<std::string> range;
while (getline(ss, l, '-')) {
range.push_back(l);
}
if (range.size() == 1) {
cpuset->push_back(std::stoi(range[0]));
} else if (range.size() == 2) {
for (int i = std::stoi(range[0]), e = std::stoi(range[1]); i <= e; i++) {
cpuset->push_back(i);
}
} else {
ADEBUG << "Parsing cpuset format error.";
exit(0);
}
}
}
void SetSchedAffinity(std::thread* thread, const std::vector<int>& cpus,
const std::string& affinity, int cpu_id) {
cpu_set_t set;
CPU_ZERO(&set);
if (cpus.size()) {
if (!affinity.compare("range")) {
for (const auto cpu : cpus) {
CPU_SET(cpu, &set);
}
pthread_setaffinity_np(thread->native_handle(), sizeof(set), &set);
AINFO << "thread " << thread->get_id() << " set range affinity";
} else if (!affinity.compare("1to1")) {
if (cpu_id == -1 || (uint32_t)cpu_id >= cpus.size()) {
return;
}
CPU_SET(cpus[cpu_id], &set);
pthread_setaffinity_np(thread->native_handle(), sizeof(set), &set);
AINFO << "thread " << thread->get_id() << " set 1to1 affinity";
}
}
}
void SetSchedPolicy(std::thread* thread, std::string spolicy,
int sched_priority, pid_t tid) {
struct sched_param sp;
int policy;
memset(reinterpret_cast<void*>(&sp), 0, sizeof(sp));
sp.sched_priority = sched_priority;
if (!spolicy.compare("SCHED_FIFO")) {
policy = SCHED_FIFO;
pthread_setschedparam(thread->native_handle(), policy, &sp);
AINFO << "thread " << tid << " set sched_policy: " << spolicy;
} else if (!spolicy.compare("SCHED_RR")) {
policy = SCHED_RR;
pthread_setschedparam(thread->native_handle(), policy, &sp);
AINFO << "thread " << tid << " set sched_policy: " << spolicy;
} else if (!spolicy.compare("SCHED_OTHER")) {
setpriority(PRIO_PROCESS, tid, sched_priority);
AINFO << "thread " << tid << " set sched_policy: " << spolicy;
}
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/common/pin_thread_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/scheduler/common/pin_thread.h"
#include <sys/syscall.h>
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "cyber/cyber.h"
namespace apollo {
namespace cyber {
namespace scheduler {
TEST(PinThreadTest, parse_cpuset) {
std::string cpuset = "0-1,2-3";
std::vector<int> cpus;
ParseCpuset(cpuset, &cpus);
ASSERT_EQ(cpus.size(), 4);
cpuset = "0-1";
cpus.clear();
ParseCpuset(cpuset, &cpus);
ASSERT_EQ(cpus.size(), 2);
cpuset = "0";
cpus.clear();
ParseCpuset(cpuset, &cpus);
ASSERT_EQ(cpus.size(), 1);
}
TEST(PinThreadTest, affinity) {
std::string affinity = "range";
std::vector<int> cpuset;
cpuset.emplace_back(0);
std::thread t = std::thread([]() {});
SetSchedAffinity(&t, cpuset, affinity, 0);
if (t.joinable()) {
t.join();
}
affinity = "1to1";
std::thread t1 = std::thread([]() {});
SetSchedAffinity(&t1, cpuset, affinity, 0);
if (t1.joinable()) {
t1.join();
}
}
TEST(pin_thread_test, sched_policy) {
std::string policy = "SCHED_FIFO";
int priority = 0;
std::thread t = std::thread([]() {});
SetSchedPolicy(&t, policy, priority);
if (t.joinable()) {
t.join();
}
policy = "SCHED_RR";
std::thread t1 = std::thread([]() {});
SetSchedPolicy(&t1, policy, priority);
if (t1.joinable()) {
t1.join();
}
policy = "SCHED_OTHER";
std::atomic<pid_t> tid{-1};
std::thread t2 =
std::thread([&]() { tid = static_cast<int>(syscall(SYS_gettid)); });
while (tid.load() == -1) {
cpu_relax();
}
SetSchedPolicy(&t2, policy, priority, tid.load());
if (t2.joinable()) {
t2.join();
}
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/common/cv_wrapper.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_SCHEDULER_COMMON_CV_WRAPPER_H_
#define CYBER_SCHEDULER_COMMON_CV_WRAPPER_H_
#include <condition_variable>
namespace apollo {
namespace cyber {
namespace scheduler {
class CvWrapper {
public:
CvWrapper& operator=(const CvWrapper& other) = delete;
std::condition_variable& Cv() { return cv_; }
private:
mutable std::condition_variable cv_;
};
} // namespace scheduler
} // namespace cyber
} // namespace apollo
#endif // CYBER_SCHEDULER_COMMON_CV_WRAPPER_H_
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/common/mutex_wrapper.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_SCHEDULER_COMMON_MUTEX_WRAPPER_H_
#define CYBER_SCHEDULER_COMMON_MUTEX_WRAPPER_H_
#include <mutex>
namespace apollo {
namespace cyber {
namespace scheduler {
class MutexWrapper {
public:
MutexWrapper& operator=(const MutexWrapper& other) = delete;
std::mutex& Mutex() { return mutex_; }
private:
mutable std::mutex mutex_;
};
} // namespace scheduler
} // namespace cyber
} // namespace apollo
#endif // CYBER_SCHEDULER_COMMON_MUTEX_WRAPPER_H_
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/policy/scheduler_classic.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_SCHEDULER_POLICY_SCHEDULER_CLASSIC_H_
#define CYBER_SCHEDULER_POLICY_SCHEDULER_CLASSIC_H_
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "cyber/croutine/croutine.h"
#include "cyber/proto/classic_conf.pb.h"
#include "cyber/scheduler/scheduler.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::croutine::CRoutine;
using apollo::cyber::proto::ClassicConf;
using apollo::cyber::proto::ClassicTask;
class SchedulerClassic : public Scheduler {
public:
bool RemoveCRoutine(uint64_t crid) override;
bool RemoveTask(const std::string& name) override;
bool DispatchTask(const std::shared_ptr<CRoutine>&) override;
private:
friend Scheduler* Instance();
SchedulerClassic();
void CreateProcessor();
bool NotifyProcessor(uint64_t crid) override;
std::unordered_map<std::string, ClassicTask> cr_confs_;
ClassicConf classic_conf_;
};
} // namespace scheduler
} // namespace cyber
} // namespace apollo
#endif // CYBER_SCHEDULER_POLICY_SCHEDULER_CLASSIC_H_
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/policy/scheduler_choreography.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/scheduler/policy/scheduler_choreography.h"
#include <memory>
#include <string>
#include <utility>
#include "cyber/common/environment.h"
#include "cyber/common/file.h"
#include "cyber/scheduler/policy/choreography_context.h"
#include "cyber/scheduler/policy/classic_context.h"
#include "cyber/scheduler/processor.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::base::AtomicRWLock;
using apollo::cyber::base::ReadLockGuard;
using apollo::cyber::base::WriteLockGuard;
using apollo::cyber::common::GetAbsolutePath;
using apollo::cyber::common::GetProtoFromFile;
using apollo::cyber::common::GlobalData;
using apollo::cyber::common::PathExists;
using apollo::cyber::common::WorkRoot;
using apollo::cyber::croutine::RoutineState;
SchedulerChoreography::SchedulerChoreography()
: choreography_processor_prio_(0), pool_processor_prio_(0) {
std::string conf("conf/");
conf.append(GlobalData::Instance()->ProcessGroup()).append(".conf");
auto cfg_file = GetAbsolutePath(WorkRoot(), conf);
apollo::cyber::proto::CyberConfig cfg;
if (PathExists(cfg_file) && GetProtoFromFile(cfg_file, &cfg)) {
for (auto& thr : cfg.scheduler_conf().threads()) {
inner_thr_confs_[thr.name()] = thr;
}
if (cfg.scheduler_conf().has_process_level_cpuset()) {
process_level_cpuset_ = cfg.scheduler_conf().process_level_cpuset();
ProcessLevelResourceControl();
}
const apollo::cyber::proto::ChoreographyConf& choreography_conf =
cfg.scheduler_conf().choreography_conf();
proc_num_ = choreography_conf.choreography_processor_num();
choreography_affinity_ = choreography_conf.choreography_affinity();
choreography_processor_policy_ =
choreography_conf.choreography_processor_policy();
choreography_processor_prio_ =
choreography_conf.choreography_processor_prio();
ParseCpuset(choreography_conf.choreography_cpuset(), &choreography_cpuset_);
task_pool_size_ = choreography_conf.pool_processor_num();
pool_affinity_ = choreography_conf.pool_affinity();
pool_processor_policy_ = choreography_conf.pool_processor_policy();
pool_processor_prio_ = choreography_conf.pool_processor_prio();
ParseCpuset(choreography_conf.pool_cpuset(), &pool_cpuset_);
for (const auto& task : choreography_conf.tasks()) {
cr_confs_[task.name()] = task;
}
}
if (proc_num_ == 0) {
auto& global_conf = GlobalData::Instance()->Config();
if (global_conf.has_scheduler_conf() &&
global_conf.scheduler_conf().has_default_proc_num()) {
proc_num_ = global_conf.scheduler_conf().default_proc_num();
} else {
proc_num_ = 2;
}
task_pool_size_ = proc_num_;
}
CreateProcessor();
}
void SchedulerChoreography::CreateProcessor() {
for (uint32_t i = 0; i < proc_num_; i++) {
auto proc = std::make_shared<Processor>();
auto ctx = std::make_shared<ChoreographyContext>();
proc->BindContext(ctx);
SetSchedAffinity(proc->Thread(), choreography_cpuset_,
choreography_affinity_, i);
SetSchedPolicy(proc->Thread(), choreography_processor_policy_,
choreography_processor_prio_, proc->Tid());
pctxs_.emplace_back(ctx);
processors_.emplace_back(proc);
}
for (uint32_t i = 0; i < task_pool_size_; i++) {
auto proc = std::make_shared<Processor>();
auto ctx = std::make_shared<ClassicContext>();
proc->BindContext(ctx);
SetSchedAffinity(proc->Thread(), pool_cpuset_, pool_affinity_, i);
SetSchedPolicy(proc->Thread(), pool_processor_policy_, pool_processor_prio_,
proc->Tid());
pctxs_.emplace_back(ctx);
processors_.emplace_back(proc);
}
}
bool SchedulerChoreography::DispatchTask(const std::shared_ptr<CRoutine>& cr) {
// we use multi-key mutex to prevent race condition
// when del && add cr with same crid
MutexWrapper* wrapper = nullptr;
if (!id_map_mutex_.Get(cr->id(), &wrapper)) {
{
std::lock_guard<std::mutex> wl_lg(cr_wl_mtx_);
if (!id_map_mutex_.Get(cr->id(), &wrapper)) {
wrapper = new MutexWrapper();
id_map_mutex_.Set(cr->id(), wrapper);
}
}
}
std::lock_guard<std::mutex> lg(wrapper->Mutex());
// Assign sched cfg to tasks according to configuration.
if (cr_confs_.find(cr->name()) != cr_confs_.end()) {
ChoreographyTask taskconf = cr_confs_[cr->name()];
cr->set_priority(taskconf.prio());
if (taskconf.has_processor()) {
cr->set_processor_id(taskconf.processor());
}
}
{
WriteLockGuard<AtomicRWLock> lk(id_cr_lock_);
if (id_cr_.find(cr->id()) != id_cr_.end()) {
return false;
}
id_cr_[cr->id()] = cr;
}
// Enqueue task.
uint32_t pid = cr->processor_id();
if (pid < proc_num_) {
// Enqueue task to Choreo Policy.
static_cast<ChoreographyContext*>(pctxs_[pid].get())->Enqueue(cr);
} else {
// Check if task prio is reasonable.
if (cr->priority() >= MAX_PRIO) {
AWARN << cr->name() << " prio great than MAX_PRIO.";
cr->set_priority(MAX_PRIO - 1);
}
cr->set_group_name(DEFAULT_GROUP_NAME);
// Enqueue task to pool runqueue.
{
WriteLockGuard<AtomicRWLock> lk(
ClassicContext::rq_locks_[DEFAULT_GROUP_NAME].at(cr->priority()));
ClassicContext::cr_group_[DEFAULT_GROUP_NAME]
.at(cr->priority())
.emplace_back(cr);
}
}
return true;
}
bool SchedulerChoreography::RemoveTask(const std::string& name) {
if (cyber_unlikely(stop_)) {
return true;
}
auto crid = GlobalData::GenerateHashId(name);
return RemoveCRoutine(crid);
}
bool SchedulerChoreography::RemoveCRoutine(uint64_t crid) {
// we use multi-key mutex to prevent race condition
// when del && add cr with same crid
MutexWrapper* wrapper = nullptr;
if (!id_map_mutex_.Get(crid, &wrapper)) {
{
std::lock_guard<std::mutex> wl_lg(cr_wl_mtx_);
if (!id_map_mutex_.Get(crid, &wrapper)) {
wrapper = new MutexWrapper();
id_map_mutex_.Set(crid, wrapper);
}
}
}
std::lock_guard<std::mutex> lg(wrapper->Mutex());
std::shared_ptr<CRoutine> cr = nullptr;
uint32_t pid;
{
WriteLockGuard<AtomicRWLock> lk(id_cr_lock_);
auto p = id_cr_.find(crid);
if (p != id_cr_.end()) {
cr = p->second;
pid = cr->processor_id();
id_cr_[crid]->Stop();
id_cr_.erase(crid);
} else {
return false;
}
}
// rm cr from pool if rt not in choreo context
if (pid < proc_num_) {
return static_cast<ChoreographyContext*>(pctxs_[pid].get())
->RemoveCRoutine(crid);
} else {
return ClassicContext::RemoveCRoutine(cr);
}
}
bool SchedulerChoreography::NotifyProcessor(uint64_t crid) {
if (cyber_unlikely(stop_)) {
return true;
}
std::shared_ptr<CRoutine> cr;
uint32_t pid;
// find cr from id_cr && Update cr Flag
// policies will handle ready-state CRoutines
{
ReadLockGuard<AtomicRWLock> lk(id_cr_lock_);
auto it = id_cr_.find(crid);
if (it != id_cr_.end()) {
cr = it->second;
pid = cr->processor_id();
if (cr->state() == RoutineState::DATA_WAIT ||
cr->state() == RoutineState::IO_WAIT) {
cr->SetUpdateFlag();
}
} else {
return false;
}
}
if (pid < proc_num_) {
static_cast<ChoreographyContext*>(pctxs_[pid].get())->Notify();
} else {
ClassicContext::Notify(cr->group_name());
}
return true;
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/policy/choreography_context.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/scheduler/policy/choreography_context.h"
#include <limits>
#include <unordered_map>
#include <utility>
#include <vector>
#include "cyber/common/types.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::base::ReadLockGuard;
using apollo::cyber::base::WriteLockGuard;
using apollo::cyber::croutine::RoutineState;
std::shared_ptr<CRoutine> ChoreographyContext::NextRoutine() {
if (cyber_unlikely(stop_.load())) {
return nullptr;
}
ReadLockGuard<AtomicRWLock> lock(rq_lk_);
for (auto it : cr_queue_) {
auto cr = it.second;
if (!cr->Acquire()) {
continue;
}
if (cr->UpdateState() == RoutineState::READY) {
return cr;
}
cr->Release();
}
return nullptr;
}
bool ChoreographyContext::Enqueue(const std::shared_ptr<CRoutine>& cr) {
WriteLockGuard<AtomicRWLock> lock(rq_lk_);
cr_queue_.emplace(cr->priority(), cr);
return true;
}
void ChoreographyContext::Notify() {
mtx_wq_.lock();
notify++;
mtx_wq_.unlock();
cv_wq_.notify_one();
}
void ChoreographyContext::Wait() {
std::unique_lock<std::mutex> lk(mtx_wq_);
cv_wq_.wait_for(lk, std::chrono::milliseconds(1000),
[&]() { return notify > 0; });
if (notify > 0) {
notify--;
}
}
void ChoreographyContext::Shutdown() {
stop_.store(true);
mtx_wq_.lock();
notify = std::numeric_limits<unsigned char>::max();
mtx_wq_.unlock();
cv_wq_.notify_all();
}
bool ChoreographyContext::RemoveCRoutine(uint64_t crid) {
WriteLockGuard<AtomicRWLock> lock(rq_lk_);
for (auto it = cr_queue_.begin(); it != cr_queue_.end();) {
auto cr = it->second;
if (cr->id() == crid) {
cr->Stop();
while (!cr->Acquire()) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
AINFO_EVERY(1000) << "waiting for task " << cr->name() << " completion";
}
it = cr_queue_.erase(it);
cr->Release();
return true;
}
++it;
}
return false;
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/policy/classic_context.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_SCHEDULER_POLICY_CLASSIC_CONTEXT_H_
#define CYBER_SCHEDULER_POLICY_CLASSIC_CONTEXT_H_
#include <array>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include "cyber/base/atomic_rw_lock.h"
#include "cyber/croutine/croutine.h"
#include "cyber/scheduler/common/cv_wrapper.h"
#include "cyber/scheduler/common/mutex_wrapper.h"
#include "cyber/scheduler/processor_context.h"
namespace apollo {
namespace cyber {
namespace scheduler {
static constexpr uint32_t MAX_PRIO = 20;
#define DEFAULT_GROUP_NAME "default_grp"
using CROUTINE_QUEUE = std::vector<std::shared_ptr<CRoutine>>;
using MULTI_PRIO_QUEUE = std::array<CROUTINE_QUEUE, MAX_PRIO>;
using CR_GROUP = std::unordered_map<std::string, MULTI_PRIO_QUEUE>;
using LOCK_QUEUE = std::array<base::AtomicRWLock, MAX_PRIO>;
using RQ_LOCK_GROUP = std::unordered_map<std::string, LOCK_QUEUE>;
using GRP_WQ_MUTEX = std::unordered_map<std::string, MutexWrapper>;
using GRP_WQ_CV = std::unordered_map<std::string, CvWrapper>;
using NOTIFY_GRP = std::unordered_map<std::string, int>;
class ClassicContext : public ProcessorContext {
public:
ClassicContext();
explicit ClassicContext(const std::string &group_name);
std::shared_ptr<CRoutine> NextRoutine() override;
void Wait() override;
void Shutdown() override;
static void Notify(const std::string &group_name);
static bool RemoveCRoutine(const std::shared_ptr<CRoutine> &cr);
alignas(CACHELINE_SIZE) static CR_GROUP cr_group_;
alignas(CACHELINE_SIZE) static RQ_LOCK_GROUP rq_locks_;
alignas(CACHELINE_SIZE) static GRP_WQ_CV cv_wq_;
alignas(CACHELINE_SIZE) static GRP_WQ_MUTEX mtx_wq_;
alignas(CACHELINE_SIZE) static NOTIFY_GRP notify_grp_;
private:
void InitGroup(const std::string &group_name);
std::chrono::steady_clock::time_point wake_time_;
bool need_sleep_ = false;
MULTI_PRIO_QUEUE *multi_pri_rq_ = nullptr;
LOCK_QUEUE *lq_ = nullptr;
MutexWrapper *mtx_wrapper_ = nullptr;
CvWrapper *cw_ = nullptr;
std::string current_grp;
};
} // namespace scheduler
} // namespace cyber
} // namespace apollo
#endif // CYBER_SCHEDULER_POLICY_CLASSIC_CONTEXT_H_
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/policy/choreography_context.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_SCHEDULER_POLICY_CHOREOGRAPHY_CONTEXT_H_
#define CYBER_SCHEDULER_POLICY_CHOREOGRAPHY_CONTEXT_H_
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include "cyber/base/atomic_rw_lock.h"
#include "cyber/croutine/croutine.h"
#include "cyber/scheduler/processor_context.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::base::AtomicRWLock;
using croutine::CRoutine;
class ChoreographyContext : public ProcessorContext {
public:
bool RemoveCRoutine(uint64_t crid);
std::shared_ptr<CRoutine> NextRoutine() override;
bool Enqueue(const std::shared_ptr<CRoutine>&);
void Notify();
void Wait() override;
void Shutdown() override;
private:
std::mutex mtx_wq_;
std::condition_variable cv_wq_;
int notify = 0;
AtomicRWLock rq_lk_;
std::multimap<uint32_t, std::shared_ptr<CRoutine>, std::greater<uint32_t>>
cr_queue_;
};
} // namespace scheduler
} // namespace cyber
} // namespace apollo
#endif // CYBER_SCHEDULER_POLICY_CHOREOGRAPHY_CONTEXT_H_
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/policy/scheduler_choreography.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_SCHEDULER_POLICY_SCHEDULER_CHOREOGRAPHY_H_
#define CYBER_SCHEDULER_POLICY_SCHEDULER_CHOREOGRAPHY_H_
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "cyber/croutine/croutine.h"
#include "cyber/proto/choreography_conf.pb.h"
#include "cyber/scheduler/scheduler.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::croutine::CRoutine;
using apollo::cyber::proto::ChoreographyTask;
class SchedulerChoreography : public Scheduler {
public:
bool RemoveCRoutine(uint64_t crid) override;
bool RemoveTask(const std::string& name) override;
bool DispatchTask(const std::shared_ptr<CRoutine>&) override;
private:
friend Scheduler* Instance();
SchedulerChoreography();
void CreateProcessor();
bool NotifyProcessor(uint64_t crid) override;
std::unordered_map<std::string, ChoreographyTask> cr_confs_;
int32_t choreography_processor_prio_;
int32_t pool_processor_prio_;
std::string choreography_affinity_;
std::string pool_affinity_;
std::string choreography_processor_policy_;
std::string pool_processor_policy_;
std::vector<int> choreography_cpuset_;
std::vector<int> pool_cpuset_;
};
} // namespace scheduler
} // namespace cyber
} // namespace apollo
#endif // CYBER_SCHEDULER_POLICY_SCHEDULER_CHOREOGRAPHY_H_
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/policy/classic_context.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/scheduler/policy/classic_context.h"
#include <limits>
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::base::AtomicRWLock;
using apollo::cyber::base::ReadLockGuard;
using apollo::cyber::base::WriteLockGuard;
using apollo::cyber::croutine::CRoutine;
using apollo::cyber::croutine::RoutineState;
alignas(CACHELINE_SIZE) GRP_WQ_MUTEX ClassicContext::mtx_wq_;
alignas(CACHELINE_SIZE) GRP_WQ_CV ClassicContext::cv_wq_;
alignas(CACHELINE_SIZE) RQ_LOCK_GROUP ClassicContext::rq_locks_;
alignas(CACHELINE_SIZE) CR_GROUP ClassicContext::cr_group_;
alignas(CACHELINE_SIZE) NOTIFY_GRP ClassicContext::notify_grp_;
ClassicContext::ClassicContext() { InitGroup(DEFAULT_GROUP_NAME); }
ClassicContext::ClassicContext(const std::string& group_name) {
InitGroup(group_name);
}
void ClassicContext::InitGroup(const std::string& group_name) {
multi_pri_rq_ = &cr_group_[group_name];
lq_ = &rq_locks_[group_name];
mtx_wrapper_ = &mtx_wq_[group_name];
cw_ = &cv_wq_[group_name];
notify_grp_[group_name] = 0;
current_grp = group_name;
}
std::shared_ptr<CRoutine> ClassicContext::NextRoutine() {
if (cyber_unlikely(stop_.load())) {
return nullptr;
}
for (int i = MAX_PRIO - 1; i >= 0; --i) {
ReadLockGuard<AtomicRWLock> lk(lq_->at(i));
for (auto& cr : multi_pri_rq_->at(i)) {
if (!cr->Acquire()) {
continue;
}
if (cr->UpdateState() == RoutineState::READY) {
return cr;
}
cr->Release();
}
}
return nullptr;
}
void ClassicContext::Wait() {
std::unique_lock<std::mutex> lk(mtx_wrapper_->Mutex());
cw_->Cv().wait_for(lk, std::chrono::milliseconds(1000),
[&]() { return notify_grp_[current_grp] > 0; });
if (notify_grp_[current_grp] > 0) {
notify_grp_[current_grp]--;
}
}
void ClassicContext::Shutdown() {
stop_.store(true);
mtx_wrapper_->Mutex().lock();
notify_grp_[current_grp] = std::numeric_limits<unsigned char>::max();
mtx_wrapper_->Mutex().unlock();
cw_->Cv().notify_all();
}
void ClassicContext::Notify(const std::string& group_name) {
(&mtx_wq_[group_name])->Mutex().lock();
notify_grp_[group_name]++;
(&mtx_wq_[group_name])->Mutex().unlock();
cv_wq_[group_name].Cv().notify_one();
}
bool ClassicContext::RemoveCRoutine(const std::shared_ptr<CRoutine>& cr) {
auto grp = cr->group_name();
auto prio = cr->priority();
auto crid = cr->id();
WriteLockGuard<AtomicRWLock> lk(ClassicContext::rq_locks_[grp].at(prio));
auto& croutines = ClassicContext::cr_group_[grp].at(prio);
for (auto it = croutines.begin(); it != croutines.end(); ++it) {
if ((*it)->id() == crid) {
auto cr = *it;
cr->Stop();
while (!cr->Acquire()) {
std::this_thread::sleep_for(std::chrono::microseconds(1));
AINFO_EVERY(1000) << "waiting for task " << cr->name() << " completion";
}
croutines.erase(it);
cr->Release();
return true;
}
}
return false;
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber/scheduler
|
apollo_public_repos/apollo/cyber/scheduler/policy/scheduler_classic.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/scheduler/policy/scheduler_classic.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "cyber/common/environment.h"
#include "cyber/common/file.h"
#include "cyber/scheduler/policy/classic_context.h"
#include "cyber/scheduler/processor.h"
namespace apollo {
namespace cyber {
namespace scheduler {
using apollo::cyber::base::ReadLockGuard;
using apollo::cyber::base::WriteLockGuard;
using apollo::cyber::common::GetAbsolutePath;
using apollo::cyber::common::GetProtoFromFile;
using apollo::cyber::common::GlobalData;
using apollo::cyber::common::PathExists;
using apollo::cyber::common::WorkRoot;
using apollo::cyber::croutine::RoutineState;
SchedulerClassic::SchedulerClassic() {
std::string conf("conf/");
conf.append(GlobalData::Instance()->ProcessGroup()).append(".conf");
auto cfg_file = GetAbsolutePath(WorkRoot(), conf);
apollo::cyber::proto::CyberConfig cfg;
if (PathExists(cfg_file) && GetProtoFromFile(cfg_file, &cfg)) {
for (auto& thr : cfg.scheduler_conf().threads()) {
inner_thr_confs_[thr.name()] = thr;
}
if (cfg.scheduler_conf().has_process_level_cpuset()) {
process_level_cpuset_ = cfg.scheduler_conf().process_level_cpuset();
ProcessLevelResourceControl();
}
classic_conf_ = cfg.scheduler_conf().classic_conf();
for (auto& group : classic_conf_.groups()) {
auto& group_name = group.name();
for (auto task : group.tasks()) {
task.set_group_name(group_name);
cr_confs_[task.name()] = task;
}
}
} else {
// if do not set default_proc_num in scheduler conf
// give a default value
uint32_t proc_num = 2;
auto& global_conf = GlobalData::Instance()->Config();
if (global_conf.has_scheduler_conf() &&
global_conf.scheduler_conf().has_default_proc_num()) {
proc_num = global_conf.scheduler_conf().default_proc_num();
}
task_pool_size_ = proc_num;
auto sched_group = classic_conf_.add_groups();
sched_group->set_name(DEFAULT_GROUP_NAME);
sched_group->set_processor_num(proc_num);
}
CreateProcessor();
}
void SchedulerClassic::CreateProcessor() {
for (auto& group : classic_conf_.groups()) {
auto& group_name = group.name();
auto proc_num = group.processor_num();
if (task_pool_size_ == 0) {
task_pool_size_ = proc_num;
}
auto& affinity = group.affinity();
auto& processor_policy = group.processor_policy();
auto processor_prio = group.processor_prio();
std::vector<int> cpuset;
ParseCpuset(group.cpuset(), &cpuset);
for (uint32_t i = 0; i < proc_num; i++) {
auto ctx = std::make_shared<ClassicContext>(group_name);
pctxs_.emplace_back(ctx);
auto proc = std::make_shared<Processor>();
proc->BindContext(ctx);
SetSchedAffinity(proc->Thread(), cpuset, affinity, i);
SetSchedPolicy(proc->Thread(), processor_policy, processor_prio,
proc->Tid());
processors_.emplace_back(proc);
}
}
}
bool SchedulerClassic::DispatchTask(const std::shared_ptr<CRoutine>& cr) {
// we use multi-key mutex to prevent race condition
// when del && add cr with same crid
MutexWrapper* wrapper = nullptr;
if (!id_map_mutex_.Get(cr->id(), &wrapper)) {
{
std::lock_guard<std::mutex> wl_lg(cr_wl_mtx_);
if (!id_map_mutex_.Get(cr->id(), &wrapper)) {
wrapper = new MutexWrapper();
id_map_mutex_.Set(cr->id(), wrapper);
}
}
}
std::lock_guard<std::mutex> lg(wrapper->Mutex());
{
WriteLockGuard<AtomicRWLock> lk(id_cr_lock_);
if (id_cr_.find(cr->id()) != id_cr_.end()) {
return false;
}
id_cr_[cr->id()] = cr;
}
if (cr_confs_.find(cr->name()) != cr_confs_.end()) {
ClassicTask task = cr_confs_[cr->name()];
cr->set_priority(task.prio());
cr->set_group_name(task.group_name());
} else {
// croutine that not exist in conf
cr->set_group_name(classic_conf_.groups(0).name());
}
if (cr->priority() >= MAX_PRIO) {
AWARN << cr->name() << " prio is greater than MAX_PRIO[ << " << MAX_PRIO
<< "].";
cr->set_priority(MAX_PRIO - 1);
}
// Enqueue task.
{
WriteLockGuard<AtomicRWLock> lk(
ClassicContext::rq_locks_[cr->group_name()].at(cr->priority()));
ClassicContext::cr_group_[cr->group_name()]
.at(cr->priority())
.emplace_back(cr);
}
ClassicContext::Notify(cr->group_name());
return true;
}
bool SchedulerClassic::NotifyProcessor(uint64_t crid) {
if (cyber_unlikely(stop_)) {
return true;
}
{
ReadLockGuard<AtomicRWLock> lk(id_cr_lock_);
if (id_cr_.find(crid) != id_cr_.end()) {
auto cr = id_cr_[crid];
if (cr->state() == RoutineState::DATA_WAIT ||
cr->state() == RoutineState::IO_WAIT) {
cr->SetUpdateFlag();
}
ClassicContext::Notify(cr->group_name());
return true;
}
}
return false;
}
bool SchedulerClassic::RemoveTask(const std::string& name) {
if (cyber_unlikely(stop_)) {
return true;
}
auto crid = GlobalData::GenerateHashId(name);
return RemoveCRoutine(crid);
}
bool SchedulerClassic::RemoveCRoutine(uint64_t crid) {
// we use multi-key mutex to prevent race condition
// when del && add cr with same crid
MutexWrapper* wrapper = nullptr;
if (!id_map_mutex_.Get(crid, &wrapper)) {
{
std::lock_guard<std::mutex> wl_lg(cr_wl_mtx_);
if (!id_map_mutex_.Get(crid, &wrapper)) {
wrapper = new MutexWrapper();
id_map_mutex_.Set(crid, wrapper);
}
}
}
std::lock_guard<std::mutex> lg(wrapper->Mutex());
std::shared_ptr<CRoutine> cr = nullptr;
{
WriteLockGuard<AtomicRWLock> lk(id_cr_lock_);
if (id_cr_.find(crid) != id_cr_.end()) {
cr = id_cr_[crid];
id_cr_[crid]->Stop();
id_cr_.erase(crid);
} else {
return false;
}
}
return ClassicContext::RemoveCRoutine(cr);
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/component/timer_component.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_COMPONENT_TIMER_COMPONENT_H_
#define CYBER_COMPONENT_TIMER_COMPONENT_H_
#include <memory>
#include "cyber/component/component_base.h"
namespace apollo {
namespace cyber {
class Timer;
/**
* @brief .
* TimerComponent is a timer component. Your component can inherit from
* Component, and implement Init() & Proc(), They are called by the CyberRT
* frame.
*/
class TimerComponent : public ComponentBase {
public:
TimerComponent();
~TimerComponent() override;
/**
* @brief init the component by protobuf object.
*
* @param config which is define in 'cyber/proto/component_conf.proto'
*
* @return returns true if successful, otherwise returns false
*/
bool Initialize(const TimerComponentConfig& config) override;
void Clear() override;
bool Process();
uint64_t GetInterval() const;
private:
/**
* @brief The Proc logic of the component, which called by the CyberRT frame.
*
* @return returns true if successful, otherwise returns false
*/
virtual bool Proc() = 0;
uint64_t interval_ = 0;
std::unique_ptr<Timer> timer_;
};
} // namespace cyber
} // namespace apollo
#endif // CYBER_COMPONENT_TIMER_COMPONENT_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/component/component_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/component/component.h"
#include <memory>
#include "gtest/gtest.h"
#include "cyber/init.h"
#include "cyber/message/raw_message.h"
namespace apollo {
namespace cyber {
using apollo::cyber::Component;
using apollo::cyber::message::RawMessage;
using apollo::cyber::proto::ComponentConfig;
using apollo::cyber::proto::TimerComponentConfig;
static bool ret_proc = true;
static bool ret_init = true;
template <typename M0, typename M1 = NullType, typename M2 = NullType,
typename M3 = NullType>
class Component_A : public Component<M0, M1, M2, M3> {
public:
Component_A() {}
bool Init() { return ret_init; }
private:
bool Proc(const std::shared_ptr<M0> &msg0, const std::shared_ptr<M1> &msg1,
const std::shared_ptr<M2> &msg2, const std::shared_ptr<M3> &msg3) {
return ret_proc;
}
};
template <typename M0, typename M1>
class Component_B : public Component<M0, M1> {
public:
Component_B() {}
bool Init() { return ret_init; }
private:
bool Proc(const std::shared_ptr<M0> &, const std::shared_ptr<M1> &) {
return ret_proc;
}
};
template <typename M0>
class Component_C : public Component<M0> {
public:
Component_C() {}
bool Init() { return ret_init; }
private:
bool Proc(const std::shared_ptr<M0> &) { return ret_proc; }
};
TEST(CommonComponent, init) {
ret_proc = true;
ret_init = true;
apollo::cyber::proto::ComponentConfig compcfg;
auto msg_str1 = std::make_shared<message::RawMessage>();
auto msg_str2 = std::make_shared<message::RawMessage>();
auto msg_str3 = std::make_shared<message::RawMessage>();
auto msg_str4 = std::make_shared<message::RawMessage>();
compcfg.set_name("perception");
apollo::cyber::proto::ReaderOption *read_opt = compcfg.add_readers();
read_opt->set_channel("/perception/channel");
auto comC = std::make_shared<Component_C<RawMessage>>();
EXPECT_TRUE(comC->Initialize(compcfg));
EXPECT_TRUE(comC->Process(msg_str1));
compcfg.set_name("perception2");
apollo::cyber::proto::ReaderOption *read_opt2 = compcfg.add_readers();
read_opt2->set_channel("/driver/channel1");
auto comB = std::make_shared<Component_B<RawMessage, RawMessage>>();
EXPECT_TRUE(comB->Initialize(compcfg));
EXPECT_TRUE(comB->Process(msg_str1, msg_str2));
compcfg.set_name("perception3");
apollo::cyber::proto::ReaderOption *read_opt3 = compcfg.add_readers();
read_opt3->set_channel("/driver/channel2");
compcfg.set_name("perception4");
apollo::cyber::proto::ReaderOption *read_opt4 = compcfg.add_readers();
read_opt4->set_channel("/driver/channel3");
auto comA = std::make_shared<
Component_A<RawMessage, RawMessage, RawMessage, RawMessage>>();
EXPECT_TRUE(comA->Initialize(compcfg));
EXPECT_TRUE(comA->Process(msg_str1, msg_str2, msg_str3, msg_str4));
}
TEST(CommonComponentFail, init) {
ret_proc = false;
ret_init = false;
apollo::cyber::proto::ComponentConfig compcfg;
auto msg_str1 = std::make_shared<message::RawMessage>();
auto msg_str2 = std::make_shared<message::RawMessage>();
auto msg_str3 = std::make_shared<message::RawMessage>();
auto msg_str4 = std::make_shared<message::RawMessage>();
compcfg.set_name("perception_f");
apollo::cyber::proto::ReaderOption *read_opt = compcfg.add_readers();
read_opt->set_channel("/perception/channel");
auto comC = std::make_shared<Component_C<RawMessage>>();
EXPECT_FALSE(comC->Initialize(compcfg));
EXPECT_FALSE(comC->Process(msg_str1));
compcfg.set_name("perception2_f");
apollo::cyber::proto::ReaderOption *read_opt2 = compcfg.add_readers();
read_opt2->set_channel("/driver/channel1");
auto comB = std::make_shared<Component_B<RawMessage, RawMessage>>();
EXPECT_FALSE(comB->Initialize(compcfg));
EXPECT_FALSE(comB->Process(msg_str1, msg_str2));
compcfg.set_name("perception3_f");
apollo::cyber::proto::ReaderOption *read_opt3 = compcfg.add_readers();
read_opt3->set_channel("/driver/channel2");
apollo::cyber::proto::ReaderOption *read_opt4 = compcfg.add_readers();
read_opt4->set_channel("/driver/channel3");
auto comA = std::make_shared<
Component_A<RawMessage, RawMessage, RawMessage, RawMessage>>();
EXPECT_FALSE(comA->Initialize(compcfg));
EXPECT_FALSE(comA->Process(msg_str1, msg_str2, msg_str3, msg_str4));
}
} // namespace cyber
} // namespace apollo
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
apollo::cyber::Init(argv[0]);
return RUN_ALL_TESTS();
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/component/timer_component.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/component/timer_component.h"
#include "cyber/timer/timer.h"
namespace apollo {
namespace cyber {
TimerComponent::TimerComponent() {}
TimerComponent::~TimerComponent() {}
bool TimerComponent::Process() {
if (is_shutdown_.load()) {
return true;
}
return Proc();
}
bool TimerComponent::Initialize(const TimerComponentConfig& config) {
if (!config.has_name() || !config.has_interval()) {
AERROR << "Missing required field in config file.";
return false;
}
node_.reset(new Node(config.name()));
LoadConfigFiles(config);
if (!Init()) {
return false;
}
std::shared_ptr<TimerComponent> self =
std::dynamic_pointer_cast<TimerComponent>(shared_from_this());
auto func = [self]() { self->Process(); };
timer_.reset(new Timer(config.interval(), func, false));
timer_->Start();
return true;
}
void TimerComponent::Clear() { timer_.reset(); }
uint64_t TimerComponent::GetInterval() const { return interval_; }
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/component/timer_component_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/component/timer_component.h"
#include <memory>
#include "gtest/gtest.h"
#include "cyber/init.h"
namespace apollo {
namespace cyber {
static bool ret_proc = true;
static bool ret_init = true;
class Component_Timer : public TimerComponent {
public:
Component_Timer() {}
bool Init() { return ret_init; }
bool Proc() { return ret_proc; }
};
TEST(TimerComponent, timertest) {
ret_proc = true;
ret_init = true;
cyber::Init("timer component test");
apollo::cyber::proto::TimerComponentConfig compcfg;
compcfg.set_name("driver");
compcfg.set_interval(100);
std::shared_ptr<Component_Timer> com = std::make_shared<Component_Timer>();
EXPECT_TRUE(com->Initialize(compcfg));
EXPECT_TRUE(com->Process());
}
TEST(TimerComponentFalse, timerfail) {
ret_proc = false;
ret_init = false;
cyber::Init("timer component test");
apollo::cyber::proto::TimerComponentConfig compcfg;
compcfg.set_name("driver1");
compcfg.set_interval(100);
std::shared_ptr<Component_Timer> com = std::make_shared<Component_Timer>();
EXPECT_FALSE(com->Initialize(compcfg));
EXPECT_FALSE(com->Process());
}
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/component/component_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_COMPONENT_COMPONENT_BASE_H_
#define CYBER_COMPONENT_COMPONENT_BASE_H_
#include <atomic>
#include <memory>
#include <string>
#include <vector>
#include "gflags/gflags.h"
#include "cyber/proto/component_conf.pb.h"
#include "cyber/class_loader/class_loader.h"
#include "cyber/common/environment.h"
#include "cyber/common/file.h"
#include "cyber/node/node.h"
#include "cyber/scheduler/scheduler.h"
namespace apollo {
namespace cyber {
using apollo::cyber::proto::ComponentConfig;
using apollo::cyber::proto::TimerComponentConfig;
class ComponentBase : public std::enable_shared_from_this<ComponentBase> {
public:
template <typename M>
using Reader = cyber::Reader<M>;
virtual ~ComponentBase() {}
virtual bool Initialize(const ComponentConfig& config) { return false; }
virtual bool Initialize(const TimerComponentConfig& config) { return false; }
virtual void Shutdown() {
if (is_shutdown_.exchange(true)) {
return;
}
Clear();
for (auto& reader : readers_) {
reader->Shutdown();
}
scheduler::Instance()->RemoveTask(node_->Name());
}
template <typename T>
bool GetProtoConfig(T* config) const {
return common::GetProtoFromFile(config_file_path_, config);
}
protected:
virtual bool Init() = 0;
virtual void Clear() { return; }
const std::string& ConfigFilePath() const { return config_file_path_; }
void LoadConfigFiles(const ComponentConfig& config) {
if (!config.config_file_path().empty()) {
if (config.config_file_path()[0] != '/') {
config_file_path_ = common::GetAbsolutePath(common::WorkRoot(),
config.config_file_path());
} else {
config_file_path_ = config.config_file_path();
}
}
if (!config.flag_file_path().empty()) {
std::string flag_file_path = config.flag_file_path();
if (flag_file_path[0] != '/') {
flag_file_path =
common::GetAbsolutePath(common::WorkRoot(), flag_file_path);
}
google::SetCommandLineOption("flagfile", flag_file_path.c_str());
}
}
void LoadConfigFiles(const TimerComponentConfig& config) {
if (!config.config_file_path().empty()) {
if (config.config_file_path()[0] != '/') {
config_file_path_ = common::GetAbsolutePath(common::WorkRoot(),
config.config_file_path());
} else {
config_file_path_ = config.config_file_path();
}
}
if (!config.flag_file_path().empty()) {
std::string flag_file_path = config.flag_file_path();
if (flag_file_path[0] != '/') {
flag_file_path =
common::GetAbsolutePath(common::WorkRoot(), flag_file_path);
}
google::SetCommandLineOption("flagfile", flag_file_path.c_str());
}
}
std::atomic<bool> is_shutdown_ = {false};
std::shared_ptr<Node> node_ = nullptr;
std::string config_file_path_ = "";
std::vector<std::shared_ptr<ReaderBase>> readers_;
};
} // namespace cyber
} // namespace apollo
#endif // CYBER_COMPONENT_COMPONENT_BASE_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/component/component.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_COMPONENT_COMPONENT_H_
#define CYBER_COMPONENT_COMPONENT_H_
#include <memory>
#include <utility>
#include <vector>
#include "cyber/base/macros.h"
#include "cyber/blocker/blocker_manager.h"
#include "cyber/common/global_data.h"
#include "cyber/common/types.h"
#include "cyber/common/util.h"
#include "cyber/component/component_base.h"
#include "cyber/croutine/routine_factory.h"
#include "cyber/data/data_visitor.h"
#include "cyber/scheduler/scheduler.h"
namespace apollo {
namespace cyber {
using apollo::cyber::common::GlobalData;
using apollo::cyber::proto::RoleAttributes;
/**
* @brief .
* The Component can process up to four channels of messages. The message type
* is specified when the component is created. The Component is inherited from
* ComponentBase. Your component can inherit from Component, and implement
* Init() & Proc(...), They are picked up by the CyberRT. There are 4
* specialization implementations.
*
* @tparam M0 the first message.
* @tparam M1 the second message.
* @tparam M2 the third message.
* @tparam M3 the fourth message.
* @warning The Init & Proc functions need to be overloaded, but don't want to
* be called. They are called by the CyberRT Frame.
*
*/
template <typename M0 = NullType, typename M1 = NullType,
typename M2 = NullType, typename M3 = NullType>
class Component : public ComponentBase {
public:
Component() {}
~Component() override {}
/**
* @brief init the component by protobuf object.
*
* @param config which is defined in 'cyber/proto/component_conf.proto'
*
* @return returns true if successful, otherwise returns false
*/
bool Initialize(const ComponentConfig& config) override;
bool Process(const std::shared_ptr<M0>& msg0, const std::shared_ptr<M1>& msg1,
const std::shared_ptr<M2>& msg2,
const std::shared_ptr<M3>& msg3);
private:
/**
* @brief The process logical of yours.
*
* @param msg0 the first channel message.
* @param msg1 the second channel message.
* @param msg2 the third channel message.
* @param msg3 the fourth channel message.
*
* @return returns true if successful, otherwise returns false
*/
virtual bool Proc(const std::shared_ptr<M0>& msg0,
const std::shared_ptr<M1>& msg1,
const std::shared_ptr<M2>& msg2,
const std::shared_ptr<M3>& msg3) = 0;
};
template <>
class Component<NullType, NullType, NullType, NullType> : public ComponentBase {
public:
Component() {}
~Component() override {}
bool Initialize(const ComponentConfig& config) override;
};
template <typename M0>
class Component<M0, NullType, NullType, NullType> : public ComponentBase {
public:
Component() {}
~Component() override {}
bool Initialize(const ComponentConfig& config) override;
bool Process(const std::shared_ptr<M0>& msg);
private:
virtual bool Proc(const std::shared_ptr<M0>& msg) = 0;
};
template <typename M0, typename M1>
class Component<M0, M1, NullType, NullType> : public ComponentBase {
public:
Component() {}
~Component() override {}
bool Initialize(const ComponentConfig& config) override;
bool Process(const std::shared_ptr<M0>& msg0,
const std::shared_ptr<M1>& msg1);
private:
virtual bool Proc(const std::shared_ptr<M0>& msg,
const std::shared_ptr<M1>& msg1) = 0;
};
template <typename M0, typename M1, typename M2>
class Component<M0, M1, M2, NullType> : public ComponentBase {
public:
Component() {}
~Component() override {}
bool Initialize(const ComponentConfig& config) override;
bool Process(const std::shared_ptr<M0>& msg0, const std::shared_ptr<M1>& msg1,
const std::shared_ptr<M2>& msg2);
private:
virtual bool Proc(const std::shared_ptr<M0>& msg,
const std::shared_ptr<M1>& msg1,
const std::shared_ptr<M2>& msg2) = 0;
};
template <typename M0>
bool Component<M0, NullType, NullType, NullType>::Process(
const std::shared_ptr<M0>& msg) {
if (is_shutdown_.load()) {
return true;
}
return Proc(msg);
}
inline bool Component<NullType, NullType, NullType>::Initialize(
const ComponentConfig& config) {
node_.reset(new Node(config.name()));
LoadConfigFiles(config);
if (!Init()) {
AERROR << "Component Init() failed." << std::endl;
return false;
}
return true;
}
template <typename M0>
bool Component<M0, NullType, NullType, NullType>::Initialize(
const ComponentConfig& config) {
node_.reset(new Node(config.name()));
LoadConfigFiles(config);
if (config.readers_size() < 1) {
AERROR << "Invalid config file: too few readers.";
return false;
}
if (!Init()) {
AERROR << "Component Init() failed.";
return false;
}
bool is_reality_mode = GlobalData::Instance()->IsRealityMode();
ReaderConfig reader_cfg;
reader_cfg.channel_name = config.readers(0).channel();
reader_cfg.qos_profile.CopyFrom(config.readers(0).qos_profile());
reader_cfg.pending_queue_size = config.readers(0).pending_queue_size();
std::weak_ptr<Component<M0>> self =
std::dynamic_pointer_cast<Component<M0>>(shared_from_this());
auto func = [self](const std::shared_ptr<M0>& msg) {
auto ptr = self.lock();
if (ptr) {
ptr->Process(msg);
} else {
AERROR << "Component object has been destroyed.";
}
};
std::shared_ptr<Reader<M0>> reader = nullptr;
if (cyber_likely(is_reality_mode)) {
reader = node_->CreateReader<M0>(reader_cfg);
} else {
reader = node_->CreateReader<M0>(reader_cfg, func);
}
if (reader == nullptr) {
AERROR << "Component create reader failed.";
return false;
}
readers_.emplace_back(std::move(reader));
if (cyber_unlikely(!is_reality_mode)) {
return true;
}
data::VisitorConfig conf = {readers_[0]->ChannelId(),
readers_[0]->PendingQueueSize()};
auto dv = std::make_shared<data::DataVisitor<M0>>(conf);
croutine::RoutineFactory factory =
croutine::CreateRoutineFactory<M0>(func, dv);
auto sched = scheduler::Instance();
return sched->CreateTask(factory, node_->Name());
}
template <typename M0, typename M1>
bool Component<M0, M1, NullType, NullType>::Process(
const std::shared_ptr<M0>& msg0, const std::shared_ptr<M1>& msg1) {
if (is_shutdown_.load()) {
return true;
}
return Proc(msg0, msg1);
}
template <typename M0, typename M1>
bool Component<M0, M1, NullType, NullType>::Initialize(
const ComponentConfig& config) {
node_.reset(new Node(config.name()));
LoadConfigFiles(config);
if (config.readers_size() < 2) {
AERROR << "Invalid config file: too few readers.";
return false;
}
if (!Init()) {
AERROR << "Component Init() failed.";
return false;
}
bool is_reality_mode = GlobalData::Instance()->IsRealityMode();
ReaderConfig reader_cfg;
reader_cfg.channel_name = config.readers(1).channel();
reader_cfg.qos_profile.CopyFrom(config.readers(1).qos_profile());
reader_cfg.pending_queue_size = config.readers(1).pending_queue_size();
auto reader1 = node_->template CreateReader<M1>(reader_cfg);
reader_cfg.channel_name = config.readers(0).channel();
reader_cfg.qos_profile.CopyFrom(config.readers(0).qos_profile());
reader_cfg.pending_queue_size = config.readers(0).pending_queue_size();
std::shared_ptr<Reader<M0>> reader0 = nullptr;
if (cyber_likely(is_reality_mode)) {
reader0 = node_->template CreateReader<M0>(reader_cfg);
} else {
std::weak_ptr<Component<M0, M1>> self =
std::dynamic_pointer_cast<Component<M0, M1>>(shared_from_this());
auto blocker1 = blocker::BlockerManager::Instance()->GetBlocker<M1>(
config.readers(1).channel());
auto func = [self, blocker1](const std::shared_ptr<M0>& msg0) {
auto ptr = self.lock();
if (ptr) {
if (!blocker1->IsPublishedEmpty()) {
auto msg1 = blocker1->GetLatestPublishedPtr();
ptr->Process(msg0, msg1);
}
} else {
AERROR << "Component object has been destroyed.";
}
};
reader0 = node_->template CreateReader<M0>(reader_cfg, func);
}
if (reader0 == nullptr || reader1 == nullptr) {
AERROR << "Component create reader failed.";
return false;
}
readers_.push_back(std::move(reader0));
readers_.push_back(std::move(reader1));
if (cyber_unlikely(!is_reality_mode)) {
return true;
}
auto sched = scheduler::Instance();
std::weak_ptr<Component<M0, M1>> self =
std::dynamic_pointer_cast<Component<M0, M1>>(shared_from_this());
auto func = [self](const std::shared_ptr<M0>& msg0,
const std::shared_ptr<M1>& msg1) {
auto ptr = self.lock();
if (ptr) {
ptr->Process(msg0, msg1);
} else {
AERROR << "Component object has been destroyed.";
}
};
std::vector<data::VisitorConfig> config_list;
for (auto& reader : readers_) {
config_list.emplace_back(reader->ChannelId(), reader->PendingQueueSize());
}
auto dv = std::make_shared<data::DataVisitor<M0, M1>>(config_list);
croutine::RoutineFactory factory =
croutine::CreateRoutineFactory<M0, M1>(func, dv);
return sched->CreateTask(factory, node_->Name());
}
template <typename M0, typename M1, typename M2>
bool Component<M0, M1, M2, NullType>::Process(const std::shared_ptr<M0>& msg0,
const std::shared_ptr<M1>& msg1,
const std::shared_ptr<M2>& msg2) {
if (is_shutdown_.load()) {
return true;
}
return Proc(msg0, msg1, msg2);
}
template <typename M0, typename M1, typename M2>
bool Component<M0, M1, M2, NullType>::Initialize(
const ComponentConfig& config) {
node_.reset(new Node(config.name()));
LoadConfigFiles(config);
if (config.readers_size() < 3) {
AERROR << "Invalid config file: too few readers.";
return false;
}
if (!Init()) {
AERROR << "Component Init() failed.";
return false;
}
bool is_reality_mode = GlobalData::Instance()->IsRealityMode();
ReaderConfig reader_cfg;
reader_cfg.channel_name = config.readers(1).channel();
reader_cfg.qos_profile.CopyFrom(config.readers(1).qos_profile());
reader_cfg.pending_queue_size = config.readers(1).pending_queue_size();
auto reader1 = node_->template CreateReader<M1>(reader_cfg);
reader_cfg.channel_name = config.readers(2).channel();
reader_cfg.qos_profile.CopyFrom(config.readers(2).qos_profile());
reader_cfg.pending_queue_size = config.readers(2).pending_queue_size();
auto reader2 = node_->template CreateReader<M2>(reader_cfg);
reader_cfg.channel_name = config.readers(0).channel();
reader_cfg.qos_profile.CopyFrom(config.readers(0).qos_profile());
reader_cfg.pending_queue_size = config.readers(0).pending_queue_size();
std::shared_ptr<Reader<M0>> reader0 = nullptr;
if (cyber_likely(is_reality_mode)) {
reader0 = node_->template CreateReader<M0>(reader_cfg);
} else {
std::weak_ptr<Component<M0, M1, M2, NullType>> self =
std::dynamic_pointer_cast<Component<M0, M1, M2, NullType>>(
shared_from_this());
auto blocker1 = blocker::BlockerManager::Instance()->GetBlocker<M1>(
config.readers(1).channel());
auto blocker2 = blocker::BlockerManager::Instance()->GetBlocker<M2>(
config.readers(2).channel());
auto func = [self, blocker1, blocker2](const std::shared_ptr<M0>& msg0) {
auto ptr = self.lock();
if (ptr) {
if (!blocker1->IsPublishedEmpty() && !blocker2->IsPublishedEmpty()) {
auto msg1 = blocker1->GetLatestPublishedPtr();
auto msg2 = blocker2->GetLatestPublishedPtr();
ptr->Process(msg0, msg1, msg2);
}
} else {
AERROR << "Component object has been destroyed.";
}
};
reader0 = node_->template CreateReader<M0>(reader_cfg, func);
}
if (reader0 == nullptr || reader1 == nullptr || reader2 == nullptr) {
AERROR << "Component create reader failed.";
return false;
}
readers_.push_back(std::move(reader0));
readers_.push_back(std::move(reader1));
readers_.push_back(std::move(reader2));
if (cyber_unlikely(!is_reality_mode)) {
return true;
}
auto sched = scheduler::Instance();
std::weak_ptr<Component<M0, M1, M2, NullType>> self =
std::dynamic_pointer_cast<Component<M0, M1, M2, NullType>>(
shared_from_this());
auto func = [self](const std::shared_ptr<M0>& msg0,
const std::shared_ptr<M1>& msg1,
const std::shared_ptr<M2>& msg2) {
auto ptr = self.lock();
if (ptr) {
ptr->Process(msg0, msg1, msg2);
} else {
AERROR << "Component object has been destroyed.";
}
};
std::vector<data::VisitorConfig> config_list;
for (auto& reader : readers_) {
config_list.emplace_back(reader->ChannelId(), reader->PendingQueueSize());
}
auto dv = std::make_shared<data::DataVisitor<M0, M1, M2>>(config_list);
croutine::RoutineFactory factory =
croutine::CreateRoutineFactory<M0, M1, M2>(func, dv);
return sched->CreateTask(factory, node_->Name());
}
template <typename M0, typename M1, typename M2, typename M3>
bool Component<M0, M1, M2, M3>::Process(const std::shared_ptr<M0>& msg0,
const std::shared_ptr<M1>& msg1,
const std::shared_ptr<M2>& msg2,
const std::shared_ptr<M3>& msg3) {
if (is_shutdown_.load()) {
return true;
}
return Proc(msg0, msg1, msg2, msg3);
}
template <typename M0, typename M1, typename M2, typename M3>
bool Component<M0, M1, M2, M3>::Initialize(const ComponentConfig& config) {
node_.reset(new Node(config.name()));
LoadConfigFiles(config);
if (config.readers_size() < 4) {
AERROR << "Invalid config file: too few readers_." << std::endl;
return false;
}
if (!Init()) {
AERROR << "Component Init() failed." << std::endl;
return false;
}
bool is_reality_mode = GlobalData::Instance()->IsRealityMode();
ReaderConfig reader_cfg;
reader_cfg.channel_name = config.readers(1).channel();
reader_cfg.qos_profile.CopyFrom(config.readers(1).qos_profile());
reader_cfg.pending_queue_size = config.readers(1).pending_queue_size();
auto reader1 = node_->template CreateReader<M1>(reader_cfg);
reader_cfg.channel_name = config.readers(2).channel();
reader_cfg.qos_profile.CopyFrom(config.readers(2).qos_profile());
reader_cfg.pending_queue_size = config.readers(2).pending_queue_size();
auto reader2 = node_->template CreateReader<M2>(reader_cfg);
reader_cfg.channel_name = config.readers(3).channel();
reader_cfg.qos_profile.CopyFrom(config.readers(3).qos_profile());
reader_cfg.pending_queue_size = config.readers(3).pending_queue_size();
auto reader3 = node_->template CreateReader<M3>(reader_cfg);
reader_cfg.channel_name = config.readers(0).channel();
reader_cfg.qos_profile.CopyFrom(config.readers(0).qos_profile());
reader_cfg.pending_queue_size = config.readers(0).pending_queue_size();
std::shared_ptr<Reader<M0>> reader0 = nullptr;
if (cyber_likely(is_reality_mode)) {
reader0 = node_->template CreateReader<M0>(reader_cfg);
} else {
std::weak_ptr<Component<M0, M1, M2, M3>> self =
std::dynamic_pointer_cast<Component<M0, M1, M2, M3>>(
shared_from_this());
auto blocker1 = blocker::BlockerManager::Instance()->GetBlocker<M1>(
config.readers(1).channel());
auto blocker2 = blocker::BlockerManager::Instance()->GetBlocker<M2>(
config.readers(2).channel());
auto blocker3 = blocker::BlockerManager::Instance()->GetBlocker<M3>(
config.readers(3).channel());
auto func = [self, blocker1, blocker2,
blocker3](const std::shared_ptr<M0>& msg0) {
auto ptr = self.lock();
if (ptr) {
if (!blocker1->IsPublishedEmpty() && !blocker2->IsPublishedEmpty() &&
!blocker3->IsPublishedEmpty()) {
auto msg1 = blocker1->GetLatestPublishedPtr();
auto msg2 = blocker2->GetLatestPublishedPtr();
auto msg3 = blocker3->GetLatestPublishedPtr();
ptr->Process(msg0, msg1, msg2, msg3);
}
} else {
AERROR << "Component object has been destroyed.";
}
};
reader0 = node_->template CreateReader<M0>(reader_cfg, func);
}
if (reader0 == nullptr || reader1 == nullptr || reader2 == nullptr ||
reader3 == nullptr) {
AERROR << "Component create reader failed." << std::endl;
return false;
}
readers_.push_back(std::move(reader0));
readers_.push_back(std::move(reader1));
readers_.push_back(std::move(reader2));
readers_.push_back(std::move(reader3));
if (cyber_unlikely(!is_reality_mode)) {
return true;
}
auto sched = scheduler::Instance();
std::weak_ptr<Component<M0, M1, M2, M3>> self =
std::dynamic_pointer_cast<Component<M0, M1, M2, M3>>(shared_from_this());
auto func =
[self](const std::shared_ptr<M0>& msg0, const std::shared_ptr<M1>& msg1,
const std::shared_ptr<M2>& msg2, const std::shared_ptr<M3>& msg3) {
auto ptr = self.lock();
if (ptr) {
ptr->Process(msg0, msg1, msg2, msg3);
} else {
AERROR << "Component object has been destroyed." << std::endl;
}
};
std::vector<data::VisitorConfig> config_list;
for (auto& reader : readers_) {
config_list.emplace_back(reader->ChannelId(), reader->PendingQueueSize());
}
auto dv = std::make_shared<data::DataVisitor<M0, M1, M2, M3>>(config_list);
croutine::RoutineFactory factory =
croutine::CreateRoutineFactory<M0, M1, M2, M3>(func, dv);
return sched->CreateTask(factory, node_->Name());
}
#define CYBER_REGISTER_COMPONENT(name) \
CLASS_LOADER_REGISTER_CLASS(name, apollo::cyber::ComponentBase)
} // namespace cyber
} // namespace apollo
#endif // CYBER_COMPONENT_COMPONENT_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/component/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "cyber_component_hdrs",
srcs = glob([
"*.h",
]),
)
cc_library(
name = "component",
hdrs = ["component.h"],
deps = [
":component_base",
"//cyber/scheduler",
],
)
cc_test(
name = "component_test",
size = "small",
srcs = ["component_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest",
],
linkstatic = True,
)
cc_library(
name = "timer_component",
srcs = ["timer_component.cc"],
hdrs = ["timer_component.h"],
deps = [
":component_base",
"//cyber/blocker:blocker_manager",
"//cyber/timer",
"//cyber/transport/message:history",
"//cyber/transport/transmitter",
],
alwayslink = True,
)
cc_test(
name = "timer_component_test",
size = "small",
srcs = ["timer_component_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_library(
name = "component_base",
hdrs = ["component_base.h"],
deps = [
"//cyber/base:signal",
"//cyber/base:thread_pool",
"//cyber/class_loader",
"//cyber/node",
"@com_github_gflags_gflags//:gflags",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/raw_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 "cyber/message/raw_message.h"
#include <cstring>
#include <string>
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace message {
TEST(RawMessageTest, constructor) {
RawMessage msg_a;
EXPECT_EQ(msg_a.message, "");
RawMessage msg_b("raw");
EXPECT_EQ(msg_b.message, "raw");
}
TEST(RawMessageTest, serialize_to_array) {
RawMessage msg("serialize_to_array");
EXPECT_FALSE(msg.SerializeToArray(nullptr, 128));
char buf[64] = {0};
EXPECT_FALSE(msg.SerializeToArray(buf, -1));
EXPECT_TRUE(msg.SerializeToArray(buf, 64));
EXPECT_EQ(memcmp(buf, msg.message.data(), msg.ByteSize()), 0);
}
TEST(RawMessageTest, serialize_to_string) {
RawMessage msg("serialize_to_string");
std::string str("");
EXPECT_FALSE(msg.SerializeToString(nullptr));
EXPECT_TRUE(msg.SerializeToString(&str));
EXPECT_EQ(str, "serialize_to_string");
}
TEST(RawMessageTest, parse_from_string) {
RawMessage msg;
EXPECT_TRUE(msg.ParseFromString("parse_from_string"));
EXPECT_EQ(msg.message, "parse_from_string");
}
TEST(RawMessageTest, parse_from_array) {
RawMessage msg;
std::string str("parse_from_array");
EXPECT_FALSE(msg.ParseFromArray(nullptr, static_cast<int>(str.size())));
EXPECT_FALSE(msg.ParseFromArray(str.data(), 0));
EXPECT_TRUE(msg.ParseFromArray(str.data(), static_cast<int>(str.size())));
EXPECT_EQ(msg.message, str);
}
TEST(RawMessageTest, message_type) {
RawMessage msg;
std::string msg_type = RawMessage::TypeName();
EXPECT_EQ(msg_type, "apollo.cyber.message.RawMessage");
// msg_type = MessageType<RawMessage>();
// EXPECT_EQ(msg_type, "apollo.cyber.message.RawMessage");
}
} // namespace message
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/py_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_MESSAGE_PY_MESSAGE_H_
#define CYBER_MESSAGE_PY_MESSAGE_H_
#include <iostream>
#include <sstream>
#include <string>
#include "cyber/common/macros.h"
#include "cyber/message/protobuf_factory.h"
namespace apollo {
namespace cyber {
namespace message {
const char* const PY_MESSAGE_FULLNAME = "apollo.cyber.message.PyMessage";
class PyMessageWrap {
public:
PyMessageWrap() : type_name_("") {}
PyMessageWrap(const std::string& msg, const std::string& type_name)
: data_(msg), type_name_(type_name) {}
PyMessageWrap(const PyMessageWrap& msg)
: data_(msg.data_), type_name_(msg.type_name_) {}
virtual ~PyMessageWrap() {}
class Descriptor {
public:
std::string full_name() const { return PY_MESSAGE_FULLNAME; }
std::string name() const { return PY_MESSAGE_FULLNAME; }
};
static const Descriptor* descriptor();
static std::string TypeName();
bool SerializeToArray(void* data, int size) const;
bool SerializeToString(std::string* output) const;
bool ParseFromArray(const void* data, int size);
bool ParseFromString(const std::string& msgstr);
int ByteSize() const;
static void GetDescriptorString(const std::string& type,
std::string* desc_str);
const std::string& data() const;
void set_data(const std::string& msg);
const std::string& type_name();
void set_type_name(const std::string& type_name);
private:
std::string data_;
std::string type_name_;
};
inline void PyMessageWrap::GetDescriptorString(const std::string& type,
std::string* desc_str) {
ProtobufFactory::Instance()->GetDescriptorString(type, desc_str);
}
inline void PyMessageWrap::set_data(const std::string& msg) { data_ = msg; }
inline const std::string& PyMessageWrap::data() const { return data_; }
inline bool PyMessageWrap::ParseFromArray(const void* data, int size) {
if (data == nullptr || size <= 0) {
return false;
}
data_.assign(reinterpret_cast<const char*>(data), size);
return true;
}
inline bool PyMessageWrap::ParseFromString(const std::string& msgstr) {
// todo : will use submsg type ywf
// std::size_t pos = msgstr.rfind(data_split_pattern);
// if (pos != std::string::npos) {
// std::size_t split_count = data_split_pattern.size();
// data_ = msgstr.substr(0, pos);
// type_name_ = msgstr.substr(pos + split_count);
// return true;
// }
data_ = msgstr;
return true;
}
inline bool PyMessageWrap::SerializeToArray(void* data, int size) const {
if (data == nullptr || size < ByteSize()) {
return false;
}
memcpy(data, data_.data(), data_.size());
return true;
}
inline bool PyMessageWrap::SerializeToString(std::string* output) const {
if (!output) {
return false;
}
// todo : will use submsg type ywf
// *output = data_ + data_split_pattern + type_name_;
*output = data_;
return true;
}
inline int PyMessageWrap::ByteSize() const {
return static_cast<int>(data_.size());
}
inline const std::string& PyMessageWrap::type_name() { return type_name_; }
inline void PyMessageWrap::set_type_name(const std::string& type_name) {
type_name_ = type_name;
}
inline const PyMessageWrap::Descriptor* PyMessageWrap::descriptor() {
static Descriptor desc;
return &desc;
}
inline std::string PyMessageWrap::TypeName() { return PY_MESSAGE_FULLNAME; }
} // namespace message
} // namespace cyber
} // namespace apollo
#endif // CYBER_MESSAGE_PY_MESSAGE_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/py_message_traits.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_MESSAGE_PY_MESSAGE_TRAITS_H_
#define CYBER_MESSAGE_PY_MESSAGE_TRAITS_H_
#include <cassert>
#include <memory>
#include <string>
#include "cyber/message/py_message.h"
namespace apollo {
namespace cyber {
namespace message {
// Template specialization for RawMessage
inline bool SerializeToArray(const PyMessageWrap& message, void* data,
int size) {
return message.SerializeToArray(data, size);
}
inline bool ParseFromArray(const void* data, int size, PyMessageWrap* message) {
return message->ParseFromArray(data, size);
}
inline int ByteSize(const PyMessageWrap& message) { return message.ByteSize(); }
} // namespace message
} // namespace cyber
} // namespace apollo
#endif // CYBER_MESSAGE_PY_MESSAGE_TRAITS_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/protobuf_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_MESSAGE_PROTOBUF_FACTORY_H_
#define CYBER_MESSAGE_PROTOBUF_FACTORY_H_
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
#include "google/protobuf/compiler/parser.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/dynamic_message.h"
#include "google/protobuf/io/tokenizer.h"
#include "cyber/proto/proto_desc.pb.h"
#include "cyber/common/macros.h"
namespace apollo {
namespace cyber {
namespace message {
using apollo::cyber::proto::ProtoDesc;
using google::protobuf::Descriptor;
using google::protobuf::DescriptorPool;
using google::protobuf::DynamicMessageFactory;
using google::protobuf::FileDescriptor;
using google::protobuf::FileDescriptorProto;
class ErrorCollector : public google::protobuf::DescriptorPool::ErrorCollector {
using ErrorLocation =
google::protobuf::DescriptorPool::ErrorCollector::ErrorLocation;
void AddError(const std::string& filename, const std::string& element_name,
const google::protobuf::Message* descriptor,
ErrorLocation location, const std::string& message) override;
void AddWarning(const std::string& filename, const std::string& element_name,
const google::protobuf::Message* descriptor,
ErrorLocation location, const std::string& message) override;
};
class ProtobufFactory {
public:
~ProtobufFactory();
// Recursively register FileDescriptorProto and all its dependencies to
// factory.
bool RegisterMessage(const std::string& proto_desc_str);
bool RegisterPythonMessage(const std::string& proto_str);
// Convert the serialized FileDescriptorProto to real descriptors and place
// them in factory.
// It is an error if a FileDescriptorProto contains references to types or
// other files that are not found in the Factory.
bool RegisterMessage(const google::protobuf::Message& message);
bool RegisterMessage(const Descriptor& desc);
bool RegisterMessage(const FileDescriptorProto& file_desc_proto);
// Serialize all descriptors of the given message to string.
static void GetDescriptorString(const google::protobuf::Message& message,
std::string* desc_str);
// Serialize all descriptors of the descriptor to string.
static void GetDescriptorString(const Descriptor* desc,
std::string* desc_str);
// Get Serialized descriptors of messages with the given type.
void GetDescriptorString(const std::string& type, std::string* desc_str);
// Given a type name, constructs the default (prototype) Message of that type.
// Returns nullptr if no such message exists.
google::protobuf::Message* GenerateMessageByType(
const std::string& type) const;
// Find a top-level message type by name. Returns nullptr if not found.
const Descriptor* FindMessageTypeByName(const std::string& type) const;
// Find a service definition by name. Returns nullptr if not found.
const google::protobuf::ServiceDescriptor* FindServiceByName(
const std::string& name) const;
void GetPythonDesc(const std::string& type, std::string* desc_str);
private:
bool RegisterMessage(const ProtoDesc& proto_desc);
google::protobuf::Message* GetMessageByGeneratedType(
const std::string& type) const;
static bool GetProtoDesc(const FileDescriptor* file_desc,
ProtoDesc* proto_desc);
std::mutex register_mutex_;
std::unique_ptr<DescriptorPool> pool_ = nullptr;
std::unique_ptr<DynamicMessageFactory> factory_ = nullptr;
DECLARE_SINGLETON(ProtobufFactory);
};
} // namespace message
} // namespace cyber
} // namespace apollo
#endif // CYBER_MESSAGE_PROTOBUF_FACTORY_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/message_header_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/message/message_header.h"
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace message {
TEST(MessageHeaderTest, magic_num) {
MessageHeader header;
EXPECT_FALSE(header.is_magic_num_match(nullptr, 0));
EXPECT_FALSE(header.is_magic_num_match("ABCD", 4));
EXPECT_TRUE(header.is_magic_num_match("BDACBDAC", 8));
EXPECT_FALSE(header.is_magic_num_match("BDACBDACBDACBDAC", 16));
header.reset_magic_num();
}
TEST(MessageHeaderTest, seq) {
MessageHeader header;
EXPECT_EQ(header.seq(), 0);
header.set_seq(0xffffffff00000001UL);
EXPECT_EQ(header.seq(), 0xffffffff00000001UL);
header.reset_seq();
EXPECT_EQ(header.seq(), 0);
}
TEST(MessageHeaderTest, timestamp_ns) {
MessageHeader header;
EXPECT_EQ(header.timestamp_ns(), 0);
header.set_timestamp_ns(0xffffffff00000001UL);
EXPECT_EQ(header.timestamp_ns(), 0xffffffff00000001UL);
header.reset_timestamp_ns();
EXPECT_EQ(header.timestamp_ns(), 0);
}
TEST(MessageHeaderTest, src_id) {
MessageHeader header;
EXPECT_EQ(header.src_id(), 0);
header.set_src_id(0xffffffff00000001UL);
EXPECT_EQ(header.src_id(), 0xffffffff00000001UL);
header.reset_src_id();
EXPECT_EQ(header.src_id(), 0);
}
TEST(MessageHeaderTest, dst_id) {
MessageHeader header;
EXPECT_EQ(header.dst_id(), 0);
header.set_dst_id(0xffffffff00000001UL);
EXPECT_EQ(header.dst_id(), 0xffffffff00000001UL);
header.reset_dst_id();
EXPECT_EQ(header.dst_id(), 0);
}
TEST(MessageHeaderTest, msg_type) {
MessageHeader header;
std::string msg_type = header.msg_type();
EXPECT_TRUE(msg_type.empty());
header.set_msg_type(nullptr, 1);
msg_type = "apollo.cyber.proto.UnitTest";
header.set_msg_type(msg_type.data(), msg_type.size());
EXPECT_EQ(msg_type, header.msg_type());
std::string long_type(1000, 'm');
EXPECT_NE(long_type, header.msg_type());
}
TEST(MessageHeaderTest, content_size) {
MessageHeader header;
EXPECT_EQ(header.content_size(), 0);
header.set_content_size(0xffff0001);
EXPECT_EQ(header.content_size(), 0xffff0001);
header.reset_content_size();
EXPECT_EQ(header.content_size(), 0);
}
} // namespace message
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/raw_message_traits.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_MESSAGE_RAW_MESSAGE_TRAITS_H_
#define CYBER_MESSAGE_RAW_MESSAGE_TRAITS_H_
#include <cassert>
#include <memory>
#include <string>
#include "cyber/message/raw_message.h"
namespace apollo {
namespace cyber {
namespace message {
// Template specialization for RawMessage
inline bool SerializeToArray(const RawMessage& message, void* data, int size) {
return message.SerializeToArray(data, size);
}
inline bool ParseFromArray(const void* data, int size, RawMessage* message) {
return message->ParseFromArray(data, size);
}
inline int ByteSize(const RawMessage& message) { return message.ByteSize(); }
} // namespace message
} // namespace cyber
} // namespace apollo
#endif // CYBER_MESSAGE_RAW_MESSAGE_TRAITS_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/protobuf_factory_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/message/protobuf_factory.h"
#include <string>
#include "gtest/gtest.h"
#include "cyber/proto/unit_test.pb.h"
namespace apollo {
namespace cyber {
namespace message {
TEST(ProtobufFactory, register_and_generate) {
// register
auto factory = ProtobufFactory::Instance();
apollo::cyber::proto::ProtoDesc proto_desc;
proto::UnitTest ut;
EXPECT_FALSE(factory->RegisterMessage("test"));
EXPECT_FALSE(factory->RegisterPythonMessage("test"));
google::protobuf::FileDescriptorProto file_desc_proto;
ut.GetDescriptor()->file()->CopyTo(&file_desc_proto);
std::string file_desc_str;
file_desc_proto.SerializeToString(&file_desc_str);
EXPECT_TRUE(factory->RegisterPythonMessage(file_desc_str));
proto_desc.set_desc(file_desc_str);
std::string proto_desc_str;
proto_desc.SerializeToString(&proto_desc_str);
EXPECT_TRUE(factory->RegisterMessage(proto_desc_str));
EXPECT_TRUE(factory->RegisterMessage(file_desc_proto));
EXPECT_TRUE(factory->RegisterMessage(*(ut.GetDescriptor())));
EXPECT_TRUE(factory->RegisterMessage(ut));
// Get Descriptor
std::string get_desc_str;
ProtobufFactory::GetDescriptorString(ut, &get_desc_str);
EXPECT_EQ(get_desc_str, proto_desc_str);
get_desc_str.clear();
ProtobufFactory::GetDescriptorString(ut.GetDescriptor(), &get_desc_str);
EXPECT_EQ(get_desc_str, proto_desc_str);
get_desc_str.clear();
factory->GetDescriptorString("apollo.cyber.proto.UnitTest", &get_desc_str);
EXPECT_EQ(get_desc_str, proto_desc_str);
// Generate
auto message = factory->GenerateMessageByType("test.not.found");
EXPECT_EQ(nullptr, message);
message = factory->GenerateMessageByType("apollo.cyber.proto.UnitTest");
EXPECT_NE(nullptr, message);
delete message;
auto desc_ptr = factory->FindMessageTypeByName("test.not.found");
EXPECT_EQ(nullptr, desc_ptr);
desc_ptr = factory->FindMessageTypeByName("apollo.cyber.proto.UnitTest");
EXPECT_NE(nullptr, desc_ptr);
}
} // namespace message
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/raw_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_MESSAGE_RAW_MESSAGE_H_
#define CYBER_MESSAGE_RAW_MESSAGE_H_
#include <cassert>
#include <cstring>
#include <memory>
#include <string>
#include "cyber/message/protobuf_factory.h"
namespace apollo {
namespace cyber {
namespace message {
struct RawMessage {
RawMessage() : message(""), timestamp(0) {}
explicit RawMessage(const std::string &data) : message(data), timestamp(0) {}
RawMessage(const std::string &data, uint64_t ts)
: message(data), timestamp(ts) {}
RawMessage(const RawMessage &raw_msg)
: message(raw_msg.message), timestamp(raw_msg.timestamp) {}
RawMessage &operator=(const RawMessage &raw_msg) {
if (this != &raw_msg) {
this->message = raw_msg.message;
this->timestamp = raw_msg.timestamp;
}
return *this;
}
~RawMessage() {}
class Descriptor {
public:
std::string full_name() const { return "apollo.cyber.message.RawMessage"; }
std::string name() const { return "apollo.cyber.message.RawMessage"; }
};
static const Descriptor *descriptor() {
static Descriptor desc;
return &desc;
}
static void GetDescriptorString(const std::string &type,
std::string *desc_str) {
ProtobufFactory::Instance()->GetDescriptorString(type, desc_str);
}
bool SerializeToArray(void *data, int size) const {
if (data == nullptr || size < ByteSize()) {
return false;
}
memcpy(data, message.data(), message.size());
return true;
}
bool SerializeToString(std::string *str) const {
if (str == nullptr) {
return false;
}
*str = message;
return true;
}
bool ParseFromArray(const void *data, int size) {
if (data == nullptr || size <= 0) {
return false;
}
message.assign(reinterpret_cast<const char *>(data), size);
return true;
}
bool ParseFromString(const std::string &str) {
message = str;
return true;
}
int ByteSize() const { return static_cast<int>(message.size()); }
static std::string TypeName() { return "apollo.cyber.message.RawMessage"; }
std::string message;
uint64_t timestamp;
};
} // namespace message
} // namespace cyber
} // namespace apollo
#endif // CYBER_MESSAGE_RAW_MESSAGE_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/protobuf_traits.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_MESSAGE_PROTOBUF_TRAITS_H_
#define CYBER_MESSAGE_PROTOBUF_TRAITS_H_
#include <cassert>
#include <memory>
#include <string>
#include "cyber/message/protobuf_factory.h"
namespace apollo {
namespace cyber {
namespace message {
template <typename MessageT,
typename std::enable_if<
std::is_base_of<google::protobuf::Message, MessageT>::value,
int>::type = 0>
inline std::string MessageType() {
return MessageT::descriptor()->full_name();
}
template <typename MessageT,
typename std::enable_if<
std::is_base_of<google::protobuf::Message, MessageT>::value,
int>::type = 0>
std::string MessageType(const MessageT& message) {
return message.GetDescriptor()->full_name();
}
template <typename MessageT,
typename std::enable_if<
std::is_base_of<google::protobuf::Message, MessageT>::value,
int>::type = 0>
inline void GetDescriptorString(const MessageT& message,
std::string* desc_str) {
ProtobufFactory::Instance()->GetDescriptorString(message, desc_str);
}
template <typename MessageT,
typename std::enable_if<
std::is_base_of<google::protobuf::Message, MessageT>::value,
int>::type = 0>
inline void GetDescriptorString(const std::string& type,
std::string* desc_str) {
ProtobufFactory::Instance()->GetDescriptorString(type, desc_str);
}
template <typename MessageT,
typename std::enable_if<
std::is_base_of<google::protobuf::Message, MessageT>::value,
int>::type = 0>
bool RegisterMessage(const MessageT& message) {
return ProtobufFactory::Instance()->RegisterMessage(message);
}
} // namespace message
} // namespace cyber
} // namespace apollo
#endif // CYBER_MESSAGE_PROTOBUF_TRAITS_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/message_traits.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_MESSAGE_MESSAGE_TRAITS_H_
#define CYBER_MESSAGE_MESSAGE_TRAITS_H_
#include <string>
#include "cyber/base/macros.h"
#include "cyber/common/log.h"
#include "cyber/message/message_header.h"
#include "cyber/message/protobuf_traits.h"
#include "cyber/message/py_message_traits.h"
#include "cyber/message/raw_message_traits.h"
namespace apollo {
namespace cyber {
namespace message {
DEFINE_TYPE_TRAIT(HasByteSize, ByteSizeLong)
DEFINE_TYPE_TRAIT(HasType, TypeName)
DEFINE_TYPE_TRAIT(HasSetType, SetTypeName)
DEFINE_TYPE_TRAIT(HasGetDescriptorString, GetDescriptorString)
DEFINE_TYPE_TRAIT(HasDescriptor, descriptor)
DEFINE_TYPE_TRAIT(HasFullName, full_name)
DEFINE_TYPE_TRAIT(HasSerializeToString, SerializeToString)
DEFINE_TYPE_TRAIT(HasParseFromString, ParseFromString)
DEFINE_TYPE_TRAIT(HasSerializeToArray, SerializeToArray)
DEFINE_TYPE_TRAIT(HasParseFromArray, ParseFromArray)
template <typename T>
class HasSerializer {
public:
static constexpr bool value =
HasSerializeToString<T>::value && HasParseFromString<T>::value &&
HasSerializeToArray<T>::value && HasParseFromArray<T>::value;
};
// avoid potential ODR violation
template <typename T>
constexpr bool HasSerializer<T>::value;
template <typename T,
typename std::enable_if<HasType<T>::value &&
std::is_member_function_pointer<
decltype(&T::TypeName)>::value,
bool>::type = 0>
std::string MessageType(const T& message) {
return message.TypeName();
}
template <typename T,
typename std::enable_if<HasType<T>::value &&
!std::is_member_function_pointer<
decltype(&T::TypeName)>::value,
bool>::type = 0>
std::string MessageType(const T& message) {
return T::TypeName();
}
template <typename T,
typename std::enable_if<
!HasType<T>::value &&
!std::is_base_of<google::protobuf::Message, T>::value,
bool>::type = 0>
std::string MessageType(const T& message) {
return typeid(T).name();
}
template <typename T,
typename std::enable_if<HasType<T>::value &&
!std::is_member_function_pointer<
decltype(&T::TypeName)>::value,
bool>::type = 0>
std::string MessageType() {
return T::TypeName();
}
template <typename T,
typename std::enable_if<
!HasType<T>::value &&
!std::is_base_of<google::protobuf::Message, T>::value,
bool>::type = 0>
std::string MessageType() {
return typeid(T).name();
}
template <
typename T,
typename std::enable_if<
HasType<T>::value &&
std::is_member_function_pointer<decltype(&T::TypeName)>::value &&
!std::is_base_of<google::protobuf::Message, T>::value,
bool>::type = 0>
std::string MessageType() {
return typeid(T).name();
}
template <typename T>
typename std::enable_if<HasSetType<T>::value, void>::type SetTypeName(
const std::string& type_name, T* message) {
message->SetTypeName(type_name);
}
template <typename T>
typename std::enable_if<!HasSetType<T>::value, void>::type SetTypeName(
const std::string& type_name, T* message) {}
template <typename T>
typename std::enable_if<HasByteSize<T>::value, int>::type ByteSize(
const T& message) {
return static_cast<int>(message.ByteSizeLong());
}
template <typename T>
typename std::enable_if<!HasByteSize<T>::value, int>::type ByteSize(
const T& message) {
(void)message;
return -1;
}
template <typename T>
int FullByteSize(const T& message) {
int content_size = ByteSize(message);
if (content_size < 0) {
return content_size;
}
return content_size + static_cast<int>(sizeof(MessageHeader));
}
template <typename T>
typename std::enable_if<HasParseFromArray<T>::value, bool>::type ParseFromArray(
const void* data, int size, T* message) {
return message->ParseFromArray(data, size);
}
template <typename T>
typename std::enable_if<!HasParseFromArray<T>::value, bool>::type
ParseFromArray(const void* data, int size, T* message) {
return false;
}
template <typename T>
typename std::enable_if<HasParseFromString<T>::value, bool>::type
ParseFromString(const std::string& str, T* message) {
return message->ParseFromString(str);
}
template <typename T>
typename std::enable_if<!HasParseFromString<T>::value, bool>::type
ParseFromString(const std::string& str, T* message) {
return false;
}
template <typename T>
typename std::enable_if<HasParseFromArray<T>::value, bool>::type ParseFromHC(
const void* data, int size, T* message) {
const auto header_size = sizeof(MessageHeader);
RETURN_VAL_IF(size < (int)header_size, false);
const MessageHeader* header = static_cast<const MessageHeader*>(data);
RETURN_VAL_IF((size - header_size) < header->content_size(), false);
SetTypeName(header->msg_type(), message);
return message->ParseFromArray(
static_cast<const void*>(static_cast<const char*>(data) + header_size),
header->content_size());
}
template <typename T>
typename std::enable_if<!HasParseFromArray<T>::value, bool>::type ParseFromHC(
const void* data, int size, T* message) {
return false;
}
template <typename T>
typename std::enable_if<HasSerializeToArray<T>::value, bool>::type
SerializeToArray(const T& message, void* data, int size) {
return message.SerializeToArray(data, size);
}
template <typename T>
typename std::enable_if<!HasSerializeToArray<T>::value, bool>::type
SerializeToArray(const T& message, void* data, int size) {
return false;
}
template <typename T>
typename std::enable_if<HasSerializeToString<T>::value, bool>::type
SerializeToString(const T& message, std::string* str) {
return message.SerializeToString(str);
}
template <typename T>
typename std::enable_if<!HasSerializeToString<T>::value, bool>::type
SerializeToString(const T& message, std::string* str) {
return false;
}
template <typename T>
typename std::enable_if<HasSerializeToArray<T>::value, bool>::type
SerializeToHC(const T& message, void* data, int size) {
int msg_size = ByteSize(message);
if (msg_size < 0) {
return false;
}
const std::string& type_name = MessageType(message);
MessageHeader header;
header.set_msg_type(type_name.data(), type_name.size());
header.set_content_size(msg_size);
if (sizeof(header) > static_cast<size_t>(size)) {
return false;
}
char* ptr = reinterpret_cast<char*>(data);
memcpy(ptr, static_cast<const void*>(&header), sizeof(header));
ptr += sizeof(header);
int left_size = size - static_cast<int>(sizeof(header));
return SerializeToArray(message, reinterpret_cast<void*>(ptr), left_size);
}
template <typename T>
typename std::enable_if<!HasSerializeToArray<T>::value, bool>::type
SerializeToHC(const T& message, void* data, int size) {
return false;
}
template <typename T, typename std::enable_if<HasGetDescriptorString<T>::value,
bool>::type = 0>
void GetDescriptorString(const std::string& type, std::string* desc_str) {
T::GetDescriptorString(type, desc_str);
}
template <typename T,
typename std::enable_if<
!HasGetDescriptorString<T>::value &&
!std::is_base_of<google::protobuf::Message, T>::value,
bool>::type = 0>
void GetDescriptorString(const std::string& type, std::string* desc_str) {}
template <typename MessageT,
typename std::enable_if<
!std::is_base_of<google::protobuf::Message, MessageT>::value,
int>::type = 0>
void GetDescriptorString(const MessageT& message, std::string* desc_str) {}
template <
typename T, typename Descriptor,
typename std::enable_if<HasFullName<Descriptor>::value, bool>::type = 0>
std::string GetFullName() {
return T::descriptor()->full_name();
}
template <
typename T, typename Descriptor,
typename std::enable_if<!HasFullName<Descriptor>::value, bool>::type = 0>
std::string GetFullName() {
return typeid(T).name();
}
template <typename T,
typename std::enable_if<
HasDescriptor<T>::value &&
!std::is_base_of<google::protobuf::Message, T>::value,
bool>::type = 0>
std::string GetMessageName() {
return GetFullName<T, decltype(*T::descriptor())>();
}
template <typename T,
typename std::enable_if<
HasDescriptor<T>::value &&
std::is_base_of<google::protobuf::Message, T>::value,
bool>::type = 0>
std::string GetMessageName() {
return T::descriptor()->full_name();
}
template <typename T,
typename std::enable_if<!HasDescriptor<T>::value, bool>::type = 0>
std::string GetMessageName() {
return typeid(T).name();
}
} // namespace message
} // namespace cyber
} // namespace apollo
#endif // CYBER_MESSAGE_MESSAGE_TRAITS_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/message_header.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#ifndef CYBER_MESSAGE_MESSAGE_HEADER_H_
#define CYBER_MESSAGE_MESSAGE_HEADER_H_
#include <arpa/inet.h>
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <string>
namespace apollo {
namespace cyber {
namespace message {
class MessageHeader {
public:
MessageHeader() {
reset_magic_num();
reset_seq();
reset_timestamp_ns();
reset_src_id();
reset_dst_id();
reset_msg_type();
reset_res();
reset_content_size();
}
bool is_magic_num_match(const char* other, size_t other_len) const {
if (other == nullptr || other_len != sizeof(magic_num_)) {
return false;
}
return memcmp(magic_num_, other, sizeof(magic_num_)) == 0;
}
void reset_magic_num() { memcpy(magic_num_, "BDACBDAC", sizeof(magic_num_)); }
uint64_t seq() const { return ConvertArrayTo64(seq_); }
void set_seq(uint64_t seq) { Convert64ToArray(seq, const_cast<char*>(seq_)); }
void reset_seq() { memset(seq_, 0, sizeof(seq_)); }
uint64_t timestamp_ns() const { return ConvertArrayTo64(timestamp_ns_); }
void set_timestamp_ns(uint64_t timestamp_ns) {
Convert64ToArray(timestamp_ns, const_cast<char*>(timestamp_ns_));
}
void reset_timestamp_ns() { memset(timestamp_ns_, 0, sizeof(timestamp_ns_)); }
uint64_t src_id() const { return ConvertArrayTo64(src_id_); }
void set_src_id(uint64_t src_id) {
Convert64ToArray(src_id, const_cast<char*>(src_id_));
}
void reset_src_id() { memset(src_id_, 0, sizeof(src_id_)); }
uint64_t dst_id() const { return ConvertArrayTo64(dst_id_); }
void set_dst_id(uint64_t dst_id) {
Convert64ToArray(dst_id, const_cast<char*>(dst_id_));
}
void reset_dst_id() { memset(dst_id_, 0, sizeof(dst_id_)); }
const char* msg_type() const { return msg_type_; }
void set_msg_type(const char* msg_type, size_t msg_type_len) {
if (msg_type == nullptr || msg_type_len == 0) {
return;
}
size_t real_len = msg_type_len;
if (msg_type_len >= sizeof(msg_type_)) {
real_len = sizeof(msg_type_) - 1;
}
reset_msg_type();
memcpy(msg_type_, msg_type, real_len);
}
void reset_msg_type() { memset(msg_type_, 0, sizeof(msg_type_)); }
void reset_res() { memset(res_, 0, sizeof(res_)); }
uint32_t content_size() const { return ConvertArrayTo32(content_size_); }
void set_content_size(uint32_t content_size) {
Convert32ToArray(content_size, const_cast<char*>(content_size_));
}
void reset_content_size() { memset(content_size_, 0, sizeof(content_size_)); }
private:
void Convert32ToArray(uint32_t input, char* output) {
uint32_t n = htonl(input);
memcpy(static_cast<void*>(output), static_cast<const void*>(&n), sizeof(n));
}
void Convert64ToArray(uint64_t input, char* output) {
uint32_t h_high =
static_cast<uint32_t>((input & 0xffffffff00000000UL) >> 32);
uint32_t h_low = static_cast<uint32_t>(input & 0x00000000ffffffffUL);
Convert32ToArray(h_high, output);
Convert32ToArray(h_low, output + 4);
}
uint32_t ConvertArrayTo32(const char* input) const {
uint32_t n = 0;
memcpy(static_cast<void*>(&n), static_cast<const void*>(input), sizeof(n));
return ntohl(n);
}
uint64_t ConvertArrayTo64(const char* input) const {
uint64_t high = ConvertArrayTo32(input);
uint64_t low = ConvertArrayTo32(input + 4);
return (high << 32) | low;
}
char magic_num_[8];
char seq_[8];
char timestamp_ns_[8];
char src_id_[8];
char dst_id_[8];
char msg_type_[129];
char res_[19];
char content_size_[4];
};
} // namespace message
} // namespace cyber
} // namespace apollo
#endif // CYBER_MESSAGE_MESSAGE_HEADER_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/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_message_hdrs",
srcs = glob([
"*.h",
]),
)
cc_library(
name = "message_header",
hdrs = ["message_header.h"],
)
cc_test(
name = "message_header_test",
size = "small",
srcs = ["message_header_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "message_traits",
hdrs = ["message_traits.h"],
deps = [
":message_header",
":protobuf_traits",
":py_message_traits",
":raw_message_traits",
"//cyber/base:macros",
],
)
cc_test(
name = "message_traits_test",
size = "small",
srcs = ["message_traits_test.cc"],
deps = [
"//cyber",
"//cyber/proto:unit_test_cc_proto",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "protobuf_factory",
srcs = ["protobuf_factory.cc"],
hdrs = ["protobuf_factory.h"],
deps = [
"//cyber/common:log",
"//cyber/common:macros",
"//cyber/proto:proto_desc_cc_proto",
],
)
cc_library(
name = "protobuf_traits",
hdrs = ["protobuf_traits.h"],
deps = [
":protobuf_factory",
],
)
cc_library(
name = "py_message",
hdrs = ["py_message.h"],
deps = [
":protobuf_factory",
],
)
cc_library(
name = "py_message_traits",
hdrs = ["py_message_traits.h"],
deps = [
":protobuf_factory",
":py_message",
],
)
cc_library(
name = "raw_message",
hdrs = ["raw_message.h"],
deps = [
":protobuf_factory",
],
)
cc_test(
name = "raw_message_test",
size = "small",
srcs = ["raw_message_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "protobuf_factory_test",
size = "small",
srcs = ["protobuf_factory_test.cc"],
deps = [
"//cyber",
"//cyber/proto:unit_test_cc_proto",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "raw_message_traits",
hdrs = ["raw_message_traits.h"],
deps = [
":protobuf_factory",
":raw_message",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/protobuf_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/message/protobuf_factory.h"
#include "cyber/common/log.h"
namespace apollo {
namespace cyber {
namespace message {
using google::protobuf::MessageFactory;
ProtobufFactory::ProtobufFactory() {
pool_.reset(new DescriptorPool());
factory_.reset(new DynamicMessageFactory(pool_.get()));
}
ProtobufFactory::~ProtobufFactory() {
factory_.reset();
pool_.reset();
}
bool ProtobufFactory::RegisterMessage(
const google::protobuf::Message& message) {
const Descriptor* descriptor = message.GetDescriptor();
return RegisterMessage(*descriptor);
}
bool ProtobufFactory::RegisterMessage(const Descriptor& desc) {
FileDescriptorProto file_desc_proto;
desc.file()->CopyTo(&file_desc_proto);
return RegisterMessage(file_desc_proto);
}
bool ProtobufFactory::RegisterMessage(const ProtoDesc& proto_desc) {
for (int i = 0; i < proto_desc.dependencies_size(); ++i) {
auto dep = proto_desc.dependencies(i);
if (!RegisterMessage(dep)) {
return false;
}
}
FileDescriptorProto file_desc_proto;
file_desc_proto.ParseFromString(proto_desc.desc());
return RegisterMessage(file_desc_proto);
}
bool ProtobufFactory::RegisterPythonMessage(const std::string& proto_str) {
FileDescriptorProto file_desc_proto;
file_desc_proto.ParseFromString(proto_str);
return RegisterMessage(file_desc_proto);
}
bool ProtobufFactory::RegisterMessage(const std::string& proto_desc_str) {
ProtoDesc proto_desc;
proto_desc.ParseFromString(proto_desc_str);
return RegisterMessage(proto_desc);
}
// Internal method
bool ProtobufFactory::RegisterMessage(
const FileDescriptorProto& file_desc_proto) {
ErrorCollector ec;
std::lock_guard<std::mutex> lg(register_mutex_);
auto file_desc = pool_->BuildFileCollectingErrors(file_desc_proto, &ec);
if (!file_desc) {
/*
AERROR << "Failed to register protobuf messages ["
<< file_desc_proto.name() << "]";
*/
return false;
}
return true;
}
// Internal method
bool ProtobufFactory::GetProtoDesc(const FileDescriptor* file_desc,
ProtoDesc* proto_desc) {
FileDescriptorProto file_desc_proto;
file_desc->CopyTo(&file_desc_proto);
std::string str("");
if (!file_desc_proto.SerializeToString(&str)) {
return false;
}
proto_desc->set_desc(str);
for (int i = 0; i < file_desc->dependency_count(); ++i) {
auto desc = proto_desc->add_dependencies();
if (!GetProtoDesc(file_desc->dependency(i), desc)) {
return false;
}
}
return true;
}
void ProtobufFactory::GetDescriptorString(const Descriptor* desc,
std::string* desc_str) {
ProtoDesc proto_desc;
if (!GetProtoDesc(desc->file(), &proto_desc)) {
AERROR << "Failed to get descriptor from message";
return;
}
if (!proto_desc.SerializeToString(desc_str)) {
AERROR << "Failed to get descriptor from message";
}
}
void ProtobufFactory::GetDescriptorString(
const google::protobuf::Message& message, std::string* desc_str) {
const Descriptor* desc = message.GetDescriptor();
return GetDescriptorString(desc, desc_str);
}
void ProtobufFactory::GetPythonDesc(const std::string& type,
std::string* desc_str) {
auto desc = pool_->FindMessageTypeByName(type);
if (desc == nullptr) {
return;
}
google::protobuf::DescriptorProto dp;
desc->CopyTo(&dp);
dp.SerializeToString(desc_str);
}
void ProtobufFactory::GetDescriptorString(const std::string& type,
std::string* desc_str) {
auto desc = DescriptorPool::generated_pool()->FindMessageTypeByName(type);
if (desc != nullptr) {
return GetDescriptorString(desc, desc_str);
}
desc = pool_->FindMessageTypeByName(type);
if (desc == nullptr) {
return;
}
return GetDescriptorString(desc, desc_str);
}
// Internal method
google::protobuf::Message* ProtobufFactory::GenerateMessageByType(
const std::string& type) const {
google::protobuf::Message* message = GetMessageByGeneratedType(type);
if (message != nullptr) {
return message;
}
const google::protobuf::Descriptor* descriptor =
pool_->FindMessageTypeByName(type);
if (descriptor == nullptr) {
AERROR << "cannot find [" << type << "] descriptor";
return nullptr;
}
const google::protobuf::Message* prototype =
factory_->GetPrototype(descriptor);
if (prototype == nullptr) {
AERROR << "cannot find [" << type << "] prototype";
return nullptr;
}
return prototype->New();
}
google::protobuf::Message* ProtobufFactory::GetMessageByGeneratedType(
const std::string& type) const {
auto descriptor =
DescriptorPool::generated_pool()->FindMessageTypeByName(type);
if (descriptor == nullptr) {
// AERROR << "cannot find [" << type << "] descriptor";
return nullptr;
}
auto prototype =
MessageFactory::generated_factory()->GetPrototype(descriptor);
if (prototype == nullptr) {
// AERROR << "cannot find [" << type << "] prototype";
return nullptr;
}
return prototype->New();
}
const Descriptor* ProtobufFactory::FindMessageTypeByName(
const std::string& name) const {
return pool_->FindMessageTypeByName(name);
}
const google::protobuf::ServiceDescriptor* ProtobufFactory::FindServiceByName(
const std::string& name) const {
return pool_->FindServiceByName(name);
}
void ErrorCollector::AddError(const std::string& filename,
const std::string& element_name,
const google::protobuf::Message* descriptor,
ErrorLocation location,
const std::string& message) {
UNUSED(element_name);
UNUSED(descriptor);
UNUSED(location);
AWARN << "[" << filename << "] " << message;
}
void ErrorCollector::AddWarning(const std::string& filename,
const std::string& element_name,
const google::protobuf::Message* descriptor,
ErrorLocation location,
const std::string& message) {
UNUSED(element_name);
UNUSED(descriptor);
UNUSED(location);
AWARN << "[" << filename << "] " << message;
}
} // namespace message
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/message/message_traits_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/message/message_traits.h"
#include <string>
#include "gtest/gtest.h"
#include "cyber/proto/unit_test.pb.h"
namespace apollo {
namespace cyber {
namespace message {
class Data {
uint64_t timestamp;
std::string content;
};
class Message {
public:
std::string content;
std::size_t ByteSizeLong() const { return content.size(); }
bool SerializeToArray(void* data, int size) const {
if (data == nullptr || size < 0 ||
static_cast<size_t>(size) < ByteSizeLong()) {
return false;
}
memcpy(data, content.data(), content.size());
return true;
}
bool SerializeToString(std::string* str) const {
*str = content;
return true;
}
bool ParseFromArray(const void* data, int size) {
if (data == nullptr || size <= 0) {
return false;
}
content.assign(static_cast<const char*>(data), size);
return true;
}
bool ParseFromString(const std::string& str) {
content = str;
return true;
}
static void GetDescriptorString(const std::string&, std::string* str) {
*str = "message";
}
std::string TypeName() const { return "type"; }
};
class PbMessage {
public:
static std::string TypeName() { return "protobuf"; }
};
TEST(MessageTraitsTest, type_trait) {
EXPECT_FALSE(HasType<Data>::value);
EXPECT_FALSE(HasSerializer<Data>::value);
EXPECT_FALSE(HasGetDescriptorString<Data>::value);
EXPECT_TRUE(HasType<Message>::value);
EXPECT_TRUE(HasSerializer<Message>::value);
EXPECT_TRUE(HasGetDescriptorString<Message>::value);
EXPECT_TRUE(HasSerializer<proto::UnitTest>::value);
EXPECT_TRUE(HasType<PyMessageWrap>::value);
EXPECT_TRUE(HasSerializer<PyMessageWrap>::value);
EXPECT_TRUE(HasGetDescriptorString<PyMessageWrap>::value);
EXPECT_TRUE(HasType<RawMessage>::value);
EXPECT_TRUE(HasSerializer<RawMessage>::value);
EXPECT_TRUE(HasGetDescriptorString<RawMessage>::value);
Message msg;
EXPECT_EQ("type", MessageType<Message>(msg));
PbMessage pb_msg;
EXPECT_EQ("protobuf", MessageType<PbMessage>(pb_msg));
EXPECT_EQ("protobuf", MessageType<PbMessage>());
}
TEST(MessageTraitsTest, byte_size) {
Data data;
EXPECT_EQ(ByteSize(data), -1);
Message msg;
EXPECT_EQ(ByteSize(msg), 0);
msg.content = "123";
EXPECT_EQ(ByteSize(msg), 3);
proto::UnitTest ut;
ut.set_class_name("MessageTraitsTest");
ut.set_case_name("byte_size");
EXPECT_GT(ByteSize(ut), 0);
RawMessage raw_msg;
EXPECT_EQ(ByteSize(raw_msg), 0);
raw_msg.message = "123";
EXPECT_EQ(ByteSize(raw_msg), 3);
PyMessageWrap py_msg;
EXPECT_EQ(ByteSize(py_msg), 0);
py_msg.set_data("123");
EXPECT_EQ(ByteSize(py_msg), 3);
}
TEST(MessageTraitsTest, serialize_to_array) {
const int kArraySize = 256;
char array[kArraySize] = {0};
proto::UnitTest ut;
ut.set_class_name("MessageTraits");
ut.set_case_name("serialize_to_string");
EXPECT_TRUE(SerializeToArray(ut, array, sizeof(array)));
{
std::string arr_str(array);
EXPECT_EQ(arr_str, "\n\rMessageTraits\x12\x13serialize_to_string");
}
memset(array, 0, sizeof(array));
Data data;
EXPECT_FALSE(SerializeToArray(data, array, sizeof(array)));
EXPECT_EQ(strlen(array), 0);
memset(array, 0, sizeof(array));
Message msg{"content"};
EXPECT_TRUE(SerializeToArray(msg, array, sizeof(array)));
{
std::string arr_str(array);
EXPECT_EQ("content", arr_str);
}
memset(array, 0, sizeof(array));
RawMessage raw("content");
EXPECT_TRUE(SerializeToArray(raw, array, sizeof(array)));
{
std::string arr_str(array);
EXPECT_EQ("content", arr_str);
}
}
TEST(MessageTraitsTest, serialize_to_string) {
std::string str("");
// protobuf message
proto::UnitTest ut;
ut.set_class_name("MessageTraits");
ut.set_case_name("serialize_to_string");
EXPECT_TRUE(SerializeToString(ut, &str));
EXPECT_EQ(str, "\n\rMessageTraits\x12\x13serialize_to_string");
str = "";
Data data;
EXPECT_FALSE(SerializeToString(data, &str));
EXPECT_EQ("", str);
str = "";
Message msg{"content"};
EXPECT_TRUE(SerializeToString(msg, &str));
EXPECT_EQ("content", str);
str = "";
RawMessage raw("content");
EXPECT_TRUE(SerializeToString(raw, &str));
EXPECT_EQ("content", str);
}
TEST(MessageTraitsTest, parse_from_array) {
const int kArraySize = 256;
const char array[kArraySize] = "\n\rMessageTraits\x12\x11parse_from_string";
const int arr_str_len = static_cast<int>(strlen(array));
const std::string arr_str(array);
proto::UnitTest ut;
EXPECT_TRUE(ParseFromArray(array, arr_str_len, &ut));
EXPECT_EQ(ut.class_name(), "MessageTraits");
EXPECT_EQ(ut.case_name(), "parse_from_string");
Data data;
EXPECT_FALSE(ParseFromArray(array, arr_str_len, &data));
Message msg{"content"};
EXPECT_TRUE(ParseFromArray(array, arr_str_len, &msg));
EXPECT_EQ(msg.content, arr_str);
RawMessage raw;
EXPECT_TRUE(ParseFromArray(array, arr_str_len, &raw));
EXPECT_EQ(raw.message, arr_str);
}
TEST(MessageTraitsTest, parse_from_string) {
proto::UnitTest ut;
std::string str("\n\rMessageTraits\x12\x11parse_from_string");
EXPECT_TRUE(ParseFromString(str, &ut));
EXPECT_EQ(ut.class_name(), "MessageTraits");
EXPECT_EQ(ut.case_name(), "parse_from_string");
Data data;
EXPECT_FALSE(ParseFromString(str, &data));
Message msg{"content"};
EXPECT_TRUE(ParseFromString(str, &msg));
EXPECT_EQ("\n\rMessageTraits\x12\x11parse_from_string", msg.content);
RawMessage raw;
EXPECT_TRUE(ParseFromString(str, &raw));
EXPECT_EQ(str, raw.message);
}
TEST(MessageTraitsTest, serialize_parse_hc) {
auto msg = std::make_shared<proto::Chatter>();
msg->set_timestamp(12345);
msg->set_seq(1);
msg->set_content("chatter msg");
const int size = ByteSize(*msg) + static_cast<int>(sizeof(MessageHeader));
std::string buffer;
buffer.resize(size);
EXPECT_TRUE(SerializeToHC(*msg, const_cast<char*>(buffer.data()), size));
auto pb_msg = std::make_shared<proto::Chatter>();
auto raw_msg = std::make_shared<RawMessage>();
EXPECT_TRUE(
ParseFromHC(const_cast<char*>(buffer.data()), size, pb_msg.get()));
EXPECT_TRUE(
ParseFromHC(const_cast<char*>(buffer.data()), size, raw_msg.get()));
std::string new_buffer;
new_buffer.resize(size);
EXPECT_TRUE(
SerializeToHC(*pb_msg, const_cast<char*>(new_buffer.data()), size));
EXPECT_EQ(new_buffer, buffer);
new_buffer.clear();
new_buffer.resize(size);
EXPECT_TRUE(
SerializeToHC(*raw_msg, const_cast<char*>(new_buffer.data()), size));
EXPECT_TRUE(
ParseFromHC(const_cast<char*>(new_buffer.data()), size, pb_msg.get()));
EXPECT_EQ(pb_msg->timestamp(), 12345);
EXPECT_EQ(pb_msg->seq(), 1);
EXPECT_EQ(pb_msg->content(), "chatter msg");
}
TEST(MessageTraitsTest, message_type) {
std::string msg_type = MessageType<proto::UnitTest>();
EXPECT_EQ(msg_type, "apollo.cyber.proto.UnitTest");
proto::UnitTest ut;
msg_type = MessageType(ut);
EXPECT_EQ(msg_type, "apollo.cyber.proto.UnitTest");
}
TEST(MessageTraitsTest, descriptor) {
const std::string pb_desc =
"\n\xFA\x1\n\x1B"
"cyber/proto/unit_test.proto\x12\x12"
"apollo.cyber.proto\"1\n\bUnitTest\x12\x12\n\nclass_name\x18\x1 "
"\x1(\t\x12\x11\n\tcase_name\x18\x2 "
"\x1(\t\"S\n\aChatter\x12\x11\n\ttimestamp\x18\x1 "
"\x1(\x4\x12\x17\n\xFlidar_timestamp\x18\x2 \x1(\x4\x12\v\n\x3seq\x18\x3 "
"\x1(\x4\x12\xF\n\acontent\x18\x4 \x1(\f\"?\n\x10"
"ChatterBenchmark\x12\r\n\x5stamp\x18\x1 \x1(\x4\x12\v\n\x3seq\x18\x2 "
"\x1(\x4\x12\xF\n\acontent\x18\x3 \x1(\t";
std::string desc;
GetDescriptorString<proto::UnitTest>("apollo.cyber.proto.UnitTest", &desc);
EXPECT_EQ(pb_desc, desc);
desc = "";
GetDescriptorString<RawMessage>("apollo.cyber.proto.UnitTest", &desc);
EXPECT_EQ(pb_desc, desc);
desc = "";
GetDescriptorString<Data>("apollo", &desc);
EXPECT_EQ("", desc);
desc = "";
GetDescriptorString<Message>("apollo", &desc);
EXPECT_EQ("message", desc);
}
} // namespace message
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/time/time.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_TIME_TIME_H_
#define CYBER_TIME_TIME_H_
#include <limits>
#include <string>
#include "cyber/time/duration.h"
namespace apollo {
namespace cyber {
/**
* @brief Cyber has builtin time type Time.
*/
class Time {
public:
static const Time MAX;
static const Time MIN;
Time() = default;
explicit Time(uint64_t nanoseconds);
explicit Time(int nanoseconds);
explicit Time(double seconds);
Time(uint32_t seconds, uint32_t nanoseconds);
Time(const Time& other);
Time& operator=(const Time& other);
/**
* @brief get the current time.
*
* @return return the current time.
*/
static Time Now();
static Time MonoTime();
/**
* @brief Sleep Until time.
*
* @param time the Time object.
*/
static void SleepUntil(const Time& time);
/**
* @brief convert time to second.
*
* @return return a double value unit is second.
*/
double ToSecond() const;
/**
* @brief convert time to microsecond (us).
*
* @return return a unit64_t value unit is us.
*/
uint64_t ToMicrosecond() const;
/**
* @brief convert time to nanosecond.
*
* @return return a unit64_t value unit is nanosecond.
*/
uint64_t ToNanosecond() const;
/**
* @brief convert time to a string.
*
* @return return a string.
*/
std::string ToString() const;
/**
* @brief determine if time is 0
*
* @return return true if time is 0
*/
bool IsZero() const;
Duration operator-(const Time& rhs) const;
Time operator+(const Duration& rhs) const;
Time operator-(const Duration& rhs) const;
Time& operator+=(const Duration& rhs);
Time& operator-=(const Duration& rhs);
bool operator==(const Time& rhs) const;
bool operator!=(const Time& rhs) const;
bool operator>(const Time& rhs) const;
bool operator<(const Time& rhs) const;
bool operator>=(const Time& rhs) const;
bool operator<=(const Time& rhs) const;
private:
uint64_t nanoseconds_ = 0;
};
std::ostream& operator<<(std::ostream& os, const Time& rhs);
} // namespace cyber
} // namespace apollo
#endif // CYBER_TIME_TIME_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/time/clock_test.cc
|
/******************************************************************************
* Copyright 2017 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/time/clock.h"
#include "gtest/gtest.h"
using apollo::cyber::proto::ClockMode;
namespace apollo {
namespace cyber {
TEST(Clock, MockTime) {
Clock::SetMode(ClockMode::MODE_CYBER);
EXPECT_EQ(ClockMode::MODE_CYBER, Clock::mode());
Clock::SetMode(ClockMode::MODE_MOCK);
EXPECT_EQ(ClockMode::MODE_MOCK, Clock::mode());
EXPECT_EQ(0, Clock::Now().ToNanosecond());
Clock::SetNow(Time(1));
EXPECT_EQ(1, Clock::Now().ToNanosecond());
Clock::SetNowInSeconds(123.456);
EXPECT_DOUBLE_EQ(123.456, Clock::NowInSeconds());
}
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/time/duration.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_TIME_DURATION_H_
#define CYBER_TIME_DURATION_H_
#include <cstdint>
#include <iostream>
namespace apollo {
namespace cyber {
class Duration {
public:
Duration() = default;
explicit Duration(int64_t nanoseconds);
explicit Duration(int nanoseconds);
explicit Duration(double seconds);
Duration(uint32_t seconds, uint32_t nanoseconds);
Duration(const Duration &other);
Duration &operator=(const Duration &other);
~Duration() = default;
double ToSecond() const;
int64_t ToNanosecond() const;
bool IsZero() const;
void Sleep() const;
Duration operator+(const Duration &rhs) const;
Duration operator-(const Duration &rhs) const;
Duration operator-() const;
Duration operator*(double scale) const;
Duration &operator+=(const Duration &rhs);
Duration &operator-=(const Duration &rhs);
Duration &operator*=(double scale);
bool operator==(const Duration &rhs) const;
bool operator!=(const Duration &rhs) const;
bool operator>(const Duration &rhs) const;
bool operator<(const Duration &rhs) const;
bool operator>=(const Duration &rhs) const;
bool operator<=(const Duration &rhs) const;
private:
int64_t nanoseconds_ = 0;
};
std::ostream &operator<<(std::ostream &os, const Duration &rhs);
} // namespace cyber
} // namespace apollo
#endif // CYBER_TIME_DURATION_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/time/time_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/time/time.h"
#include <iostream>
#include "gtest/gtest.h"
#include "cyber/time/duration.h"
namespace apollo {
namespace cyber {
TEST(TimeTest, constructor) {
Time time(100UL);
EXPECT_EQ(100UL, time.ToNanosecond());
time = Time(1.1);
EXPECT_EQ(1100000000UL, time.ToNanosecond());
EXPECT_DOUBLE_EQ(1.1, time.ToSecond());
time = Time(1, 1);
EXPECT_EQ(1000000001UL, time.ToNanosecond());
EXPECT_DOUBLE_EQ(1.000000001, time.ToSecond());
Time time2(time);
EXPECT_EQ(time, time2);
}
TEST(TimeTest, operators) {
Time t1(100);
Duration d(200);
Time t2(300);
EXPECT_NE(t1, t2);
EXPECT_LT(t1, t2);
EXPECT_LE(t1, t2);
EXPECT_GT(t2, t1);
EXPECT_GE(t2, t1);
EXPECT_EQ(t1 + d, t2);
EXPECT_EQ(t2 - d, t1);
EXPECT_EQ(t1 += d, t2);
EXPECT_GE(t1, t2);
EXPECT_LE(t1, t2);
EXPECT_EQ(Time(100), t1 -= d);
}
TEST(TimeTest, to_string) {
Time t1(1531225311123456789UL);
std::cout << t1.ToString().c_str() << std::endl;
Time t2(1531225311000006789UL);
std::cout << t2.ToString().c_str() << std::endl;
}
TEST(TimeTest, now) { std::cout << "Time Now: " << Time::Now() << std::endl; }
TEST(TimeTest, is_zero) {
Time time;
EXPECT_TRUE(time.IsZero());
EXPECT_FALSE(Time::MAX.IsZero());
EXPECT_TRUE(Time::MIN.IsZero());
}
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/time/clock.cc
|
/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "cyber/time/clock.h"
#include "cyber/common/global_data.h"
#include "cyber/common/log.h"
#include "cyber/common/util.h"
namespace apollo {
namespace cyber {
using GlobalData = ::apollo::cyber::common::GlobalData;
using AtomicRWLock = ::apollo::cyber::base::AtomicRWLock;
using AtomicWriteLockGuard =
::apollo::cyber::base::WriteLockGuard<AtomicRWLock>;
using AtomicReadLockGuard = ::apollo::cyber::base::ReadLockGuard<AtomicRWLock>;
Clock::Clock() {
const auto& cyber_config = GlobalData::Instance()->Config();
const auto& clock_mode = cyber_config.run_mode_conf().clock_mode();
mode_ = clock_mode;
mock_now_ = Time(0);
}
Time Clock::Now() {
auto clock = Instance();
AtomicReadLockGuard lg(clock->rwlock_);
switch (clock->mode_) {
case ClockMode::MODE_CYBER:
return Time::Now();
case ClockMode::MODE_MOCK:
return clock->mock_now_;
default:
AFATAL << "Unsupported clock mode: "
<< apollo::cyber::common::ToInt(clock->mode_);
}
return Time::Now();
}
double Clock::NowInSeconds() { return Now().ToSecond(); }
void Clock::SetMode(ClockMode mode) {
auto clock = Instance();
AtomicWriteLockGuard lg(clock->rwlock_);
switch (mode) {
case ClockMode::MODE_MOCK: {
clock->mode_ = mode;
break;
}
case ClockMode::MODE_CYBER: {
clock->mode_ = mode;
break;
}
default:
AERROR << "Unknown ClockMode: " << mode;
}
clock->mock_now_ = Time(0);
}
ClockMode Clock::mode() {
auto clock = Instance();
AtomicReadLockGuard lg(clock->rwlock_);
return clock->mode_;
}
void Clock::SetNow(const Time& now) {
auto clock = Instance();
AtomicWriteLockGuard lg(clock->rwlock_);
if (clock->mode_ != ClockMode::MODE_MOCK) {
AERROR << "SetSimNow only works for ClockMode::MOCK";
return;
}
clock->mock_now_ = now;
}
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/time/duration.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/time/duration.h"
#include <chrono>
#include <iomanip>
#include <iostream>
#include <thread>
namespace apollo {
namespace cyber {
Duration::Duration(int64_t nanoseconds) { nanoseconds_ = nanoseconds; }
Duration::Duration(int nanoseconds) {
nanoseconds_ = static_cast<int64_t>(nanoseconds);
}
Duration::Duration(double seconds) {
nanoseconds_ = static_cast<int64_t>(seconds * 1000000000UL);
}
Duration::Duration(uint32_t seconds, uint32_t nanoseconds) {
nanoseconds_ = static_cast<uint64_t>(seconds) * 1000000000UL + nanoseconds;
}
Duration::Duration(const Duration &other) { nanoseconds_ = other.nanoseconds_; }
Duration &Duration::operator=(const Duration &other) {
this->nanoseconds_ = other.nanoseconds_;
return *this;
}
double Duration::ToSecond() const {
return static_cast<double>(nanoseconds_) / 1000000000UL;
}
int64_t Duration::ToNanosecond() const { return nanoseconds_; }
bool Duration::IsZero() const { return nanoseconds_ == 0; }
void Duration::Sleep() const {
auto sleep_time = std::chrono::nanoseconds(nanoseconds_);
std::this_thread::sleep_for(sleep_time);
}
Duration Duration::operator+(const Duration &rhs) const {
return Duration(nanoseconds_ + rhs.nanoseconds_);
}
Duration Duration::operator-(const Duration &rhs) const {
return Duration(nanoseconds_ - rhs.nanoseconds_);
}
Duration Duration::operator-() const { return Duration(-nanoseconds_); }
Duration Duration::operator*(double scale) const {
return Duration(int64_t(static_cast<double>(nanoseconds_) * scale));
}
Duration &Duration::operator+=(const Duration &rhs) {
*this = *this + rhs;
return *this;
}
Duration &Duration::operator-=(const Duration &rhs) {
*this = *this - rhs;
return *this;
}
Duration &Duration::operator*=(double scale) {
*this = Duration(int64_t(static_cast<double>(nanoseconds_) * scale));
return *this;
}
bool Duration::operator==(const Duration &rhs) const {
return nanoseconds_ == rhs.nanoseconds_;
}
bool Duration::operator!=(const Duration &rhs) const {
return nanoseconds_ != rhs.nanoseconds_;
}
bool Duration::operator>(const Duration &rhs) const {
return nanoseconds_ > rhs.nanoseconds_;
}
bool Duration::operator<(const Duration &rhs) const {
return nanoseconds_ < rhs.nanoseconds_;
}
bool Duration::operator>=(const Duration &rhs) const {
return nanoseconds_ >= rhs.nanoseconds_;
}
bool Duration::operator<=(const Duration &rhs) const {
return nanoseconds_ <= rhs.nanoseconds_;
}
std::ostream &operator<<(std::ostream &os, const Duration &rhs) {
std::ios::fmtflags before(os.flags());
os << std::fixed << std::setprecision(9) << rhs.ToSecond() << "s";
os.flags(before);
return os;
}
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/time/duration_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/time/duration.h"
#include "gtest/gtest.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
TEST(DurationTest, constructor) {
Duration duration(100);
EXPECT_EQ(100, duration.ToNanosecond());
duration = Duration(1.1);
EXPECT_EQ(1100000000UL, duration.ToNanosecond());
EXPECT_DOUBLE_EQ(1.1, duration.ToSecond());
duration = Duration(1, 1);
EXPECT_EQ(1000000001UL, duration.ToNanosecond());
EXPECT_DOUBLE_EQ(1.000000001, duration.ToSecond());
Duration d2(duration);
EXPECT_EQ(duration, d2);
}
TEST(DurationTest, operators) {
Duration d1(100);
Duration d2(200);
Duration d3(300);
EXPECT_NE(d1, d3);
EXPECT_LT(d1, d3);
EXPECT_LE(d1, d3);
EXPECT_GT(d3, d1);
EXPECT_GE(d3, d1);
EXPECT_EQ(d1 + d2, d3);
EXPECT_EQ(d2, d1 * 2);
EXPECT_EQ(d3 - d2, d1);
EXPECT_EQ(d1 += d2, d3);
EXPECT_GE(d1, d3);
EXPECT_LE(d1, d3);
EXPECT_EQ(Duration(100), d1 -= d2);
EXPECT_EQ(d2, d1 *= 2);
}
TEST(DurationTest, is_zero) {
Duration duration;
EXPECT_TRUE(duration.IsZero());
}
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/time/rate.cc
|
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, 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 the Willow Garage 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.
*
* Author: Eitan Marder-Eppstein
*********************************************************************/
/******************************************************************************
* 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/time/rate.h"
#include "cyber/common/log.h"
namespace apollo {
namespace cyber {
Rate::Rate(double frequency)
: start_(Time::Now()),
expected_cycle_time_(1.0 / frequency),
actual_cycle_time_(0.0) {}
Rate::Rate(uint64_t nanoseconds)
: start_(Time::Now()),
expected_cycle_time_(static_cast<int64_t>(nanoseconds)),
actual_cycle_time_(0.0) {}
Rate::Rate(const Duration& d)
: start_(Time::Now()), expected_cycle_time_(d), actual_cycle_time_(0.0) {}
void Rate::Sleep() {
Time expected_end = start_ + expected_cycle_time_;
Time actual_end = Time::Now();
// detect backward jumps in time
if (actual_end < start_) {
AWARN << "Detect backward jumps in time";
expected_end = actual_end + expected_cycle_time_;
}
// calculate the time we'll sleep for
Duration sleep_time = expected_end - actual_end;
// set the actual amount of time the loop took in case the user wants to kNow
actual_cycle_time_ = actual_end - start_;
// make sure to reset our start time
start_ = expected_end;
// if we've taken too much time we won't sleep
if (sleep_time < Duration(0.0)) {
AWARN << "Detect forward jumps in time";
// if we've jumped forward in time, or the loop has taken more than a full
// extra cycle, reset our cycle
if (actual_end > expected_end + expected_cycle_time_) {
start_ = actual_end;
}
// return false to show that the desired rate was not met
return;
}
Time::SleepUntil(expected_end);
}
void Rate::Reset() { start_ = Time::Now(); }
Duration Rate::CycleTime() const { return actual_cycle_time_; }
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/time/rate.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_TIME_RATE_H_
#define CYBER_TIME_RATE_H_
#include "cyber/time/duration.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
class Rate {
public:
explicit Rate(double frequency);
explicit Rate(uint64_t nanoseconds);
explicit Rate(const Duration&);
void Sleep();
void Reset();
Duration CycleTime() const;
Duration ExpectedCycleTime() const { return expected_cycle_time_; }
private:
Time start_;
Duration expected_cycle_time_;
Duration actual_cycle_time_;
};
} // namespace cyber
} // namespace apollo
#endif // CYBER_TIME_RATE_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/time/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "cyber_time_hdrs",
srcs = glob([
"*.h",
]),
)
cc_library(
name = "time",
srcs = ["time.cc"],
hdrs = ["time.h"],
deps = [
":duration",
],
)
cc_test(
name = "time_test",
size = "small",
srcs = ["time_test.cc"],
deps = [
":time",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "rate",
srcs = ["rate.cc"],
hdrs = ["rate.h"],
deps = [
":duration",
":time",
"//cyber/common:log",
],
)
cc_library(
name = "duration",
srcs = ["duration.cc"],
hdrs = ["duration.h"],
)
cc_test(
name = "duration_test",
size = "small",
srcs = ["duration_test.cc"],
deps = [
":duration",
":time",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "clock",
srcs = ["clock.cc"],
hdrs = ["clock.h"],
deps = [
":time",
"//cyber/base:atomic_rw_lock",
"//cyber/common:global_data",
"//cyber/common:log",
"//cyber/common:macros",
"//cyber/common:util",
"//cyber/proto:run_mode_conf_cc_proto",
],
)
cc_test(
name = "clock_test",
size = "small",
srcs = ["clock_test.cc"],
deps = [
":clock",
"@com_google_googletest//:gtest_main",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/time/time.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/time/time.h"
#include <chrono>
#include <ctime>
#include <iomanip>
#include <limits>
#include <sstream>
#include <thread>
namespace apollo {
namespace cyber {
using std::chrono::high_resolution_clock;
using std::chrono::steady_clock;
using std::chrono::system_clock;
const Time Time::MAX = Time(std::numeric_limits<uint64_t>::max());
const Time Time::MIN = Time(0);
Time::Time(uint64_t nanoseconds) { nanoseconds_ = nanoseconds; }
Time::Time(int nanoseconds) {
nanoseconds_ = static_cast<uint64_t>(nanoseconds);
}
Time::Time(double seconds) {
nanoseconds_ = static_cast<uint64_t>(seconds * 1000000000UL);
}
Time::Time(uint32_t seconds, uint32_t nanoseconds) {
nanoseconds_ = static_cast<uint64_t>(seconds) * 1000000000UL + nanoseconds;
}
Time::Time(const Time& other) { nanoseconds_ = other.nanoseconds_; }
Time& Time::operator=(const Time& other) {
this->nanoseconds_ = other.nanoseconds_;
return *this;
}
Time Time::Now() {
auto now = high_resolution_clock::now();
auto nano_time_point =
std::chrono::time_point_cast<std::chrono::nanoseconds>(now);
auto epoch = nano_time_point.time_since_epoch();
uint64_t now_nano =
std::chrono::duration_cast<std::chrono::nanoseconds>(epoch).count();
return Time(now_nano);
}
Time Time::MonoTime() {
auto now = steady_clock::now();
auto nano_time_point =
std::chrono::time_point_cast<std::chrono::nanoseconds>(now);
auto epoch = nano_time_point.time_since_epoch();
uint64_t now_nano =
std::chrono::duration_cast<std::chrono::nanoseconds>(epoch).count();
return Time(now_nano);
}
double Time::ToSecond() const {
return static_cast<double>(nanoseconds_) / 1000000000UL;
}
bool Time::IsZero() const { return nanoseconds_ == 0; }
uint64_t Time::ToNanosecond() const { return nanoseconds_; }
uint64_t Time::ToMicrosecond() const {
return static_cast<uint64_t>(nanoseconds_ / 1000.0);
}
std::string Time::ToString() const {
auto nano = std::chrono::nanoseconds(nanoseconds_);
system_clock::time_point tp(nano);
auto time = system_clock::to_time_t(tp);
struct tm stm;
auto ret = localtime_r(&time, &stm);
if (ret == nullptr) {
return std::to_string(static_cast<double>(nanoseconds_) / 1000000000.0);
}
std::stringstream ss;
#if __GNUC__ >= 5
ss << std::put_time(ret, "%F %T");
ss << "." << std::setw(9) << std::setfill('0') << nanoseconds_ % 1000000000UL;
#else
char date_time[128];
strftime(date_time, sizeof(date_time), "%F %T", ret);
ss << std::string(date_time) << "." << std::setw(9) << std::setfill('0')
<< nanoseconds_ % 1000000000UL;
#endif
return ss.str();
}
void Time::SleepUntil(const Time& time) {
auto nano = std::chrono::nanoseconds(time.ToNanosecond());
system_clock::time_point tp(nano);
std::this_thread::sleep_until(tp);
}
Duration Time::operator-(const Time& rhs) const {
return Duration(static_cast<int64_t>(nanoseconds_ - rhs.nanoseconds_));
}
Time Time::operator+(const Duration& rhs) const {
return Time(nanoseconds_ + rhs.ToNanosecond());
}
Time Time::operator-(const Duration& rhs) const {
return Time(nanoseconds_ - rhs.ToNanosecond());
}
Time& Time::operator+=(const Duration& rhs) {
*this = *this + rhs;
return *this;
}
Time& Time::operator-=(const Duration& rhs) {
*this = *this - rhs;
return *this;
}
bool Time::operator==(const Time& rhs) const {
return nanoseconds_ == rhs.nanoseconds_;
}
bool Time::operator!=(const Time& rhs) const {
return nanoseconds_ != rhs.nanoseconds_;
}
bool Time::operator>(const Time& rhs) const {
return nanoseconds_ > rhs.nanoseconds_;
}
bool Time::operator<(const Time& rhs) const {
return nanoseconds_ < rhs.nanoseconds_;
}
bool Time::operator>=(const Time& rhs) const {
return nanoseconds_ >= rhs.nanoseconds_;
}
bool Time::operator<=(const Time& rhs) const {
return nanoseconds_ <= rhs.nanoseconds_;
}
std::ostream& operator<<(std::ostream& os, const Time& rhs) {
os << rhs.ToString();
return os;
}
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/time/clock.h
|
/******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_TIME_CLOCK_H_
#define CYBER_TIME_CLOCK_H_
#include <mutex>
#include "cyber/proto/run_mode_conf.pb.h"
#include "cyber/base/atomic_rw_lock.h"
#include "cyber/common/macros.h"
#include "cyber/time/time.h"
namespace apollo {
namespace cyber {
using ::apollo::cyber::proto::ClockMode;
/**
* @class Clock
* @brief a singleton clock that can be used to get the current
* timestamp. The source can be either system(cyber) clock or a mock clock.
* Mock clock is for testing purpose mainly.
*/
class Clock {
public:
static constexpr int64_t PRECISION =
std::chrono::system_clock::duration::period::den /
std::chrono::system_clock::duration::period::num;
/// PRECISION >= 1000000 means the precision is at least 1us.
static_assert(PRECISION >= 1000000,
"The precision of the system clock should be at least 1 "
"microsecond.");
/**
* @brief get current time.
* @return a Time object representing the current time.
*/
static Time Now();
/**
* @brief gets the current time in second.
* @return the current time in second.
*/
static double NowInSeconds();
/**
* @brief This is for mock clock mode only. It will set the timestamp
* for the mock clock.
*/
static void SetNow(const Time& now);
/**
* @brief Set the behavior of the \class Clock.
* @param The new clock mode to be set.
*/
static void SetMode(ClockMode mode);
/**
* @brief Gets the current clock mode.
* @return The current clock mode.
*/
static ClockMode mode();
/**
* @brief This is for mock clock mode only. It will set the timestamp
* for the mock clock with UNIX timestamp in seconds.
*/
static void SetNowInSeconds(const double seconds) {
Clock::SetNow(Time(seconds));
}
private:
ClockMode mode_;
Time mock_now_;
::apollo::cyber::base::AtomicRWLock rwlock_;
DECLARE_SINGLETON(Clock)
};
} // namespace cyber
} // namespace apollo
#endif // CYBER_TIME_CLOCK_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/types.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_COMMON_TYPES_H_
#define CYBER_COMMON_TYPES_H_
#include <cstdint>
namespace apollo {
namespace cyber {
class NullType {};
// Return code definition for cyber internal function return.
enum ReturnCode {
SUCC = 0,
FAIL = 1,
};
/**
* @brief Describe relation between nodes, writers/readers...
*/
enum Relation : std::uint8_t {
NO_RELATION = 0,
DIFF_HOST, // different host
DIFF_PROC, // same host, but different process
SAME_PROC, // same process
};
static const char SRV_CHANNEL_REQ_SUFFIX[] = "__SRV__REQUEST";
static const char SRV_CHANNEL_RES_SUFFIX[] = "__SRV__RESPONSE";
} // namespace cyber
} // namespace apollo
#endif // CYBER_COMMON_TYPES_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/file.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/common/file.h"
#include <dirent.h>
#include <fcntl.h>
#include <glob.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
#include <cstddef>
#include <fstream>
#include <string>
#include "google/protobuf/util/json_util.h"
#include "nlohmann/json.hpp"
namespace apollo {
namespace cyber {
namespace common {
using std::istreambuf_iterator;
using std::string;
using std::vector;
bool SetProtoToASCIIFile(const google::protobuf::Message &message,
int file_descriptor) {
using google::protobuf::TextFormat;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyOutputStream;
if (file_descriptor < 0) {
AERROR << "Invalid file descriptor.";
return false;
}
ZeroCopyOutputStream *output = new FileOutputStream(file_descriptor);
bool success = TextFormat::Print(message, output);
delete output;
close(file_descriptor);
return success;
}
bool SetProtoToASCIIFile(const google::protobuf::Message &message,
const std::string &file_name) {
int fd = open(file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
if (fd < 0) {
AERROR << "Unable to open file " << file_name << " to write.";
return false;
}
return SetProtoToASCIIFile(message, fd);
}
bool GetProtoFromASCIIFile(const std::string &file_name,
google::protobuf::Message *message) {
using google::protobuf::TextFormat;
using google::protobuf::io::FileInputStream;
using google::protobuf::io::ZeroCopyInputStream;
int file_descriptor = open(file_name.c_str(), O_RDONLY);
if (file_descriptor < 0) {
AERROR << "Failed to open file " << file_name << " in text mode.";
// Failed to open;
return false;
}
ZeroCopyInputStream *input = new FileInputStream(file_descriptor);
bool success = TextFormat::Parse(input, message);
if (!success) {
AERROR << "Failed to parse file " << file_name << " as text proto.";
}
delete input;
close(file_descriptor);
return success;
}
bool SetProtoToBinaryFile(const google::protobuf::Message &message,
const std::string &file_name) {
std::fstream output(file_name,
std::ios::out | std::ios::trunc | std::ios::binary);
return message.SerializeToOstream(&output);
}
bool GetProtoFromBinaryFile(const std::string &file_name,
google::protobuf::Message *message) {
std::fstream input(file_name, std::ios::in | std::ios::binary);
if (!input.good()) {
AERROR << "Failed to open file " << file_name << " in binary mode.";
return false;
}
if (!message->ParseFromIstream(&input)) {
AERROR << "Failed to parse file " << file_name << " as binary proto.";
return false;
}
return true;
}
bool GetProtoFromFile(const std::string &file_name,
google::protobuf::Message *message) {
// Try the binary parser first if it's much likely a binary proto.
static const std::string kBinExt = ".bin";
if (std::equal(kBinExt.rbegin(), kBinExt.rend(), file_name.rbegin())) {
return GetProtoFromBinaryFile(file_name, message) ||
GetProtoFromASCIIFile(file_name, message);
}
return GetProtoFromASCIIFile(file_name, message) ||
GetProtoFromBinaryFile(file_name, message);
}
bool GetProtoFromJsonFile(const std::string &file_name,
google::protobuf::Message *message) {
using google::protobuf::util::JsonParseOptions;
using google::protobuf::util::JsonStringToMessage;
std::ifstream ifs(file_name);
if (!ifs.is_open()) {
AERROR << "Failed to open file " << file_name;
return false;
}
nlohmann::json Json;
ifs >> Json;
ifs.close();
JsonParseOptions options;
options.ignore_unknown_fields = true;
google::protobuf::util::Status dump_status;
return (JsonStringToMessage(Json.dump(), message, options).ok());
}
bool GetContent(const std::string &file_name, std::string *content) {
std::ifstream fin(file_name);
if (!fin) {
return false;
}
std::stringstream str_stream;
str_stream << fin.rdbuf();
*content = str_stream.str();
return true;
}
std::string GetAbsolutePath(const std::string &prefix,
const std::string &relative_path) {
if (relative_path.empty()) {
return prefix;
}
// If prefix is empty or relative_path is already absolute.
if (prefix.empty() || relative_path.front() == '/') {
return relative_path;
}
if (prefix.back() == '/') {
return prefix + relative_path;
}
return prefix + "/" + relative_path;
}
bool PathExists(const std::string &path) {
struct stat info;
return stat(path.c_str(), &info) == 0;
}
bool DirectoryExists(const std::string &directory_path) {
struct stat info;
return stat(directory_path.c_str(), &info) == 0 && (info.st_mode & S_IFDIR);
}
std::vector<std::string> Glob(const std::string &pattern) {
glob_t globs = {};
std::vector<std::string> results;
if (glob(pattern.c_str(), GLOB_TILDE, nullptr, &globs) == 0) {
for (size_t i = 0; i < globs.gl_pathc; ++i) {
results.emplace_back(globs.gl_pathv[i]);
}
}
globfree(&globs);
return results;
}
bool CopyFile(const std::string &from, const std::string &to) {
std::ifstream src(from, std::ios::binary);
if (!src) {
AWARN << "Source path could not be normally opened: " << from;
std::string command = "cp -r " + from + " " + to;
ADEBUG << command;
const int ret = std::system(command.c_str());
if (ret == 0) {
ADEBUG << "Copy success, command returns " << ret;
return true;
} else {
ADEBUG << "Copy error, command returns " << ret;
return false;
}
}
std::ofstream dst(to, std::ios::binary);
if (!dst) {
AERROR << "Target path is not writable: " << to;
return false;
}
dst << src.rdbuf();
return true;
}
bool CopyDir(const std::string &from, const std::string &to) {
DIR *directory = opendir(from.c_str());
if (directory == nullptr) {
AERROR << "Cannot open directory " << from;
return false;
}
bool ret = true;
if (EnsureDirectory(to)) {
struct dirent *entry;
while ((entry = readdir(directory)) != nullptr) {
// skip directory_path/. and directory_path/..
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
continue;
}
const std::string sub_path_from = from + "/" + entry->d_name;
const std::string sub_path_to = to + "/" + entry->d_name;
if (entry->d_type == DT_DIR) {
ret &= CopyDir(sub_path_from, sub_path_to);
} else {
ret &= CopyFile(sub_path_from, sub_path_to);
}
}
} else {
AERROR << "Cannot create target directory " << to;
ret = false;
}
closedir(directory);
return ret;
}
bool Copy(const std::string &from, const std::string &to) {
return DirectoryExists(from) ? CopyDir(from, to) : CopyFile(from, to);
}
bool EnsureDirectory(const std::string &directory_path) {
std::string path = directory_path;
for (size_t i = 1; i < directory_path.size(); ++i) {
if (directory_path[i] == '/') {
// Whenever a '/' is encountered, create a temporary view from
// the start of the path to the character right before this.
path[i] = 0;
if (mkdir(path.c_str(), S_IRWXU) != 0) {
if (errno != EEXIST) {
return false;
}
}
// Revert the temporary view back to the original.
path[i] = '/';
}
}
// Make the final (full) directory.
if (mkdir(path.c_str(), S_IRWXU) != 0) {
if (errno != EEXIST) {
return false;
}
}
return true;
}
bool RemoveAllFiles(const std::string &directory_path) {
DIR *directory = opendir(directory_path.c_str());
if (directory == nullptr) {
AERROR << "Cannot open directory " << directory_path;
return false;
}
struct dirent *file;
while ((file = readdir(directory)) != nullptr) {
// skip directory_path/. and directory_path/..
if (!strcmp(file->d_name, ".") || !strcmp(file->d_name, "..")) {
continue;
}
// build the path for each file in the folder
std::string file_path = directory_path + "/" + file->d_name;
if (unlink(file_path.c_str()) < 0) {
AERROR << "Fail to remove file " << file_path << ": " << strerror(errno);
closedir(directory);
return false;
}
}
closedir(directory);
return true;
}
std::vector<std::string> ListSubPaths(const std::string &directory_path,
const unsigned char d_type) {
std::vector<std::string> result;
DIR *directory = opendir(directory_path.c_str());
if (directory == nullptr) {
AERROR << "Cannot open directory " << directory_path;
return result;
}
struct dirent *entry;
while ((entry = readdir(directory)) != nullptr) {
// Skip "." and "..".
if (entry->d_type == d_type && strcmp(entry->d_name, ".") != 0 &&
strcmp(entry->d_name, "..") != 0) {
result.emplace_back(entry->d_name);
}
}
closedir(directory);
return result;
}
std::string GetFileName(const std::string &path, const bool remove_extension) {
std::string::size_type start = path.rfind('/');
if (start == std::string::npos) {
start = 0;
} else {
// Move to the next char after '/'.
++start;
}
std::string::size_type end = std::string::npos;
if (remove_extension) {
end = path.rfind('.');
// The last '.' is found before last '/', ignore.
if (end != std::string::npos && end < start) {
end = std::string::npos;
}
}
const auto len = (end != std::string::npos) ? end - start : end;
return path.substr(start, len);
}
std::string GetCurrentPath() {
char tmp[PATH_MAX];
return getcwd(tmp, sizeof(tmp)) ? std::string(tmp) : std::string("");
}
bool GetType(const string &filename, FileType *type) {
struct stat stat_buf;
if (lstat(filename.c_str(), &stat_buf) != 0) {
return false;
}
if (S_ISDIR(stat_buf.st_mode) != 0) {
*type = TYPE_DIR;
} else if (S_ISREG(stat_buf.st_mode) != 0) {
*type = TYPE_FILE;
} else {
AWARN << "failed to get type: " << filename;
return false;
}
return true;
}
bool DeleteFile(const string &filename) {
if (!PathExists(filename)) {
return true;
}
FileType type;
if (!GetType(filename, &type)) {
return false;
}
if (type == TYPE_FILE) {
if (remove(filename.c_str()) != 0) {
AERROR << "failed to remove file: " << filename;
return false;
}
return true;
}
DIR *dir = opendir(filename.c_str());
if (dir == nullptr) {
AWARN << "failed to opendir: " << filename;
return false;
}
dirent *dir_info = nullptr;
while ((dir_info = readdir(dir)) != nullptr) {
if (strcmp(dir_info->d_name, ".") == 0 ||
strcmp(dir_info->d_name, "..") == 0) {
continue;
}
string temp_file = filename + "/" + string(dir_info->d_name);
FileType temp_type;
if (!GetType(temp_file, &temp_type)) {
AWARN << "failed to get file type: " << temp_file;
closedir(dir);
return false;
}
if (type == TYPE_DIR) {
DeleteFile(temp_file);
}
remove(temp_file.c_str());
}
closedir(dir);
remove(filename.c_str());
return true;
}
bool CreateDir(const string &dir) {
int ret = mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
if (ret != 0) {
AWARN << "failed to create dir. [dir: " << dir
<< "] [err: " << strerror(errno) << "]";
return false;
}
return true;
}
} // namespace common
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/file.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_COMMON_FILE_H_
#define CYBER_COMMON_FILE_H_
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstdio>
#include <fstream>
#include <string>
#include <vector>
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "google/protobuf/text_format.h"
#include "cyber/common/log.h"
/**
* @namespace apollo::common::util
* @brief apollo::common::util
*/
namespace apollo {
namespace cyber {
namespace common {
// file type: file or directory
enum FileType { TYPE_FILE, TYPE_DIR };
bool SetProtoToASCIIFile(const google::protobuf::Message &message,
int file_descriptor);
/**
* @brief Sets the content of the file specified by the file_name to be the
* ascii representation of the input protobuf.
* @param message The proto to output to the specified file.
* @param file_name The name of the target file to set the content.
* @return If the action is successful.
*/
bool SetProtoToASCIIFile(const google::protobuf::Message &message,
const std::string &file_name);
/**
* @brief Parses the content of the file specified by the file_name as ascii
* representation of protobufs, and merges the parsed content to the
* proto.
* @param file_name The name of the file to parse whose content.
* @param message The proto to carry the parsed content in the specified file.
* @return If the action is successful.
*/
bool GetProtoFromASCIIFile(const std::string &file_name,
google::protobuf::Message *message);
/**
* @brief Sets the content of the file specified by the file_name to be the
* binary representation of the input protobuf.
* @param message The proto to output to the specified file.
* @param file_name The name of the target file to set the content.
* @return If the action is successful.
*/
bool SetProtoToBinaryFile(const google::protobuf::Message &message,
const std::string &file_name);
/**
* @brief Parses the content of the file specified by the file_name as binary
* representation of protobufs, and merges the parsed content to the
* proto.
* @param file_name The name of the file to parse whose content.
* @param message The proto to carry the parsed content in the specified file.
* @return If the action is successful.
*/
bool GetProtoFromBinaryFile(const std::string &file_name,
google::protobuf::Message *message);
/**
* @brief Parses the content of the file specified by the file_name as a
* representation of protobufs, and merges the parsed content to the
* proto.
* @param file_name The name of the file to parse whose content.
* @param message The proto to carry the parsed content in the specified file.
* @return If the action is successful.
*/
bool GetProtoFromFile(const std::string &file_name,
google::protobuf::Message *message);
/**
* @brief Parses the content of the json file specified by the file_name as ascii
* representation of protobufs, and merges the parsed content to the
* proto.
* @param file_name The name of the file to parse whose content.
* @param message The proto to carry the parsed content in the specified file.
* @return If the action is successful.
*/
bool GetProtoFromJsonFile(const std::string &file_name,
google::protobuf::Message *message);
/**
* @brief Get file content as string.
* @param file_name The name of the file to read content.
* @param content The file content.
* @return If the action is successful.
*/
bool GetContent(const std::string &file_name, std::string *content);
/**
* @brief Get absolute path by concatenating prefix and relative_path.
* @return The absolute path.
*/
std::string GetAbsolutePath(const std::string &prefix,
const std::string &relative_path);
/**
* @brief Check if the path exists.
* @param path a file name, such as /a/b/c.txt
* @return If the path exists.
*/
bool PathExists(const std::string &path);
/**
* @brief Check if the directory specified by directory_path exists
* and is indeed a directory.
* @param directory_path Directory path.
* @return If the directory specified by directory_path exists
* and is indeed a directory.
*/
bool DirectoryExists(const std::string &directory_path);
/**
* @brief Expand path pattern to matched paths.
* @param pattern Path pattern, which may contain wildcards [?*].
* @return Matched path list.
*/
std::vector<std::string> Glob(const std::string &pattern);
/**
* @brief Copy a file.
* @param from The file path to copy from.
* @param to The file path to copy to.
* @return If the action is successful.
*/
bool CopyFile(const std::string &from, const std::string &to);
/**
* @brief Copy a directory.
* @param from The path to copy from.
* @param to The path to copy to.
* @return If the action is successful.
*/
bool CopyDir(const std::string &from, const std::string &to);
/**
* @brief Copy a file or directory.
* @param from The path to copy from.
* @param to The path to copy to.
* @return If the action is successful.
*/
bool Copy(const std::string &from, const std::string &to);
/**
* @brief Check if a specified directory specified by directory_path exists.
* If not, recursively create the directory (and its parents).
* @param directory_path Directory path.
* @return If the directory does exist or its creation is successful.
*/
bool EnsureDirectory(const std::string &directory_path);
/**
* @brief Remove all the files under a specified directory. Note that
* sub-directories are NOT affected.
* @param directory_path Directory path.
* @return If the action is successful.
*/
bool RemoveAllFiles(const std::string &directory_path);
/**
* @brief List sub-paths.
* @param directory_path Directory path.
* @param d_type Sub-path type, DT_DIR for directory, or DT_REG for file.
* @return A vector of sub-paths, without the directory_path prefix.
*/
std::vector<std::string> ListSubPaths(const std::string &directory_path,
const unsigned char d_type = DT_DIR);
std::string GetFileName(const std::string &path,
const bool remove_extension = false);
std::string GetCurrentPath();
// delete file including file or directory
bool DeleteFile(const std::string &filename);
bool GetType(const std::string &filename, FileType *type);
bool CreateDir(const std::string &dir);
} // namespace common
} // namespace cyber
} // namespace apollo
#endif // CYBER_COMMON_FILE_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/global_data.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_COMMON_GLOBAL_DATA_H_
#define CYBER_COMMON_GLOBAL_DATA_H_
#include <string>
#include <unordered_map>
#include "cyber/proto/cyber_conf.pb.h"
#include "cyber/base/atomic_hash_map.h"
#include "cyber/base/atomic_rw_lock.h"
#include "cyber/common/log.h"
#include "cyber/common/macros.h"
#include "cyber/common/util.h"
namespace apollo {
namespace cyber {
namespace common {
using ::apollo::cyber::base::AtomicHashMap;
using ::apollo::cyber::proto::ClockMode;
using ::apollo::cyber::proto::CyberConfig;
using ::apollo::cyber::proto::RunMode;
class GlobalData {
public:
~GlobalData();
int ProcessId() const;
void SetProcessGroup(const std::string& process_group);
const std::string& ProcessGroup() const;
void SetComponentNums(const int component_nums);
int ComponentNums() const;
void SetSchedName(const std::string& sched_name);
const std::string& SchedName() const;
const std::string& HostIp() const;
const std::string& HostName() const;
const CyberConfig& Config() const;
void EnableSimulationMode();
void DisableSimulationMode();
bool IsRealityMode() const;
bool IsMockTimeMode() const;
static uint64_t GenerateHashId(const std::string& name) {
return common::Hash(name);
}
static uint64_t RegisterNode(const std::string& node_name);
static std::string GetNodeById(uint64_t id);
static uint64_t RegisterChannel(const std::string& channel);
static std::string GetChannelById(uint64_t id);
static uint64_t RegisterService(const std::string& service);
static std::string GetServiceById(uint64_t id);
static uint64_t RegisterTaskName(const std::string& task_name);
static std::string GetTaskNameById(uint64_t id);
private:
void InitHostInfo();
bool InitConfig();
// global config
CyberConfig config_;
// host info
std::string host_ip_;
std::string host_name_;
// process info
int process_id_;
std::string process_group_;
int component_nums_ = 0;
// sched policy info
std::string sched_name_ = "CYBER_DEFAULT";
// run mode
RunMode run_mode_;
ClockMode clock_mode_;
static AtomicHashMap<uint64_t, std::string, 512> node_id_map_;
static AtomicHashMap<uint64_t, std::string, 256> channel_id_map_;
static AtomicHashMap<uint64_t, std::string, 256> service_id_map_;
static AtomicHashMap<uint64_t, std::string, 256> task_id_map_;
DECLARE_SINGLETON(GlobalData)
};
} // namespace common
} // namespace cyber
} // namespace apollo
#endif // CYBER_COMMON_GLOBAL_DATA_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/macros_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/common/macros.h"
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace common {
class ClassWithShutdown {
public:
void Shutdown() { set_foo(1); }
static int foo() { return foo_; }
static void set_foo(int val) { foo_ = val; }
private:
static int foo_;
DECLARE_SINGLETON(ClassWithShutdown)
};
int ClassWithShutdown::foo_ = 0;
inline ClassWithShutdown::ClassWithShutdown() {}
class ClassWithoutShutdown {
private:
DECLARE_SINGLETON(ClassWithoutShutdown)
};
inline ClassWithoutShutdown::ClassWithoutShutdown() {}
TEST(MacrosTest, has_shut_down_test) {
EXPECT_TRUE(HasShutdown<ClassWithShutdown>::value);
EXPECT_FALSE(HasShutdown<ClassWithoutShutdown>::value);
}
TEST(MacrosTest, shut_down_test) {
EXPECT_EQ(ClassWithShutdown::foo(), 0);
ClassWithShutdown::CleanUp();
EXPECT_EQ(ClassWithShutdown::foo(), 0);
ClassWithShutdown::Instance();
ClassWithShutdown::CleanUp();
EXPECT_EQ(ClassWithShutdown::foo(), 1);
ClassWithoutShutdown::CleanUp();
ClassWithoutShutdown::Instance();
ClassWithoutShutdown::CleanUp();
}
} // namespace common
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/environment_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/common/environment.h"
#include <cstdlib>
#include "gtest/gtest.h"
namespace apollo {
namespace cyber {
namespace common {
TEST(EnvironmentTest, get_env) {
unsetenv("EnvironmentTest_get_env");
std::string env_value = GetEnv("EnvironmentTest_get_env");
EXPECT_EQ(env_value, "");
setenv("EnvironmentTest_get_env", "123456789", 1);
env_value = GetEnv("EnvironmentTest_get_env");
EXPECT_EQ(env_value, "123456789");
unsetenv("EnvironmentTest_get_env");
const std::string default_value = "DEFAULT_FOR_TEST";
EXPECT_EQ(default_value, GetEnv("SOMETHING_NOT_EXIST", default_value));
}
TEST(EnvironmentTest, work_root) {
std::string before = WorkRoot();
unsetenv("CYBER_PATH");
std::string after = GetEnv("CYBER_PATH");
EXPECT_EQ(after, "");
setenv("CYBER_PATH", before.c_str(), 1);
after = WorkRoot();
EXPECT_EQ(after, before);
}
} // namespace common
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/environment.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_COMMON_ENVIRONMENT_H_
#define CYBER_COMMON_ENVIRONMENT_H_
#include <cassert>
#include <string>
#include "cyber/common/log.h"
namespace apollo {
namespace cyber {
namespace common {
inline std::string GetEnv(const std::string& var_name,
const std::string& default_value = "") {
const char* var = std::getenv(var_name.c_str());
if (var == nullptr) {
AWARN << "Environment variable [" << var_name << "] not set, fallback to "
<< default_value;
return default_value;
}
return std::string(var);
}
inline const std::string WorkRoot() {
std::string work_root = GetEnv("CYBER_PATH");
if (work_root.empty()) {
work_root = "/apollo/cyber";
}
return work_root;
}
} // namespace common
} // namespace cyber
} // namespace apollo
#endif // CYBER_COMMON_ENVIRONMENT_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/file_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/common/file.h"
#include <cstdlib>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "cyber/proto/unit_test.pb.h"
namespace apollo {
namespace cyber {
namespace common {
TEST(FileTest, proto_set_get_test) {
apollo::cyber::proto::UnitTest message;
message.set_class_name("FileTest");
apollo::cyber::proto::UnitTest read_message;
EXPECT_FALSE(SetProtoToASCIIFile(message, -1));
EXPECT_FALSE(SetProtoToASCIIFile(message, "not_exists_dir/message.proto"));
EXPECT_TRUE(SetProtoToASCIIFile(message, "message.ascii"));
EXPECT_TRUE(SetProtoToBinaryFile(message, "message.binary"));
EXPECT_FALSE(
GetProtoFromASCIIFile("not_exists_dir/message.proto", &read_message));
EXPECT_FALSE(
GetProtoFromBinaryFile("not_exists_dir/message.proto", &read_message));
EXPECT_TRUE(GetProtoFromASCIIFile("message.ascii", &read_message));
EXPECT_TRUE(GetProtoFromBinaryFile("message.binary", &read_message));
EXPECT_FALSE(GetProtoFromFile("not_exists_dir/message.proto", &read_message));
EXPECT_TRUE(GetProtoFromFile("message.binary", &read_message));
remove("message.binary");
remove("message.ascii");
}
TEST(FileTest, file_utils_test) {
apollo::cyber::proto::UnitTest message;
message.set_class_name("FileTest");
apollo::cyber::proto::UnitTest read_message;
EXPECT_TRUE(SetProtoToBinaryFile(message, "message.binary"));
std::string content;
GetContent("message.binary", &content);
EXPECT_FALSE(content.empty());
content = "";
GetContent("not_exists_dir/message.proto", &content);
EXPECT_EQ("", content);
EXPECT_TRUE(PathExists("./"));
EXPECT_FALSE(PathExists("not_exits_file"));
EXPECT_TRUE(DirectoryExists("./"));
EXPECT_FALSE(DirectoryExists("not_exits_file"));
EXPECT_FALSE(DirectoryExists("message.binary"));
EXPECT_FALSE(CopyFile("not_exists_file", "1.txt"));
EXPECT_TRUE(CopyFile("message.binary", "message.binary.copy"));
std::string current_path = GetCurrentPath();
EXPECT_TRUE(EnsureDirectory(current_path));
EXPECT_TRUE("/not_exists_dir");
EXPECT_TRUE(EnsureDirectory(current_path + "/1"));
EXPECT_TRUE(EnsureDirectory(current_path + "/1/2"));
EXPECT_TRUE(EnsureDirectory(current_path + "/1/2/3"));
EXPECT_TRUE(EnsureDirectory(current_path + "/2"));
EXPECT_TRUE(CopyFile("message.binary", current_path + "/2/message.binary"));
EXPECT_TRUE(DirectoryExists(current_path + "/1/2/3"));
EXPECT_FALSE(RemoveAllFiles("/not_exists_dir"));
EXPECT_FALSE(RemoveAllFiles(current_path + "/1"));
EXPECT_TRUE(RemoveAllFiles(current_path + "/2"));
remove("message.binary");
remove("message.binary.copy");
rmdir((current_path + "/1/2/3").c_str());
rmdir((current_path + "/1/2").c_str());
rmdir((current_path + "/1").c_str());
rmdir((current_path + "/2").c_str());
}
TEST(FileTest, ListSubPaths) {
const auto root_subdirs = ListSubPaths("/");
// Some common root subdirs should exist.
EXPECT_NE(root_subdirs.end(),
std::find(root_subdirs.begin(), root_subdirs.end(), "home"));
EXPECT_NE(root_subdirs.end(),
std::find(root_subdirs.begin(), root_subdirs.end(), "root"));
// Something shouldn't exist.
EXPECT_EQ(root_subdirs.end(),
std::find(root_subdirs.begin(), root_subdirs.end(), "impossible"));
}
TEST(FileTest, Glob) {
// Match none.
EXPECT_TRUE(Glob("/path/impossible/*").empty());
// Match one.
EXPECT_THAT(Glob("/apollo"), testing::ElementsAre(std::string("/apollo")));
EXPECT_THAT(Glob("/apol?o"), testing::ElementsAre(std::string("/apollo")));
// Match multiple.
EXPECT_THAT(
Glob("/apol?o/modules/p*"),
testing::AllOf(
testing::Contains(std::string("/apollo/modules/perception")),
testing::Contains(std::string("/apollo/modules/planning")),
testing::Contains(std::string("/apollo/modules/prediction"))));
}
TEST(FileTest, GetAbsolutePath) {
EXPECT_EQ("./xx.txt", GetAbsolutePath("", "./xx.txt"));
EXPECT_EQ("/abc", GetAbsolutePath("/abc", ""));
EXPECT_EQ("/home/work/xx.txt", GetAbsolutePath("/home/work", "xx.txt"));
EXPECT_EQ("/home/work/xx.txt", GetAbsolutePath("/home/work/", "xx.txt"));
EXPECT_EQ("/xx.txt", GetAbsolutePath("/home/work", "/xx.txt"));
EXPECT_EQ("/home/work/./xx.txt", GetAbsolutePath("/home/work", "./xx.txt"));
}
TEST(FileTest, GetFileName) {
EXPECT_EQ("xx.txt", GetFileName("xx.txt"));
EXPECT_EQ("xx", GetFileName("./xx.txt", true));
EXPECT_EQ("xx.txt", GetFileName("./xx.txt"));
EXPECT_EQ("xx", GetFileName("./xx.txt", true));
EXPECT_EQ(".txt", GetFileName("./.txt"));
EXPECT_EQ("", GetFileName("./.txt", true));
EXPECT_EQ("txt", GetFileName("/path/.to/txt"));
EXPECT_EQ("txt", GetFileName("/path/.to/txt", true));
EXPECT_EQ("", GetFileName("/path/to/"));
EXPECT_EQ("", GetFileName("/path/to/", true));
}
} // namespace common
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/log.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.
*****************************************************************************/
/**
* @log
*/
#ifndef CYBER_COMMON_LOG_H_
#define CYBER_COMMON_LOG_H_
#include <cstdarg>
#include <string>
#include "glog/logging.h"
#include "glog/raw_logging.h"
#include "cyber/binary.h"
#define LEFT_BRACKET "["
#define RIGHT_BRACKET "]"
#ifndef MODULE_NAME
#define MODULE_NAME apollo::cyber::binary::GetName().c_str()
#endif
#define ADEBUG_MODULE(module) \
VLOG(4) << LEFT_BRACKET << module << RIGHT_BRACKET << "[DEBUG] "
#define ADEBUG ADEBUG_MODULE(MODULE_NAME)
#define AINFO ALOG_MODULE(MODULE_NAME, INFO)
#define AWARN ALOG_MODULE(MODULE_NAME, WARN)
#define AERROR ALOG_MODULE(MODULE_NAME, ERROR)
#define AFATAL ALOG_MODULE(MODULE_NAME, FATAL)
#ifndef ALOG_MODULE_STREAM
#define ALOG_MODULE_STREAM(log_severity) ALOG_MODULE_STREAM_##log_severity
#endif
#ifndef ALOG_MODULE
#define ALOG_MODULE(module, log_severity) \
ALOG_MODULE_STREAM(log_severity)(module)
#endif
#define ALOG_MODULE_STREAM_INFO(module) \
google::LogMessage(__FILE__, __LINE__, google::INFO).stream() \
<< LEFT_BRACKET << module << RIGHT_BRACKET
#define ALOG_MODULE_STREAM_WARN(module) \
google::LogMessage(__FILE__, __LINE__, google::WARNING).stream() \
<< LEFT_BRACKET << module << RIGHT_BRACKET
#define ALOG_MODULE_STREAM_ERROR(module) \
google::LogMessage(__FILE__, __LINE__, google::ERROR).stream() \
<< LEFT_BRACKET << module << RIGHT_BRACKET
#define ALOG_MODULE_STREAM_FATAL(module) \
google::LogMessage(__FILE__, __LINE__, google::FATAL).stream() \
<< LEFT_BRACKET << module << RIGHT_BRACKET
#define AINFO_IF(cond) ALOG_IF(INFO, cond, MODULE_NAME)
#define AWARN_IF(cond) ALOG_IF(WARN, cond, MODULE_NAME)
#define AERROR_IF(cond) ALOG_IF(ERROR, cond, MODULE_NAME)
#define AFATAL_IF(cond) ALOG_IF(FATAL, cond, MODULE_NAME)
#define ALOG_IF(severity, cond, module) \
!(cond) ? (void)0 \
: google::LogMessageVoidify() & ALOG_MODULE(module, severity)
#define ACHECK(cond) CHECK(cond) << LEFT_BRACKET << MODULE_NAME << RIGHT_BRACKET
#define AINFO_EVERY(freq) \
LOG_EVERY_N(INFO, freq) << LEFT_BRACKET << MODULE_NAME << RIGHT_BRACKET
#define AWARN_EVERY(freq) \
LOG_EVERY_N(WARNING, freq) << LEFT_BRACKET << MODULE_NAME << RIGHT_BRACKET
#define AERROR_EVERY(freq) \
LOG_EVERY_N(ERROR, freq) << LEFT_BRACKET << MODULE_NAME << RIGHT_BRACKET
#if !defined(RETURN_IF_NULL)
#define RETURN_IF_NULL(ptr) \
if (ptr == nullptr) { \
AWARN << #ptr << " is nullptr."; \
return; \
}
#endif
#if !defined(RETURN_VAL_IF_NULL)
#define RETURN_VAL_IF_NULL(ptr, val) \
if (ptr == nullptr) { \
AWARN << #ptr << " is nullptr."; \
return val; \
}
#endif
#if !defined(RETURN_IF)
#define RETURN_IF(condition) \
if (condition) { \
AWARN << #condition << " is met."; \
return; \
}
#endif
#if !defined(RETURN_VAL_IF)
#define RETURN_VAL_IF(condition, val) \
if (condition) { \
AWARN << #condition << " is met."; \
return val; \
}
#endif
#if !defined(_RETURN_VAL_IF_NULL2__)
#define _RETURN_VAL_IF_NULL2__
#define RETURN_VAL_IF_NULL2(ptr, val) \
if (ptr == nullptr) { \
return (val); \
}
#endif
#if !defined(_RETURN_VAL_IF2__)
#define _RETURN_VAL_IF2__
#define RETURN_VAL_IF2(condition, val) \
if (condition) { \
return (val); \
}
#endif
#if !defined(_RETURN_IF2__)
#define _RETURN_IF2__
#define RETURN_IF2(condition) \
if (condition) { \
return; \
}
#endif
#endif // CYBER_COMMON_LOG_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/macros.h
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef CYBER_COMMON_MACROS_H_
#define CYBER_COMMON_MACROS_H_
#include <iostream>
#include <memory>
#include <mutex>
#include <type_traits>
#include <utility>
#include "cyber/base/macros.h"
DEFINE_TYPE_TRAIT(HasShutdown, Shutdown)
template <typename T>
typename std::enable_if<HasShutdown<T>::value>::type CallShutdown(T *instance) {
instance->Shutdown();
}
template <typename T>
typename std::enable_if<!HasShutdown<T>::value>::type CallShutdown(
T *instance) {
(void)instance;
}
// There must be many copy-paste versions of these macros which are same
// things, undefine them to avoid conflict.
#undef UNUSED
#undef DISALLOW_COPY_AND_ASSIGN
#define UNUSED(param) (void)param
#define DISALLOW_COPY_AND_ASSIGN(classname) \
classname(const classname &) = delete; \
classname &operator=(const classname &) = delete;
#define DECLARE_SINGLETON(classname) \
public: \
static classname *Instance(bool create_if_needed = true) { \
static classname *instance = nullptr; \
if (!instance && create_if_needed) { \
static std::once_flag flag; \
std::call_once(flag, \
[&] { instance = new (std::nothrow) classname(); }); \
} \
return instance; \
} \
\
static void CleanUp() { \
auto instance = Instance(false); \
if (instance != nullptr) { \
CallShutdown(instance); \
} \
} \
\
private: \
classname(); \
DISALLOW_COPY_AND_ASSIGN(classname)
#endif // CYBER_COMMON_MACROS_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/time_conversion.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_COMMON_TIME_CONVERSION_H_
#define CYBER_COMMON_TIME_CONVERSION_H_
#include <cstdint>
#include <ctime>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
namespace apollo {
namespace cyber {
namespace common {
// Leap seconds change every a few years. See below for details.
// http://www.leapsecond.com/java/gpsclock.htm
// http://maia.usno.navy.mil/ser7/tai-utc.dat
//
// UNIX time counts seconds since 1970-1-1, without leap seconds.
// GPS time counts seconds since 1980-1-6, with leap seconds.
// When a leap second is inserted, UNIX time is ambiguous, as shown below.
// UNIX date and time UNIX epoch GPS epoch
// 2008-12-31 23:59:59.0 1230767999.0 914803213.0
// 2008-12-31 23:59:59.5 1230767999.5 914803213.5
// 2008-12-31 23:59:60.0 1230768000.0 914803214.0
// 2008-12-31 23:59:60.5 1230768000.5 914803214.5
// 2009-01-01 00:00:00.0 1230768000.0 914803215.0
// 2009-01-01 00:00:00.5 1230768000.5 914803215.5
// A table of when a leap second is inserted and cumulative leap seconds.
static const std::vector<std::pair<int32_t, int32_t>> LEAP_SECONDS = {
// UNIX time, leap seconds
// Add future leap seconds here.
{1483228800, 18}, // 2017-01-01
{1435708800, 17}, // 2015-07-01
{1341100800, 16}, // 2012-07-01
{1230768000, 15}, // 2009-01-01
{1136073600, 14}, // 2006-01-01
};
// This is number of seconds that UNIX is ahead of GPS, without leap seconds.
constexpr int32_t UNIX_GPS_DIFF = 315964800;
constexpr int64_t ONE_MILLION = 1000000L;
constexpr int64_t ONE_BILLION = 1000000000L;
template <typename T>
T UnixToGpsSeconds(T unix_seconds) {
for (size_t i = 0; i < LEAP_SECONDS.size(); ++i) {
if (unix_seconds >= LEAP_SECONDS[i].first) {
return unix_seconds - (UNIX_GPS_DIFF - LEAP_SECONDS[i].second);
}
}
return static_cast<T>(0);
}
inline int64_t UnixToGpsMicroseconds(int64_t unix_microseconds) {
return UnixToGpsSeconds(unix_microseconds / ONE_MILLION) * ONE_MILLION +
unix_microseconds % ONE_MILLION;
}
inline int64_t UnixToGpsNanoseconds(int64_t unix_nanoseconds) {
return UnixToGpsSeconds(unix_nanoseconds / ONE_BILLION) * ONE_BILLION +
unix_nanoseconds % ONE_BILLION;
}
template <typename T>
T GpsToUnixSeconds(T gps_seconds) {
for (size_t i = 0; i < LEAP_SECONDS.size(); ++i) {
T result = gps_seconds + (UNIX_GPS_DIFF - LEAP_SECONDS[i].second);
if ((int32_t)result >= LEAP_SECONDS[i].first) {
return result;
}
}
return static_cast<T>(0);
}
inline int64_t GpsToUnixMicroseconds(int64_t gps_microseconds) {
return GpsToUnixSeconds(gps_microseconds / ONE_MILLION) * ONE_MILLION +
gps_microseconds % ONE_MILLION;
}
inline int64_t GpsToUnixNanoseconds(int64_t gps_nanoseconds) {
return GpsToUnixSeconds(gps_nanoseconds / ONE_BILLION) * ONE_BILLION +
gps_nanoseconds % ONE_BILLION;
}
inline uint64_t GpsToUnixMicroseconds(uint64_t gps_microseconds) {
return GpsToUnixSeconds(gps_microseconds / ONE_MILLION) * ONE_MILLION +
gps_microseconds % ONE_MILLION;
}
inline uint64_t GpsToUnixNanoseconds(uint64_t gps_nanoseconds) {
return GpsToUnixSeconds(gps_nanoseconds / ONE_BILLION) * ONE_BILLION +
gps_nanoseconds % ONE_BILLION;
}
inline uint64_t StringToUnixSeconds(
const std::string& time_str,
const std::string& format_str = "%Y-%m-%d %H:%M:%S") {
tm tmp_time;
strptime(time_str.c_str(), format_str.c_str(), &tmp_time);
tmp_time.tm_isdst = -1;
time_t time = mktime(&tmp_time);
return static_cast<uint64_t>(time);
}
inline std::string UnixSecondsToString(
uint64_t unix_seconds,
const std::string& format_str = "%Y-%m-%d-%H:%M:%S") {
std::time_t t = unix_seconds;
struct tm ptm;
struct tm* ret = localtime_r(&t, &ptm);
if (ret == nullptr) {
return std::string("");
}
uint32_t length = 64;
std::vector<char> buff(length, '\0');
strftime(buff.data(), length, format_str.c_str(), ret);
return std::string(buff.data());
}
} // namespace common
} // namespace cyber
} // namespace apollo
#endif // CYBER_COMMON_TIME_CONVERSION_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/log_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/common/log.h"
#include "gtest/gtest.h"
#include "glog/logging.h"
namespace apollo {
namespace cyber {
namespace common {
TEST(LogTest, TestAll) { AINFO << "11111"; }
} // namespace common
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/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.
*****************************************************************************/
#ifndef CYBER_COMMON_UTIL_H_
#define CYBER_COMMON_UTIL_H_
#include <string>
#include <type_traits>
namespace apollo {
namespace cyber {
namespace common {
inline std::size_t Hash(const std::string& key) {
return std::hash<std::string>{}(key);
}
template <typename Enum>
auto ToInt(Enum const value) -> typename std::underlying_type<Enum>::type {
return static_cast<typename std::underlying_type<Enum>::type>(value);
}
} // namespace common
} // namespace cyber
} // namespace apollo
#endif // CYBER_COMMON_UTIL_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
cc_library(
name = "common",
deps = [
"//cyber/common:environment",
"//cyber/common:file",
"//cyber/common:global_data",
"//cyber/common:log",
"//cyber/common:macros",
"//cyber/common:time_conversion",
"//cyber/common:types",
"//cyber/common:util",
],
)
cc_library(
name = "file",
srcs = ["file.cc"],
hdrs = ["file.h"],
deps = [
"//cyber/common:log",
"@com_google_protobuf//:protobuf",
"@com_github_nlohmann_json//:json",
],
)
cc_test(
name = "file_test",
size = "small",
srcs = ["file_test.cc"],
deps = [
"//cyber",
"//cyber/proto:unit_test_cc_proto",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "log",
hdrs = ["log.h"],
deps = [
"//cyber:binary",
"@com_github_google_glog//:glog",
],
)
cc_test(
name = "log_test",
size = "small",
srcs = ["log_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_library(
name = "environment",
hdrs = ["environment.h"],
deps = [
"//cyber/common:log",
],
)
cc_test(
name = "environment_test",
size = "small",
srcs = ["environment_test.cc"],
deps = [
":environment",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "global_data",
srcs = ["global_data.cc"],
hdrs = ["global_data.h"],
data = [
"//cyber:cyber_conf",
],
deps = [
"//cyber/base:atomic_hash_map",
"//cyber/base:atomic_rw_lock",
"//cyber/common:environment",
"//cyber/common:file",
"//cyber/common:macros",
"//cyber/common:util",
"//cyber/proto:cyber_conf_cc_proto",
],
)
cc_test(
name = "macros_test",
size = "small",
srcs = ["macros_test.cc"],
deps = [
"//cyber",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "macros",
hdrs = ["macros.h"],
deps = [
"//cyber/base:macros",
],
)
cc_library(
name = "time_conversion",
hdrs = ["time_conversion.h"],
)
cc_library(
name = "types",
hdrs = ["types.h"],
)
cc_library(
name = "util",
hdrs = ["util.h"],
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/common/global_data.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/common/global_data.h"
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstdlib>
#include <functional>
#include "cyber/common/environment.h"
#include "cyber/common/file.h"
namespace apollo {
namespace cyber {
namespace common {
AtomicHashMap<uint64_t, std::string, 512> GlobalData::node_id_map_;
AtomicHashMap<uint64_t, std::string, 256> GlobalData::channel_id_map_;
AtomicHashMap<uint64_t, std::string, 256> GlobalData::service_id_map_;
AtomicHashMap<uint64_t, std::string, 256> GlobalData::task_id_map_;
namespace {
const std::string& kEmptyString = "";
std::string program_path() {
char path[PATH_MAX];
auto len = readlink("/proc/self/exe", path, sizeof(path) - 1);
if (len == -1) {
return kEmptyString;
}
path[len] = '\0';
return std::string(path);
}
} // namespace
GlobalData::GlobalData() {
InitHostInfo();
ACHECK(InitConfig());
process_id_ = getpid();
auto prog_path = program_path();
if (!prog_path.empty()) {
process_group_ = GetFileName(prog_path) + "_" + std::to_string(process_id_);
} else {
process_group_ = "cyber_default_" + std::to_string(process_id_);
}
const auto& run_mode_conf = config_.run_mode_conf();
run_mode_ = run_mode_conf.run_mode();
clock_mode_ = run_mode_conf.clock_mode();
}
GlobalData::~GlobalData() {}
int GlobalData::ProcessId() const { return process_id_; }
void GlobalData::SetProcessGroup(const std::string& process_group) {
process_group_ = process_group;
}
const std::string& GlobalData::ProcessGroup() const { return process_group_; }
void GlobalData::SetComponentNums(const int component_nums) {
component_nums_ = component_nums;
}
int GlobalData::ComponentNums() const { return component_nums_; }
void GlobalData::SetSchedName(const std::string& sched_name) {
sched_name_ = sched_name;
}
const std::string& GlobalData::SchedName() const { return sched_name_; }
const std::string& GlobalData::HostIp() const { return host_ip_; }
const std::string& GlobalData::HostName() const { return host_name_; }
void GlobalData::EnableSimulationMode() {
run_mode_ = RunMode::MODE_SIMULATION;
}
void GlobalData::DisableSimulationMode() { run_mode_ = RunMode::MODE_REALITY; }
bool GlobalData::IsRealityMode() const {
return run_mode_ == RunMode::MODE_REALITY;
}
bool GlobalData::IsMockTimeMode() const {
return clock_mode_ == ClockMode::MODE_MOCK;
}
void GlobalData::InitHostInfo() {
char host_name[1024];
gethostname(host_name, sizeof(host_name));
host_name_ = host_name;
host_ip_ = "127.0.0.1";
// if we have exported a non-loopback CYBER_IP, we will use it firstly,
// otherwise, we try to find first non-loopback ipv4 addr.
const char* ip_env = getenv("CYBER_IP");
if (ip_env != nullptr) {
// maybe we need to verify ip_env
std::string ip_env_str(ip_env);
std::string starts = ip_env_str.substr(0, 3);
if (starts != "127") {
host_ip_ = ip_env_str;
AINFO << "host ip: " << host_ip_;
return;
}
}
ifaddrs* ifaddr = nullptr;
if (getifaddrs(&ifaddr) != 0) {
AERROR << "getifaddrs failed, we will use 127.0.0.1 as host ip.";
return;
}
for (ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == nullptr) {
continue;
}
int family = ifa->ifa_addr->sa_family;
if (family != AF_INET) {
continue;
}
char addr[NI_MAXHOST] = {0};
if (getnameinfo(ifa->ifa_addr, sizeof(sockaddr_in), addr, NI_MAXHOST, NULL,
0, NI_NUMERICHOST) != 0) {
continue;
}
std::string tmp_ip(addr);
std::string starts = tmp_ip.substr(0, 3);
if (starts != "127") {
host_ip_ = tmp_ip;
break;
}
}
freeifaddrs(ifaddr);
AINFO << "host ip: " << host_ip_;
}
bool GlobalData::InitConfig() {
auto config_path = GetAbsolutePath(WorkRoot(), "conf/cyber.pb.conf");
if (!GetProtoFromFile(config_path, &config_)) {
AERROR << "read cyber default conf failed!";
return false;
}
return true;
}
const CyberConfig& GlobalData::Config() const { return config_; }
uint64_t GlobalData::RegisterNode(const std::string& node_name) {
auto id = Hash(node_name);
while (node_id_map_.Has(id)) {
std::string* name = nullptr;
node_id_map_.Get(id, &name);
if (node_name == *name) {
break;
}
++id;
AWARN << " Node name hash collision: " << node_name << " <=> " << *name;
}
node_id_map_.Set(id, node_name);
return id;
}
std::string GlobalData::GetNodeById(uint64_t id) {
std::string* node_name = nullptr;
if (node_id_map_.Get(id, &node_name)) {
return *node_name;
}
return kEmptyString;
}
uint64_t GlobalData::RegisterChannel(const std::string& channel) {
auto id = Hash(channel);
while (channel_id_map_.Has(id)) {
std::string* name = nullptr;
channel_id_map_.Get(id, &name);
if (channel == *name) {
break;
}
++id;
AWARN << "Channel name hash collision: " << channel << " <=> " << *name;
}
channel_id_map_.Set(id, channel);
return id;
}
std::string GlobalData::GetChannelById(uint64_t id) {
std::string* channel = nullptr;
if (channel_id_map_.Get(id, &channel)) {
return *channel;
}
return kEmptyString;
}
uint64_t GlobalData::RegisterService(const std::string& service) {
auto id = Hash(service);
while (service_id_map_.Has(id)) {
std::string* name = nullptr;
service_id_map_.Get(id, &name);
if (service == *name) {
break;
}
++id;
AWARN << "Service name hash collision: " << service << " <=> " << *name;
}
service_id_map_.Set(id, service);
return id;
}
std::string GlobalData::GetServiceById(uint64_t id) {
std::string* service = nullptr;
if (service_id_map_.Get(id, &service)) {
return *service;
}
return kEmptyString;
}
uint64_t GlobalData::RegisterTaskName(const std::string& task_name) {
auto id = Hash(task_name);
while (task_id_map_.Has(id)) {
std::string* name = nullptr;
task_id_map_.Get(id, &name);
if (task_name == *name) {
break;
}
++id;
AWARN << "Task name hash collision: " << task_name << " <=> " << *name;
}
task_id_map_.Set(id, task_name);
return id;
}
std::string GlobalData::GetTaskNameById(uint64_t id) {
std::string* task_name = nullptr;
if (task_id_map_.Get(id, &task_name)) {
return *task_name;
}
return kEmptyString;
}
} // namespace common
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/mainboard/module_argument.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/mainboard/module_argument.h"
#include <getopt.h>
#include <libgen.h>
using apollo::cyber::common::GlobalData;
namespace apollo {
namespace cyber {
namespace mainboard {
void ModuleArgument::DisplayUsage() {
AINFO << "Usage: \n " << binary_name_ << " [OPTION]...\n"
<< "Description: \n"
<< " -h, --help : help information \n"
<< " -d, --dag_conf=CONFIG_FILE : module dag config file\n"
<< " -p, --process_group=process_group: the process "
"namespace for running this module, default in manager process\n"
<< " -s, --sched_name=sched_name: sched policy "
"conf for hole process, sched_name should be conf in cyber.pb.conf\n"
<< "Example:\n"
<< " " << binary_name_ << " -h\n"
<< " " << binary_name_ << " -d dag_conf_file1 -d dag_conf_file2 "
<< "-p process_group -s sched_name\n";
}
void ModuleArgument::ParseArgument(const int argc, char* const argv[]) {
binary_name_ = std::string(basename(argv[0]));
GetOptions(argc, argv);
if (process_group_.empty()) {
process_group_ = DEFAULT_process_group_;
}
if (sched_name_.empty()) {
sched_name_ = DEFAULT_sched_name_;
}
GlobalData::Instance()->SetProcessGroup(process_group_);
GlobalData::Instance()->SetSchedName(sched_name_);
AINFO << "binary_name_ is " << binary_name_ << ", process_group_ is "
<< process_group_ << ", has " << dag_conf_list_.size() << " dag conf";
for (std::string& dag : dag_conf_list_) {
AINFO << "dag_conf: " << dag;
}
}
void ModuleArgument::GetOptions(const int argc, char* const argv[]) {
opterr = 0; // extern int opterr
int long_index = 0;
const std::string short_opts = "hd:p:s:";
static const struct option long_opts[] = {
{"help", no_argument, nullptr, 'h'},
{"dag_conf", required_argument, nullptr, 'd'},
{"process_name", required_argument, nullptr, 'p'},
{"sched_name", required_argument, nullptr, 's'},
{NULL, no_argument, nullptr, 0}};
// log command for info
std::string cmd("");
for (int i = 0; i < argc; ++i) {
cmd += argv[i];
cmd += " ";
}
AINFO << "command: " << cmd;
if (1 == argc) {
DisplayUsage();
exit(0);
}
do {
int opt =
getopt_long(argc, argv, short_opts.c_str(), long_opts, &long_index);
if (opt == -1) {
break;
}
switch (opt) {
case 'd':
dag_conf_list_.emplace_back(std::string(optarg));
for (int i = optind; i < argc; i++) {
if (*argv[i] != '-') {
dag_conf_list_.emplace_back(std::string(argv[i]));
} else {
break;
}
}
break;
case 'p':
process_group_ = std::string(optarg);
break;
case 's':
sched_name_ = std::string(optarg);
break;
case 'h':
DisplayUsage();
exit(0);
default:
break;
}
} while (true);
if (optind < argc) {
AINFO << "Found non-option ARGV-element \"" << argv[optind++] << "\"";
DisplayUsage();
exit(1);
}
if (dag_conf_list_.empty()) {
AINFO << "-d parameter must be specified";
DisplayUsage();
exit(1);
}
}
} // namespace mainboard
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/mainboard/module_controller.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_MAINBOARD_MODULE_CONTROLLER_H_
#define CYBER_MAINBOARD_MODULE_CONTROLLER_H_
#include <memory>
#include <string>
#include <vector>
#include "cyber/proto/dag_conf.pb.h"
#include "cyber/class_loader/class_loader_manager.h"
#include "cyber/component/component.h"
#include "cyber/mainboard/module_argument.h"
namespace apollo {
namespace cyber {
namespace mainboard {
using apollo::cyber::proto::DagConfig;
class ModuleController {
public:
explicit ModuleController(const ModuleArgument& args);
virtual ~ModuleController() = default;
bool Init();
bool LoadAll();
void Clear();
private:
bool LoadModule(const std::string& path);
bool LoadModule(const DagConfig& dag_config);
int GetComponentNum(const std::string& path);
int total_component_nums = 0;
bool has_timer_component = false;
ModuleArgument args_;
class_loader::ClassLoaderManager class_loader_manager_;
std::vector<std::shared_ptr<ComponentBase>> component_list_;
};
inline ModuleController::ModuleController(const ModuleArgument& args)
: args_(args) {}
inline bool ModuleController::Init() { return LoadAll(); }
} // namespace mainboard
} // namespace cyber
} // namespace apollo
#endif // CYBER_MAINBOARD_MODULE_CONTROLLER_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/mainboard/module_controller.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/mainboard/module_controller.h"
#include <utility>
#include "cyber/common/environment.h"
#include "cyber/common/file.h"
#include "cyber/component/component_base.h"
namespace apollo {
namespace cyber {
namespace mainboard {
void ModuleController::Clear() {
for (auto& component : component_list_) {
component->Shutdown();
}
component_list_.clear(); // keep alive
class_loader_manager_.UnloadAllLibrary();
}
bool ModuleController::LoadAll() {
const std::string work_root = common::WorkRoot();
const std::string current_path = common::GetCurrentPath();
const std::string dag_root_path = common::GetAbsolutePath(work_root, "dag");
std::vector<std::string> paths;
for (auto& dag_conf : args_.GetDAGConfList()) {
std::string module_path = "";
if (dag_conf == common::GetFileName(dag_conf)) {
// case dag conf argument var is a filename
module_path = common::GetAbsolutePath(dag_root_path, dag_conf);
} else if (dag_conf[0] == '/') {
// case dag conf argument var is an absolute path
module_path = dag_conf;
} else {
// case dag conf argument var is a relative path
module_path = common::GetAbsolutePath(current_path, dag_conf);
if (!common::PathExists(module_path)) {
module_path = common::GetAbsolutePath(work_root, dag_conf);
}
}
total_component_nums += GetComponentNum(module_path);
paths.emplace_back(std::move(module_path));
}
if (has_timer_component) {
total_component_nums += scheduler::Instance()->TaskPoolSize();
}
common::GlobalData::Instance()->SetComponentNums(total_component_nums);
for (auto module_path : paths) {
AINFO << "Start initialize dag: " << module_path;
if (!LoadModule(module_path)) {
AERROR << "Failed to load module: " << module_path;
return false;
}
}
return true;
}
bool ModuleController::LoadModule(const DagConfig& dag_config) {
const std::string work_root = common::WorkRoot();
for (auto module_config : dag_config.module_config()) {
std::string load_path;
if (module_config.module_library().front() == '/') {
load_path = module_config.module_library();
} else {
load_path =
common::GetAbsolutePath(work_root, module_config.module_library());
}
if (!common::PathExists(load_path)) {
AERROR << "Path does not exist: " << load_path;
return false;
}
class_loader_manager_.LoadLibrary(load_path);
for (auto& component : module_config.components()) {
const std::string& class_name = component.class_name();
std::shared_ptr<ComponentBase> base =
class_loader_manager_.CreateClassObj<ComponentBase>(class_name);
if (base == nullptr || !base->Initialize(component.config())) {
return false;
}
component_list_.emplace_back(std::move(base));
}
for (auto& component : module_config.timer_components()) {
const std::string& class_name = component.class_name();
std::shared_ptr<ComponentBase> base =
class_loader_manager_.CreateClassObj<ComponentBase>(class_name);
if (base == nullptr || !base->Initialize(component.config())) {
return false;
}
component_list_.emplace_back(std::move(base));
}
}
return true;
}
bool ModuleController::LoadModule(const std::string& path) {
DagConfig dag_config;
if (!common::GetProtoFromFile(path, &dag_config)) {
AERROR << "Get proto failed, file: " << path;
return false;
}
return LoadModule(dag_config);
}
int ModuleController::GetComponentNum(const std::string& path) {
DagConfig dag_config;
int component_nums = 0;
if (common::GetProtoFromFile(path, &dag_config)) {
for (auto module_config : dag_config.module_config()) {
component_nums += module_config.components_size();
if (module_config.timer_components_size() > 0) {
has_timer_component = true;
}
}
}
return component_nums;
}
} // namespace mainboard
} // namespace cyber
} // namespace apollo
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/mainboard/mainboard.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/common/global_data.h"
#include "cyber/common/log.h"
#include "cyber/init.h"
#include "cyber/mainboard/module_argument.h"
#include "cyber/mainboard/module_controller.h"
#include "cyber/state.h"
using apollo::cyber::mainboard::ModuleArgument;
using apollo::cyber::mainboard::ModuleController;
int main(int argc, char** argv) {
// parse the argument
ModuleArgument module_args;
module_args.ParseArgument(argc, argv);
// initialize cyber
apollo::cyber::Init(argv[0]);
// start module
ModuleController controller(module_args);
if (!controller.Init()) {
controller.Clear();
AERROR << "module start error.";
return -1;
}
apollo::cyber::WaitForShutdown();
controller.Clear();
AINFO << "exit mainboard.";
return 0;
}
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/mainboard/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_binary")
load("//tools:cpplint.bzl", "cpplint")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
cc_binary(
name = "mainboard",
srcs = [
"mainboard.cc",
"module_argument.cc",
"module_argument.h",
"module_controller.cc",
"module_controller.h",
],
linkopts = ["-pthread"],
deps = [
"//cyber:cyber_core",
"//cyber/proto:dag_conf_cc_proto",
],
)
install(
name = "install",
runtime_dest = "cyber/bin",
targets = [":mainboard"],
)
cpplint()
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/mainboard/module_argument.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_MAINBOARD_MODULE_ARGUMENT_H_
#define CYBER_MAINBOARD_MODULE_ARGUMENT_H_
#include <list>
#include <string>
#include "cyber/common/global_data.h"
#include "cyber/common/log.h"
#include "cyber/common/types.h"
namespace apollo {
namespace cyber {
namespace mainboard {
static const char DEFAULT_process_group_[] = "mainboard_default";
static const char DEFAULT_sched_name_[] = "CYBER_DEFAULT";
class ModuleArgument {
public:
ModuleArgument() = default;
virtual ~ModuleArgument() = default;
void DisplayUsage();
void ParseArgument(int argc, char* const argv[]);
void GetOptions(const int argc, char* const argv[]);
const std::string& GetBinaryName() const;
const std::string& GetProcessGroup() const;
const std::string& GetSchedName() const;
const std::list<std::string>& GetDAGConfList() const;
private:
std::list<std::string> dag_conf_list_;
std::string binary_name_;
std::string process_group_;
std::string sched_name_;
};
inline const std::string& ModuleArgument::GetBinaryName() const {
return binary_name_;
}
inline const std::string& ModuleArgument::GetProcessGroup() const {
return process_group_;
}
inline const std::string& ModuleArgument::GetSchedName() const {
return sched_name_;
}
inline const std::list<std::string>& ModuleArgument::GetDAGConfList() const {
return dag_conf_list_;
}
} // namespace mainboard
} // namespace cyber
} // namespace apollo
#endif // CYBER_MAINBOARD_MODULE_ARGUMENT_H_
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/doxy-docs/environment.yml
|
name: CyberRT
channels:
- conda-forge
dependencies:
- breathe
- recommonmark
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/doxy-docs/Makefile
|
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext api
default: html
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
rm -rf xml
html:
doxygen
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
doxygen
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
doxygen
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
doxygen
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
doxygen
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
doxygen
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
epub:
doxygen
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
doxygen
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
doxygen
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
doxygen
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
doxygen
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
doxygen
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
doxygen
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
doxygen
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
doxygen
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
doxygen
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
doxygen
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
doxygen
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
coverage:
doxygen
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
xml:
doxygen
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
doxygen
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
| 0
|
apollo_public_repos/apollo/cyber
|
apollo_public_repos/apollo/cyber/doxy-docs/make.bat
|
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
:end
popd
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.