From 6b656496d5433b46b629d94d5e45e37357e816f0 Mon Sep 17 00:00:00 2001 From: wangyb0625 Date: Thu, 5 May 2022 20:38:46 +0800 Subject: [PATCH 1/2] =?UTF-8?q?Timer=E9=87=8D=E6=9E=84=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=BC=96=E8=AF=91=20Signed-off-by:=20wangyb0625=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication/dm_auth_manager.h | 4 +- .../include/dependency/timer/dm_timer.h | 109 +++----- .../devicestate/dm_device_state_manager.h | 4 +- .../include/discovery/dm_discovery_manager.h | 4 +- .../src/authentication/dm_auth_manager.cpp | 71 +++--- .../src/dependency/timer/dm_timer.cpp | 238 +++++++----------- .../devicestate/dm_device_state_manager.cpp | 36 +-- .../src/discovery/dm_discovery_manager.cpp | 28 +-- test/unittest/BUILD.gn | 1 - 9 files changed, 184 insertions(+), 311 deletions(-) diff --git a/services/devicemanagerservice/include/authentication/dm_auth_manager.h b/services/devicemanagerservice/include/authentication/dm_auth_manager.h index 700c965fd..c5f69a69c 100644 --- a/services/devicemanagerservice/include/authentication/dm_auth_manager.h +++ b/services/devicemanagerservice/include/authentication/dm_auth_manager.h @@ -301,7 +301,7 @@ public: * @tc.desc: Handle Authenticate Timeout of the DeviceManager Authenticate Manager * @tc.type: FUNC */ - int32_t HandleAuthenticateTimeout(); + void HandleAuthenticateTimeout(std::string name); /** * @tc.name: DmAuthManager::CancelDisplay @@ -384,7 +384,7 @@ private: std::shared_ptr authRequestContext_; std::shared_ptr authResponseContext_; std::shared_ptr authMessageProcessor_; - std::shared_ptr timerHeap_; + std::shared_ptr timer_; std::shared_ptr dmAbilityMgr_; bool isCryptoSupport_ = false; bool isFinishOfLocal_ = true; diff --git a/services/devicemanagerservice/include/dependency/timer/dm_timer.h b/services/devicemanagerservice/include/dependency/timer/dm_timer.h index eafdd5325..5c2ddff48 100644 --- a/services/devicemanagerservice/include/dependency/timer/dm_timer.h +++ b/services/devicemanagerservice/include/dependency/timer/dm_timer.h @@ -13,85 +13,56 @@ * limitations under the License. */ -#ifndef TIMER_H -#define TIMER_H +#ifndef DM_TIMER_H +#define DM_TIMER_H -#include -#include +#include +#include +#include +#include #include #include -#include -#include -#include +#include #include -#include + namespace OHOS { namespace DistributedHardware { -typedef void (*TimeoutHandle)(void *data, std::string timerName); -class DmTimer { -public: - DmTimer(std::string name, time_t expire, void *user, TimeoutHandle mHandle) - :userData_(user), timerName_(name), expire_(expire), mHandle_(mHandle) {}; -public: - void *userData_; - bool isTrigger = false; - std::string timerName_; - time_t expire_; - TimeoutHandle mHandle_; -}; - -class TimeHeap { -public: - TimeHeap(); - ~TimeHeap(); - /** - * @tc.name: TimeHeap::AddTimer - * @tc.desc: Add timer to time heap - * @tc.type: FUNC - */ - int32_t AddTimer(std::string name, int timeout, TimeoutHandle mHandle, void *user); +constexpr int32_t DELAY_TICK_MILLSECONDS = 1000; +typedef std::chrono::steady_clock::time_point timerPoint; +typedef std::chrono::steady_clock steadyClock; +typedef std::chrono::duration> timerDuration; +using TimerCallback = std::function; +const int32_t MILLISECOND_TO_SECOND = 1000; - /** - * @tc.name: TimeHeap::DelTimer - * @tc.desc: Delete timer of the time heap - * @tc.type: FUNC - */ - int32_t DelTimer(std::string name); +struct Timer +{ + std::string timerName; + timerPoint expire; + bool state; + int32_t timeOut; + TimerCallback callback; - /** - * @tc.name: TimeHeap::DelAll - * @tc.desc: Delete all timer of the time heap - * @tc.type: FUNC - */ - int32_t DelAll(); - -private: - /** - * @tc.name: TimeHeap::Run - * @tc.desc: timer wait for timeout - * @tc.type: FUNC - */ - void Run(); - - /** - * @tc.name: TimeHeap::Run - * @tc.desc: timerout event triggering - * @tc.type: FUNC - */ - int32_t Tick(); + bool operator==(const Timer& obj) const + { + return obj.timerName == timerName; + } +}; - /** - * @tc.name: TimeHeap::Run - * @tc.desc: sort the time heap - * @tc.type: FUNC - */ - int32_t MoveUp(std::shared_ptr timer); +bool Compare(const Timer &frontTimer, const Timer &timer); +class DmTimer { +public: + DmTimer(); + ~DmTimer(); + int32_t StartTimer(std::string name, int32_t time, TimerCallback callback); + int32_t DeleteTimer(std::string name); + int32_t DeleteAll(); private: - int32_t hsize_ = 0; - int32_t epollFd_; - int32_t pipefd[2]; - std::thread mThread_; - std::vector> minHeap_; + mutable std::mutex timerMutex_; + mutable std::mutex timerStateMutex_; + std::vector timerHeap_; + std::atomic timerState_{false}; + std::condition_variable runTimerCondition_; + std::condition_variable stopTimerCondition_; }; } } diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index 95a59c511..06d9a1bc4 100755 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -135,7 +135,7 @@ public: * @tc.desc: Delete TimeOut Group of the Dm Device State Manager * @tc.type: FUNC */ - void DeleteTimeOutGroup(std::string stateTimer); + void DeleteTimeOutGroup(std::string name); /** * @tc.name: DmDeviceStateManager::RegisterDevStateCallback @@ -163,7 +163,7 @@ private: std::map remoteDeviceInfos_; std::map decisionInfos_; std::map stateTimerInfoMap_; - std::shared_ptr timerHeap_; + std::shared_ptr timer_; std::shared_ptr hiChainConnector_; std::string decisionSoName_; }; diff --git a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h index 00e756b36..135be035c 100644 --- a/services/devicemanagerservice/include/discovery/dm_discovery_manager.h +++ b/services/devicemanagerservice/include/discovery/dm_discovery_manager.h @@ -77,14 +77,14 @@ public: * @tc.desc: Handle Discovery Timeout of the Dm Discovery Manager * @tc.type: FUNC */ - void HandleDiscoveryTimeout(); + void HandleDiscoveryTimeout(std::string name); private: std::shared_ptr softbusConnector_; std::shared_ptr listener_; std::queue discoveryQueue_; std::map discoveryContextMap_; - std::shared_ptr timerHeap_; + std::shared_ptr timer_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index d075d871d..436b6a3b4 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -40,23 +40,6 @@ const int32_t WAIT_REQUEST_TIMEOUT = 10; const int32_t CANCEL_PIN_CODE_DISPLAY = 1; const int32_t DEVICE_ID_HALF = 2; -static void TimeOut(void *data, std::string timerName) -{ - LOGI("time out %s", timerName.c_str()); - if (data == nullptr || timerName.find(TIMER_PREFIX) != TIMER_DEFAULT) { - LOGE("time out is not our timer"); - return; - } - - DmAuthManager *authMgr = (DmAuthManager *)data; - if (authMgr == nullptr) { - LOGE("authMgr is nullptr"); - return; - } - - authMgr->HandleAuthenticateTimeout(); -} - DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, std::shared_ptr listener, std::shared_ptr hiChainConnector) @@ -100,6 +83,11 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au return DM_INPUT_PARA_EMPTY; } + if (timer_ == nullptr) { + timer_ = std::make_shared(); + } + timer_->StartTimer(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT, + [this](std::string name){DmAuthManager::HandleAuthenticateTimeout(name);}); authMessageProcessor_ = std::make_shared(shared_from_this()); authResponseContext_ = std::make_shared(); authRequestContext_ = std::make_shared(); @@ -130,10 +118,6 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au authRequestState_->SetAuthManager(shared_from_this()); authRequestState_->SetAuthContext(authRequestContext_); authRequestState_->Enter(); - if (timerHeap_ == nullptr) { - timerHeap_ = std::make_shared(); - } - timerHeap_->AddTimer(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT, TimeOut, this); LOGI("DmAuthManager::AuthenticateDevice complete"); return DM_OK; } @@ -178,7 +162,7 @@ int32_t DmAuthManager::VerifyAuthentication(const std::string &authParam) LOGE("DmAuthManager::authenticationMap_ is null"); return DM_FAILED; } - timerHeap_->DelTimer(INPUT_TIMEOUT_TASK); + timer_->DeleteTimer(INPUT_TIMEOUT_TASK); ptr = authenticationMap_[authResponseContext_->authType]; int32_t ret = ptr->VerifyAuthentication(authResponseContext_->authToken, authParam); switch (ret) { @@ -209,9 +193,11 @@ void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int3 authResponseState_->SetAuthManager(shared_from_this()); authResponseState_->Enter(); authResponseContext_ = std::make_shared(); - timerHeap_ = std::make_shared(); - timerHeap_->AddTimer(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT, TimeOut, this); - timerHeap_->AddTimer(WAIT_NEGOTIATE_TIMEOUT_TASK, WAIT_NEGOTIATE_TIMEOUT, TimeOut, this); + timer_ = std::make_shared(); + timer_->StartTimer(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT, + [this](std::string name){DmAuthManager::HandleAuthenticateTimeout(name);}); + timer_->StartTimer(WAIT_NEGOTIATE_TIMEOUT_TASK, WAIT_NEGOTIATE_TIMEOUT, + [this](std::string name){DmAuthManager::HandleAuthenticateTimeout(name);}); } else { std::shared_ptr authMessageProcessor = std::make_shared(shared_from_this()); @@ -291,7 +277,7 @@ void DmAuthManager::OnDataReceived(const int32_t sessionId, const std::string me switch (authResponseContext_->msgType) { case MSG_TYPE_NEGOTIATE: if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) { - timerHeap_->DelTimer(WAIT_NEGOTIATE_TIMEOUT_TASK); + timer_->DeleteTimer(WAIT_NEGOTIATE_TIMEOUT_TASK); authResponseState_->TransitionTo(std::make_shared()); } else { LOGE("Device manager auth state error"); @@ -299,7 +285,7 @@ void DmAuthManager::OnDataReceived(const int32_t sessionId, const std::string me break; case MSG_TYPE_REQ_AUTH: if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) { - timerHeap_->DelTimer(WAIT_REQUEST_TIMEOUT_TASK); + timer_->DeleteTimer(WAIT_REQUEST_TIMEOUT_TASK); authResponseState_->TransitionTo(std::make_shared()); } else { LOGE("Device manager auth state error"); @@ -354,7 +340,7 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) { LOGI("DmAuthManager OnMemberJoin start"); if (authRequestState_ != nullptr) { - timerHeap_->DelTimer(ADD_TIMEOUT_TASK); + timer_->DeleteTimer(ADD_TIMEOUT_TASK); if (status != DM_OK || authResponseContext_->requestId != requestId) { if (authRequestState_ != nullptr) { authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; @@ -367,7 +353,7 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) } } -int32_t DmAuthManager::HandleAuthenticateTimeout() +void DmAuthManager::HandleAuthenticateTimeout(std::string name) { LOGI("DmAuthManager::HandleAuthenticateTimeout start"); if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) { @@ -385,7 +371,6 @@ int32_t DmAuthManager::HandleAuthenticateTimeout() authResponseState_->TransitionTo(std::make_shared()); } LOGI("DmAuthManager::HandleAuthenticateTimeout start complete"); - return DM_OK; } int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId) @@ -413,7 +398,8 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); - timerHeap_->AddTimer(NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT, TimeOut, this); + timer_->StartTimer(NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT, + [this](std::string name){DmAuthManager::HandleAuthenticateTimeout(name);}); } void DmAuthManager::RespNegotiate(const int32_t &sessionId) @@ -452,13 +438,14 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) jsonObject[TAG_CRYPTO_SUPPORT] = "false"; message = jsonObject.dump(); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); - timerHeap_->AddTimer(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT, TimeOut, this); + timer_->StartTimer(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT, + [this](std::string name){DmAuthManager::HandleAuthenticateTimeout(name);}); } void DmAuthManager::SendAuthRequest(const int32_t &sessionId) { LOGI("DmAuthManager::EstablishAuthChannel session id"); - timerHeap_->DelTimer(NEGOTIATE_TIMEOUT_TASK); + timer_->DeleteTimer(NEGOTIATE_TIMEOUT_TASK); if (authResponseContext_->cryptoSupport) { isCryptoSupport_ = true; } @@ -470,7 +457,8 @@ void DmAuthManager::SendAuthRequest(const int32_t &sessionId) for (auto msg : messageList) { softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); } - timerHeap_->AddTimer(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT, TimeOut, this); + timer_->StartTimer(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT, + [this](std::string name){DmAuthManager::HandleAuthenticateTimeout(name);}); } int32_t DmAuthManager::StartAuthProcess(const int32_t &action) @@ -496,10 +484,10 @@ int32_t DmAuthManager::StartAuthProcess(const int32_t &action) void DmAuthManager::StartRespAuthProcess() { LOGI("DmAuthManager::StartRespAuthProcess", authResponseContext_->sessionId); - timerHeap_->DelTimer(CONFIRM_TIMEOUT_TASK); + timer_->DeleteTimer(CONFIRM_TIMEOUT_TASK); if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH) { - timerHeap_->AddTimer(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT, TimeOut, this); - authRequestState_->TransitionTo(std::make_shared()); + timer_->StartTimer(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT, + [this](std::string name){DmAuthManager::HandleAuthenticateTimeout(name);}); } else { LOGE("do not accept"); authResponseContext_->state = AuthState::AUTH_REQUEST_REPLY; @@ -534,7 +522,8 @@ int32_t DmAuthManager::AddMember(const std::string &deviceId) jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; std::string connectInfo = jsonObject.dump(); - timerHeap_->AddTimer(ADD_TIMEOUT_TASK, ADD_TIMEOUT, TimeOut, this); + timer_->StartTimer(ADD_TIMEOUT_TASK, ADD_TIMEOUT, + [this](std::string name){DmAuthManager::HandleAuthenticateTimeout(name);}); int32_t ret = hiChainConnector_->AddMember(deviceId, connectInfo); if (ret != 0) { return DM_FAILED; @@ -561,7 +550,7 @@ std::string DmAuthManager::GetConnectAddr(std::string deviceId) int32_t DmAuthManager::JoinNetwork() { LOGI("DmAuthManager JoinNetwork start"); - timerHeap_->DelTimer(AUTHENTICATE_TIMEOUT_TASK); + timer_->DeleteTimer(AUTHENTICATE_TIMEOUT_TASK); authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestContext_->reason = DM_OK; authRequestState_->TransitionTo(std::make_shared()); @@ -586,7 +575,7 @@ void DmAuthManager::AuthenticateFinish() std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE); softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); } - timerHeap_->DelAll(); + timer_->DeleteAll(); isFinishOfLocal_ = true; authResponseContext_ = nullptr; authResponseState_ = nullptr; @@ -611,7 +600,7 @@ void DmAuthManager::AuthenticateFinish() listener_->OnAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, authRequestContext_->token, authResponseContext_->state, authRequestContext_->reason); softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); - timerHeap_->DelAll(); + timer_->DeleteAll(); isFinishOfLocal_ = true; authRequestContext_ = nullptr; authResponseContext_ = nullptr; diff --git a/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp b/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp index b8b0c8c6b..50b676ae4 100644 --- a/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp +++ b/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp @@ -17,181 +17,127 @@ #include "dm_log.h" #include "dm_timer.h" +#include + namespace OHOS { namespace DistributedHardware { -int32_t TimeHeap::Tick() +bool Compare(const Timer &frontTimer, const Timer &timer) { - LOGI("Tick start"); - if (hsize_ == 0) { - LOGE("Timer count is 0"); - return DM_AUTH_NO_TIMER; - } - - std::shared_ptr top = minHeap_.front(); - top->isTrigger = true; - do { - top->mHandle_(top->userData_, top->timerName_); - DelTimer(top->timerName_); - - if (hsize_ > 0) { - top = minHeap_.front(); - } else { - break; - } - } while (top->expire_ <= time(NULL)); - - return DM_OK; + return frontTimer.timeOut < timer.timeOut; } -int32_t TimeHeap::MoveUp(std::shared_ptr timer) +DmTimer::DmTimer() { - LOGI("MoveUp timer"); - if (timer == nullptr) { - LOGE("MoveUp timer is null"); - return DM_INVALID_VALUE; - } - - if (hsize_ == 0) { - LOGE("Add timer failed"); - return DM_INVALID_VALUE; - } + LOGI("DmTimer constructor"); +} - for (int32_t i = 1;; i++) { - LOGE("MoveUp 1 = %d, h = %d", i, hsize_); - if (i == hsize_) { - minHeap_.insert(minHeap_.begin() + (i - 1), timer); - break; - } - if (timer->expire_ < minHeap_[i - 1]->expire_) { - minHeap_.insert(minHeap_.begin() + (i -1), timer); - break; - } +DmTimer::~DmTimer() +{ + LOGI("DmTimer destructor"); + DeleteAll(); + if (timerState_) { + std::unique_lock locker(timerStateMutex_); + stopTimerCondition_.wait(locker, [this] { return static_cast(!timerState_); }); } - return DM_OK; } -void TimeHeap::Run() +int32_t DmTimer::StartTimer(std::string name, int32_t timeOut, TimerCallback callback) { - epoll_event event; - event.data.fd = pipefd[0]; - event.events = EPOLLIN | EPOLLET; - epoll_ctl(epollFd_, EPOLL_CTL_ADD, pipefd[0], &event); - epoll_event events[MAX_EVENT_NUMBER]; - bool stop = false; - int timeout = NO_TIMER; - - while (!stop) { - int number = epoll_wait(epollFd_, events, MAX_EVENT_NUMBER, timeout); - - LOGI("RunTimer is doing"); - if (number < 0) { - LOGE("DmTimer %s epoll_wait error: %d", minHeap_.front()->timerName_.c_str(), errno); - DelTimer(minHeap_.front()->timerName_); + LOGI("DmTimer StartTimer %s", name.c_str()); + if (name.empty() || timeOut <= 0 || timeOut > 300 || callback == nullptr) { + return DM_INPUT_PARA_EMPTY; + } + + Timer timer = { + .timerName = name, + .expire = steadyClock::now(), + .state = true, + .timeOut = timeOut, + .callback = callback + }; + { + std::lock_guard locker(timerMutex_); + timerHeap_.push_back(timer); + sort(timerHeap_.begin(), timerHeap_.end(), Compare); + } + + if (timerState_) { + LOGI("DmTimer is running"); + return DM_OK; + } + + std::thread([this] () { + { + timerState_ = true; + std::unique_lock locker(timerStateMutex_); + runTimerCondition_.notify_one(); } - if (!number) { - Tick(); - } else { - int buffer = 0; - recv(pipefd[0], (char*)&buffer, sizeof(buffer), 0); + while (timerHeap_.size() != 0) { + std::this_thread::sleep_for(std::chrono::milliseconds(DELAY_TICK_MILLSECONDS)); + LOGI("DmTimer StartTimer %d", std::chrono::duration_cast(steadyClock::now() + - timerHeap_.front().expire).count()/1000); + while (std::chrono::duration_cast(steadyClock::now() + - timerHeap_.front().expire).count()/1000 >= timerHeap_.front().timeOut + || !timerHeap_.front().state) { + std::string name = timerHeap_.front().timerName; + if (timerHeap_.front().state) { + timerHeap_.front().callback(name); + } + + auto iter = std::find(timerHeap_.begin(), timerHeap_.end(), Timer{name,}); + if (iter != timerHeap_.end()) { + std::lock_guard locker(timerMutex_); + timerHeap_.erase(timerHeap_.begin(), timerHeap_.begin()+1); + sort(timerHeap_.begin(), timerHeap_.end(), Compare); + } + + if (timerHeap_.size() == 0) { + break; + } + } } - - if (hsize_ == 0) { - break; - } else { - timeout = (minHeap_.front()->expire_ - time(NULL)) * SEC_TO_MM; + { + timerState_ = false; + std::unique_lock locker(timerStateMutex_); + stopTimerCondition_.notify_one(); } - } -} - -TimeHeap::TimeHeap(): epollFd_(epoll_create(MAX_EVENTS)) -{ - minHeap_.resize(INIT_SIZE); + }).detach(); - int ret = socketpair(PF_UNIX, SOCK_STREAM, 0, pipefd); - if (ret != 0) { - LOGE("open pipe failed"); + { + std::unique_lock locker(timerStateMutex_); + runTimerCondition_.wait(locker, [this] { return static_cast(timerState_); }); } - assert(ret == 0); -} - -TimeHeap::~TimeHeap() -{ - DelAll(); - close(epollFd_); -} - -int32_t TimeHeap::AddTimer(std::string name, int timeout, TimeoutHandle mHandle, void *user) -{ - if (name.empty() || name.find(TIMER_PREFIX) != TIMER_DEFAULT) { - LOGE("DmTimer name is not DM timer"); - return DM_INVALID_VALUE; - } - - LOGI("AddTimer %s", name.c_str()); - if (timeout <= 0 || mHandle == nullptr || user == nullptr) { - LOGE("DmTimer %s invalid value", name.c_str()); - return DM_INVALID_VALUE; - } - - if (hsize_ == 0) { - mThread_ = std::thread(&TimeHeap::Run, this); - mThread_.detach(); - } - if (hsize_ == (int32_t)(minHeap_.size() - 1)) { - minHeap_.resize(EXPAND_TWICE * minHeap_.size()); - } - - std::shared_ptr timer = std::make_shared(name, timeout + time(NULL), user, mHandle); - ++hsize_; - MoveUp(timer); - if (timer == minHeap_.front()) { - char msg = 1; - send(pipefd[1], (char*)&msg, sizeof(msg), 0); - } - LOGE("AddTimer %s complete", name.c_str()); return DM_OK; } -int32_t TimeHeap::DelTimer(std::string name) +int32_t DmTimer::DeleteTimer(std::string name) { - if (name.empty() || name.find(TIMER_PREFIX) != TIMER_DEFAULT) { - LOGE("DmTimer name is not DM timer"); - return DM_INVALID_VALUE; + LOGI("DmTimer DeleteTimer size %d", timerHeap_.size()); + if (name.empty()) { + LOGE("DmTimer DeleteTimer timer name is null"); + return DM_INPUT_PARA_EMPTY; } - LOGI("DelTimer %s", name.c_str()); - int32_t location = 0; - bool have = false; - for (int32_t i = 0; i < hsize_; i++) { - if (minHeap_[i]->timerName_ == name) { - location = i; - have = true; - break; - } + auto iter = std::find(timerHeap_.begin(), timerHeap_.end(), Timer{name,}); + if (iter == timerHeap_.end()) { + LOGE("DmTimer DeleteTimer is not this %s timer,", name.c_str()); + return DM_NO_TIMER; } - if (!have) { - LOGE("heap is not have this %s", name.c_str()); - return DM_INVALID_VALUE; - } - - if (minHeap_[location] == minHeap_.front() && minHeap_[location]->isTrigger == false) { - char msg = 1; - send(pipefd[1], &msg, sizeof(msg), 0); - } - minHeap_.erase(minHeap_.begin() + location); - hsize_--; - LOGI("DelTimer %s complete , timer count %d", name.c_str(), hsize_); + std::lock_guard locker(timerMutex_); + iter->state = false; return DM_OK; } -int32_t TimeHeap::DelAll() +int32_t DmTimer::DeleteAll() { - LOGI("DelAll start"); - for (int32_t i = hsize_ ; i > 0; i--) { - DelTimer(minHeap_[i - 1]->timerName_); + LOGI("DmTimer DeleteAll"); + if (timerHeap_.size() > 0) { + std::lock_guard locker(timerMutex_); + for (auto iter : timerHeap_) { + iter.state = false; + } } - LOGI("DelAll complete"); return DM_OK; } } diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index a10aa4f37..35f56a19c 100755 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -23,23 +23,6 @@ namespace OHOS { namespace DistributedHardware { -static void TimeOut(void *data, std::string timerName) -{ - LOGI("time out %s", timerName.c_str()); - if (data == nullptr || timerName.find(TIMER_PREFIX) != TIMER_DEFAULT) { - LOGE("time out is not our timer"); - return; - } - - DmDeviceStateManager *deviceStateMgr = (DmDeviceStateManager*)data; - if (deviceStateMgr == nullptr) { - LOGE("deviceStateMgr is nullptr"); - return; - } - - deviceStateMgr->DeleteTimeOutGroup(timerName); -} - DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr softbusConnector, std::shared_ptr listener, std::shared_ptr hiChainConnector) : softbusConnector_(softbusConnector), listener_(listener), hiChainConnector_(hiChainConnector) @@ -278,13 +261,13 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) #endif for (auto &iter : stateTimerInfoMap_) { if (iter.second.netWorkId == deviceInfo.deviceId) { - timerHeap_->DelTimer(iter.second.timerName); + timer_->DeleteTimer(iter.second.timerName); return; } } - if (timerHeap_ == nullptr) { - timerHeap_ = std::make_shared(); + if (timer_ == nullptr) { + timer_ = std::make_shared(); } std::string timerName = TIMER_PREFIX + STATE_TIMER_PREFIX + std::to_string(cumulativeQuantity_++); StateTimerInfo stateTimer = { @@ -305,12 +288,13 @@ void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) LOGI("start offline timer"); for (auto &iter : stateTimerInfoMap_) { if (iter.second.netWorkId == deviceInfo.deviceId) { - timerHeap_->AddTimer(iter.second.timerName, OFFLINE_TIMEOUT, TimeOut, this); + timer_->StartTimer(iter.second.timerName, OFFLINE_TIMEOUT, + [this](std::string name){DmDeviceStateManager::DeleteTimeOutGroup(name);}); } } } -void DmDeviceStateManager::DeleteTimeOutGroup(std::string stateTimer) +void DmDeviceStateManager::DeleteTimeOutGroup(std::string name) { #if defined(__LITEOS_M__) DmMutex mutexLock; @@ -318,14 +302,14 @@ void DmDeviceStateManager::DeleteTimeOutGroup(std::string stateTimer) std::lock_guard mutexLock(timerMapMutex_); #endif if (hiChainConnector_ != nullptr) { - auto iter = stateTimerInfoMap_.find(stateTimer); + auto iter = stateTimerInfoMap_.find(name); if (iter != stateTimerInfoMap_.end()) { LOGI("remove hichain group with device: %s", - GetAnonyString(stateTimerInfoMap_[stateTimer].deviceId).c_str()); - hiChainConnector_->DeleteTimeOutGroup(stateTimerInfoMap_[stateTimer].deviceId.c_str()); + GetAnonyString(stateTimerInfoMap_[name].deviceId).c_str()); + hiChainConnector_->DeleteTimeOutGroup(stateTimerInfoMap_[name].deviceId.c_str()); } } - stateTimerInfoMap_.erase(stateTimer); + stateTimerInfoMap_.erase(name); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp index ec0cf6383..65ed78d1d 100644 --- a/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp +++ b/services/devicemanagerservice/src/discovery/dm_discovery_manager.cpp @@ -24,23 +24,6 @@ namespace DistributedHardware { const std::string DISCOVERY_TIMEOUT_TASK = TIMER_PREFIX + "discovery"; const int32_t DISCOVERY_TIMEOUT = 120; -static void TimeOut(void *data, std::string timerName) -{ - LOGI("time out %s", timerName.c_str()); - if (data == nullptr || timerName != DISCOVERY_TIMEOUT_TASK) { - LOGE("time out is not our timer"); - return; - } - - DmDiscoveryManager *discoveryMgr = (DmDiscoveryManager *)data; - if (discoveryMgr == nullptr) { - LOGE("discoveryMgr is nullptr"); - return; - } - - discoveryMgr->HandleDiscoveryTimeout(); -} - DmDiscoveryManager::DmDiscoveryManager(std::shared_ptr softbusConnector, std::shared_ptr listener) : softbusConnector_(softbusConnector), listener_(listener) @@ -71,10 +54,11 @@ int32_t DmDiscoveryManager::StartDeviceDiscovery(const std::string &pkgName, con discoveryContextMap_.emplace(pkgName, context); softbusConnector_->RegisterSoftbusDiscoveryCallback(pkgName, std::shared_ptr(shared_from_this())); - if (timerHeap_ == nullptr) { - timerHeap_ = std::make_shared(); + if (timer_ == nullptr) { + timer_ = std::make_shared(); } - timerHeap_->AddTimer(DISCOVERY_TIMEOUT_TASK, DISCOVERY_TIMEOUT, TimeOut, this); + timer_->StartTimer(DISCOVERY_TIMEOUT_TASK, DISCOVERY_TIMEOUT, + [this](std::string name){DmDiscoveryManager::HandleDiscoveryTimeout(name);}); return softbusConnector_->StartDiscovery(subscribeInfo); } @@ -86,7 +70,7 @@ int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint if (!discoveryContextMap_.empty()) { discoveryContextMap_.erase(pkgName); softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); - timerHeap_->DelTimer(DISCOVERY_TIMEOUT_TASK); + timer_->DeleteTimer(DISCOVERY_TIMEOUT_TASK); } return softbusConnector_->StopDiscovery(subscribeId); } @@ -116,7 +100,7 @@ void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t listener_->OnDiscoverySuccess(pkgName, subscribeId); } -void DmDiscoveryManager::HandleDiscoveryTimeout() +void DmDiscoveryManager::HandleDiscoveryTimeout(std::string name) { LOGI("DmDiscoveryManager::HandleDiscoveryTimeout"); StopDeviceDiscovery(discoveryQueue_.front(), discoveryContextMap_[discoveryQueue_.front()].subscribeId); diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 93525f797..24474767d 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -32,7 +32,6 @@ group("unittest") { ":UTTest_dm_device_info_manager", ":UTTest_dm_device_state_manager", ":UTTest_dm_discovery_manager", - ":UTTest_dm_timer", ":UTTest_hichain_connector", ":UTTest_ipc_client_manager", ":UTTest_ipc_client_proxy", -- Gitee From 86c26d1b94c0b270caf9eb84c6aa1d30133a990b Mon Sep 17 00:00:00 2001 From: fuchao Date: Fri, 6 May 2022 01:57:52 +0000 Subject: [PATCH 2/2] update services/devicemanagerservice/src/dependency/timer/dm_timer.cpp. --- services/devicemanagerservice/src/dependency/timer/dm_timer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp b/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp index 50b676ae4..bcb950887 100644 --- a/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp +++ b/services/devicemanagerservice/src/dependency/timer/dm_timer.cpp @@ -121,7 +121,7 @@ int32_t DmTimer::DeleteTimer(std::string name) auto iter = std::find(timerHeap_.begin(), timerHeap_.end(), Timer{name,}); if (iter == timerHeap_.end()) { LOGE("DmTimer DeleteTimer is not this %s timer,", name.c_str()); - return DM_NO_TIMER; + return DM_FAILED; } std::lock_guard locker(timerMutex_); -- Gitee