1 /*
2  * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "listener/kv_store_death_recipient.h"
17 
18 #include "device_profile_manager.h"
19 #include "event_handler_factory.h"
20 #include "distributed_device_profile_log.h"
21 #include "distributed_device_profile_constants.h"
22 #include "static_profile_manager.h"
23 
24 namespace OHOS {
25 namespace DistributedDeviceProfile {
26 namespace {
27     const std::string TAG = "KvStoreDeathRecipient";
28     const std::string REINIT_TASK = "reInitTask";
29     const std::string DYNAMIC_STORE_ID = "dp_kv_store";
30     const std::string STATIC_STORE_ID = "dp_kv_static_store";
31 }
32 
KvDeathRecipient(const std::string & storeId)33 KvDeathRecipient::KvDeathRecipient(const std::string& storeId)
34 {
35     HILOGD("construct!");
36     storeId_ = storeId;
37     {
38         std::lock_guard<std::mutex> lock(reInitMutex_);
39         reInitHandler_ = EventHandlerFactory::GetInstance().GetEventHandler();
40     }
41 }
42 
~KvDeathRecipient()43 KvDeathRecipient::~KvDeathRecipient()
44 {
45     HILOGD("destruct!");
46     {
47         std::lock_guard<std::mutex> lock(reInitMutex_);
48         if (reInitHandler_ == nullptr) {
49             HILOGE("reInitHandler is nullptr!");
50             return;
51         }
52         reInitHandler_->RemoveTask(REINIT_TASK);
53         reInitHandler_ = nullptr;
54     }
55 }
56 
OnRemoteDied()57 void KvDeathRecipient::OnRemoteDied()
58 {
59     HILOGI("OnRemoteDied, recover db begin");
60     auto reInitTask = [storeId = storeId_]() {
61         HILOGI("ReInit, storeId:%{public}s", storeId.c_str());
62         if (storeId == DYNAMIC_STORE_ID) {
63             DeviceProfileManager::GetInstance().ReInit();
64         }
65         if (storeId == STATIC_STORE_ID) {
66             StaticProfileManager::GetInstance().ReInit();
67         }
68     };
69     {
70         std::lock_guard<std::mutex> lock(reInitMutex_);
71         if (reInitHandler_ == nullptr) {
72             HILOGE("Create EventHandler is nullptr");
73             return;
74         }
75         if (!reInitHandler_->PostTask(reInitTask, REINIT_TASK, 0)) {
76             HILOGE("Post reInitTask fail!");
77             return;
78         }
79     }
80     HILOGI("OnRemoteDied, recover db end");
81 }
82 } // namespace DeviceProfile
83 } // namespace OHOS
84