部件化更改

Signed-off-by: wangkai <wangkai424@huawei.com>
This commit is contained in:
wangkai 2022-08-23 22:36:23 +08:00
parent 0b5ad68600
commit a336c0a9dc
827 changed files with 376 additions and 212926 deletions

View File

@ -15,11 +15,9 @@ import("//build/ohos.gni")
group("build_native_test") {
testonly = true
deps = [
"frameworks/innerkitsimpl/distributeddatafwk/test:unittest",
"services/distributeddataservice/adapter/test:unittest",
"services/distributeddataservice/app/test:unittest",
"services/distributeddataservice/framework/test:unittest",
"services/distributeddataservice/libs/distributeddb/test:unittest",
"services/distributeddataservice/service/test:unittest",
"services/distributeddataservice/test:moduletest",
]
@ -36,10 +34,4 @@ group("fuzztest") {
"test/fuzztest/kvstoredisksize_fuzzer:fuzztest",
]
}
group("distributedtest") {
testonly = true
deps = []
deps += [ "test/distributedtest/single_kvstore_client:distributedtest" ]
}
###############################################################################

View File

@ -43,7 +43,7 @@ You call APIs of DDS to create, access, and subscribe to distributed databases.
## Directory Structure<a name="section161941989596"></a>
```
/foundation/distributeddatamgr/distributeddatamgr
/foundation/distributeddatamgr/datamgr_service
├── interfaces # APIs
│ └── innerkits # Native APIs
│ └── jskits # JavaScript APIs

View File

@ -43,7 +43,7 @@
## 目录<a name="section161941989596"></a>
```
/foundation/distributeddatamgr/distributeddatamgr
/foundation/distributeddatamgr/datamgr_service
├── interfaces # 接口层代码
│ └── innerkits # Native接口
│ └── jskits # JavaScript接口

View File

@ -1,10 +1,10 @@
{
"name": "@ohos/distributeddatamgr_datamgr",
"name": "@ohos/distributeddatamgr_datamgr_service",
"version": "1.0.0",
"description": "Distributed data manager that provides the capability to store data in the databases of different devices",
"homePage": "https://gitee.com/openharmony",
"license": "Apache V2",
"repository": "https://gitee.com/openharmony/distributeddatamgr_datamgr",
"repository": "https://gitee.com/openharmony/distributeddatamgr_datamgr_service",
"domain": "os",
"language": "",
"publishAs": "code-segment",
@ -15,7 +15,7 @@
],
"keywords": [
"distributeddatamgr",
"datamgr"
"datamgr_service"
],
"envs": [],
"dirs": [],
@ -32,10 +32,10 @@
}
],
"segment": {
"destPath": "foundation/distributeddatamgr/distributeddatamgr"
"destPath": "foundation/distributeddatamgr/datamgr_service"
},
"component": {
"name": "distributeddatamgr",
"name": "datamgr_service",
"subsystem": "distributeddatamgr",
"syscap": [
"SystemCapability.DistributedDataManager.KVStore.Core",
@ -49,7 +49,7 @@
"rom": "",
"ram": "",
"hisysevent_config": [
"//foundation/distributeddatamgr/distributeddatamgr/hisysevent.yaml"
"//foundation/distributeddatamgr/datamgr_service/hisysevent.yaml"
],
"deps": {
"components": [
@ -86,17 +86,14 @@
},
"build": {
"sub_component": [
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:build_module",
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/jskits/distributeddata:build_module",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app:build_module",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:build_module",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:build_module",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:build_module",
"//foundation/distributeddatamgr/distributeddatamgr/conf:build_module"
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/app:build_module",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:build_module",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:build_module",
"//foundation/distributeddatamgr/datamgr_service/conf:build_module"
],
"inner_kits": [
{
"name": "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner",
"name": "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
"header": {
"header_files": [
"blob.h",
@ -114,16 +111,14 @@
"device_status_change_listener.h",
"store_errno.h"
],
"header_base": "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include"
"header_base": "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include"
}
}
],
"test": [
"//foundation/distributeddatamgr/distributeddatamgr:build_native_test",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb/test:distributeddatamgr_fuzztest",
"//foundation/distributeddatamgr/distributeddatamgr:fuzztest",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/test:fuzztest",
"//foundation/distributeddatamgr/distributeddatamgr:distributedtest"
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/test:fuzztest",
"//foundation/distributeddatamgr/datamgr_service:fuzztest",
"//foundation/distributeddatamgr/datamgr_service:build_native_test"
]
}
}

View File

@ -21,5 +21,5 @@ ohos_prebuilt_etc("default_conf") {
source = "config.json"
relative_install_dir = "distributeddata/conf"
subsystem_name = "distributeddatamgr"
part_name = "distributeddatamgr"
part_name = "datamgr_service"
}

View File

@ -12,10 +12,10 @@
# limitations under the License.
declare_args() {
distributeddatamgr_power = true
datamgr_service_power = true
if (!defined(global_parts_info.power_manager_native_powermgr_client) ||
!defined(global_parts_info.battery_manager_native_batterysrv_client)) {
distributeddatamgr_power = false
datamgr_service_power = false
}
if (!defined(global_parts_info) ||

View File

@ -1,248 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_CONCURRENT_MAP_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_CONCURRENT_MAP_H
#include <functional>
#include <map>
#include <mutex>
namespace OHOS {
template<typename _Key, typename _Tp>
class ConcurrentMap {
public:
using key_type = typename std::map<_Key, _Tp>::key_type;
using mapped_type = typename std::map<_Key, _Tp>::mapped_type;
using value_type = typename std::map<_Key, _Tp>::value_type;
using size_type = typename std::map<_Key, _Tp>::size_type;
using reference = typename std::map<_Key, _Tp>::reference;
using const_reference = typename std::map<_Key, _Tp>::const_reference;
ConcurrentMap() = default;
~ConcurrentMap()
{
Clear();
}
ConcurrentMap(const ConcurrentMap &other)
{
operator=(std::move(other));
}
ConcurrentMap &operator=(const ConcurrentMap &other) noexcept
{
if (this == &other) {
return *this;
}
auto tmp = other.Clone();
std::lock_guard<decltype(mutex_)> lock(mutex_);
entries_ = std::move(tmp);
return *this;
}
ConcurrentMap(ConcurrentMap &&other) noexcept
{
operator=(std::move(other));
}
ConcurrentMap &operator=(ConcurrentMap &&other) noexcept
{
if (this == &other) {
return *this;
}
auto tmp = other.Steal();
std::lock_guard<decltype(mutex_)> lock(mutex_);
entries_ = std::move(tmp);
return *this;
}
template<typename... _Args>
bool Emplace(_Args &&...__args) noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.emplace(std::forward<_Args>(__args)...);
return it->second;
}
std::pair<bool, mapped_type> Find(const key_type &key) const noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.find(key);
if (it == entries_.end()) {
return std::pair { false, mapped_type() };
}
return std::pair { true, it->second };
}
bool Contains(const key_type &key) const noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return (entries_.find(key) != entries_.end());
}
template <typename _Obj>
bool InsertOrAssign(const key_type &key, _Obj &&obj) noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.insert_or_assign(key, std::forward<_Obj>(obj));
return it.second;
}
bool Insert(const key_type &key, const mapped_type &value) noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.insert(value_type { key, value });
return it.second;
}
size_type Erase(const key_type &key) noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return entries_.erase(key);
}
void Clear() noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return entries_.clear();
}
bool Empty() const noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return entries_.empty();
}
size_type Size() const noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return entries_.size();
}
// The action`s return true mains meet the erase condition
// The action`s return false mains not meet the erase condition
size_type EraseIf(const std::function<bool(const key_type &key, mapped_type &value)> &action) noexcept
{
if (action == nullptr) {
return 0;
}
std::lock_guard<decltype(mutex_)> lock(mutex_);
#if __cplusplus > 201703L
auto count = std::erase_if(entries_,
[&action](value_type &value) -> bool { return action(value.first, value.second); });
#else
auto count = entries_.size();
for (auto it = entries_.begin(); it != entries_.end();) {
if (action((*it).first, (*it).second)) {
it = entries_.erase(it);
} else {
++it;
}
}
count -= entries_.size();
#endif
return count;
}
mapped_type &operator[](const key_type &key) noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return entries_[key];
}
void ForEach(const std::function<bool(const key_type &, mapped_type &)> &action)
{
if (action == nullptr) {
return;
}
std::lock_guard<decltype(mutex_)> lock(mutex_);
for (auto &[key, value] : entries_) {
if (action(key, value)) {
break;
}
}
}
// The action's return value mains that the element is keep in map or not; true mains keep, false mains remove.
bool Compute(const key_type &key, const std::function<bool(const key_type &, mapped_type &)> &action)
{
if (action == nullptr) {
return false;
}
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.find(key);
if (it == entries_.end()) {
auto result = entries_.emplace(key, mapped_type());
it = result.second ? result.first : entries_.end();
}
if (it == entries_.end()) {
return false;
}
if (!action(it->first, it->second)) {
entries_.erase(key);
}
return true;
}
// The action's return value mains that the element is keep in map or not; true mains keep, false mains remove.
bool ComputeIfPresent(const key_type &key, const std::function<bool(const key_type &, mapped_type &)> &action)
{
if (action == nullptr) {
return false;
}
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.find(key);
if (it == entries_.end()) {
return false;
}
if (!action(key, it->second)) {
entries_.erase(key);
}
return true;
}
bool ComputeIfAbsent(const key_type &key, const std::function<mapped_type(const key_type &)> &action)
{
if (action == nullptr) {
return false;
}
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = entries_.find(key);
if (it != entries_.end()) {
return false;
}
entries_.emplace(key, action(key));
return true;
}
private:
std::map<_Key, _Tp> Steal() noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return std::move(entries_);
}
std::map<_Key, _Tp> Clone() const noexcept
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
return entries_;
}
private:
mutable std::recursive_mutex mutex_;
std::map<_Key, _Tp> entries_;
};
} // namespace OHOS
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_CONCURRENT_MAP_H

View File

@ -1,69 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 DISTRIBUTEDDATA_LOG_PRINT_H
#define DISTRIBUTEDDATA_LOG_PRINT_H
#define OS_OHOS
#if defined OS_OHOS // log for OHOS
#include "hilog/log.h"
namespace OHOS {
namespace DistributedKv {
static inline OHOS::HiviewDFX::HiLogLabel LogLabel()
{
return { LOG_CORE, 0xD001610, "ZDDS" };
}
} // end namespace DistributesdKv
namespace DistributedData {
static inline OHOS::HiviewDFX::HiLogLabel LogLabel()
{
return { LOG_CORE, 0xD001611, "ZDD" };
}
} // end namespace DistributedData
namespace AppDistributedKv {
static inline OHOS::HiviewDFX::HiLogLabel LogLabel()
{
return { LOG_CORE, 0xD001620, "ZDDC" };
}
} // namespace AppDistributedKv
namespace DistributedRdb {
static inline OHOS::HiviewDFX::HiLogLabel LogLabel()
{
return { LOG_CORE, 0xD001655, "DRDB" };
}
} // end namespace DistributedRdb
} // end namespace OHOS
#define ZLOGD(fmt, ...) \
OHOS::HiviewDFX::HiLog::Debug(LogLabel(), LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__)
#define ZLOGI(fmt, ...) \
OHOS::HiviewDFX::HiLog::Info(LogLabel(), LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__)
#define ZLOGW(fmt, ...) \
OHOS::HiviewDFX::HiLog::Warn(LogLabel(), LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__)
#define ZLOGE(fmt, ...) \
OHOS::HiviewDFX::HiLog::Error(LogLabel(), LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__)
#else
#error // unknown system
#endif
#endif // DISTRIBUTEDDATA_LOG_PRINT_H

View File

@ -1,224 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_LRU_BUCKET_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_LRU_BUCKET_H
#include <map>
#include <mutex>
#include <list>
namespace OHOS {
template<typename _Key, typename _Tp>
class LRUBucket {
public:
LRUBucket(size_t capacity)
: size_(0), capacity_(capacity) {}
LRUBucket(LRUBucket &&bucket) noexcept = delete;
LRUBucket(const LRUBucket &bucket) = delete;
LRUBucket &operator=(LRUBucket &&bucket) noexcept = delete;
LRUBucket &operator=(const LRUBucket &bucket) = delete;
~LRUBucket()
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
while (size_ > 0) {
PopBack();
}
}
size_t Size() const
{
return size_;
}
size_t Capacity() const
{
return capacity_;
}
bool ResetCapacity(size_t capacity)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
capacity_ = capacity;
while (capacity_ < size_) {
PopBack();
}
return capacity_ == capacity;
}
/**
* The time complexity is O(log(index size))
**/
bool Get(const _Key &key, _Tp &value)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = indexes_.find(key);
if (it != indexes_.end()) {
// move node from the list;
Remove(it->second);
// insert node to the head
Insert(&head_, it->second);
value = it->second->value_;
return true;
}
return false;
}
/**
* The time complexity is O(log(index size))
**/
bool Set(const _Key &key, const _Tp &value)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
if (capacity_ == 0) {
return false;
}
auto it = indexes_.find(key);
if (it != indexes_.end()) {
Update(it->second, value);
Remove(it->second);
Insert(&head_, it->second);
return true;
}
while (capacity_ <= size_) {
PopBack();
}
auto *node = new(std::nothrow) Node(value);
if (node == nullptr) {
return false;
}
Insert(&head_, node);
auto pair = indexes_.emplace(key, node);
node->iterator_ = pair.first;
return true;
}
/**
* Just update the values, not change the lru
**/
bool Update(const _Key &key, const _Tp &value)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = indexes_.find(key);
if (it != indexes_.end()) {
Update(it->second, value);
return true;
}
return false;
}
/**
* The time complexity is O(min(indexes, values))
* Just update the values, not change the lru chain
*/
bool Update(const std::map<_Key, _Tp> &values)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto idx = indexes_.begin();
auto val = values.begin();
bool updated = false;
auto comp = indexes_.key_comp();
while (idx != indexes_.end() && val != values.end()) {
if (comp(idx->first, val->first)) {
++idx;
continue;
}
if (comp(val->first, idx->first)) {
++val;
continue;
}
updated = true;
Update(idx->second, val->second);
++idx;
++val;
}
return updated;
}
/**
* The time complexity is O(log(index size))
* */
bool Delete(const _Key &key)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
auto it = indexes_.find(key);
if (it != indexes_.end()) {
Remove(it->second);
Delete(it->second);
return true;
}
return false;
}
private:
struct Node final {
using iterator = typename std::map<_Key, Node *>::iterator;
Node(const _Tp &value) : value_(value) {}
Node() : value_() {}
~Node() = default;
_Tp value_;
iterator iterator_;
Node *prev_ = this;
Node *next_ = this;
};
void PopBack()
{
auto *node = head_.prev_;
Remove(node);
Delete(node);
}
void Update(Node *node, const _Tp &value)
{
node->value_ = value;
}
void Remove(Node *node)
{
node->prev_->next_ = node->next_;
node->next_->prev_ = node->prev_;
size_--;
}
void Insert(Node *prev, Node *node)
{
prev->next_->prev_ = node;
node->next_ = prev->next_;
prev->next_ = node;
node->prev_ = prev;
size_++;
}
void Delete(Node *node)
{
indexes_.erase(node->iterator_);
delete node;
}
mutable std::recursive_mutex mutex_;
std::map<_Key, Node *> indexes_;
Node head_;
size_t size_;
size_t capacity_;
};
} // namespace OHOS
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_LRU_BUCKET_H

View File

@ -1,319 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "LRUBucketTest"
#include "lru_bucket.h"
#include "gtest/gtest.h"
using namespace testing::ext;
template<typename _Key, typename _Tp> using LRUBucket = OHOS::LRUBucket<_Key, _Tp>;
class LRUBucketTest : public testing::Test {
public:
struct TestValue {
std::string id;
std::string name;
std::string testCase;
};
static constexpr size_t TEST_CAPACITY = 10;
static void SetUpTestCase(void) {}
static void TearDownTestCase(void) {}
protected:
void SetUp()
{
bucket_.ResetCapacity(0);
bucket_.ResetCapacity(TEST_CAPACITY);
for (size_t i = 0; i < TEST_CAPACITY; ++i) {
std::string key = std::string("test_") + std::to_string(i);
TestValue value = {key, key, "case"};
bucket_.Set(key, value);
}
}
void TearDown() {}
LRUBucket<std::string, TestValue> bucket_{TEST_CAPACITY};
};
/**
* @tc.name: insert
* @tc.desc: Set the value to the lru bucket, whose capacity is more than one.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, insert, TestSize.Level0)
{
bucket_.Set("test_10", {"test_10", "test_10", "case"});
TestValue value;
ASSERT_TRUE(!bucket_.Get("test_0", value));
ASSERT_TRUE(bucket_.Get("test_6", value));
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_6", value));
}
/**
* @tc.name: cap_one_insert
* @tc.desc: Set the value to the lru bucket, whose capacity is one.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, cap_one_insert, TestSize.Level0)
{
bucket_.ResetCapacity(1);
for (size_t i = 0; i <= TEST_CAPACITY; ++i) {
std::string key = std::string("test_") + std::to_string(i);
TestValue value = {key, key, "find"};
bucket_.Set(key, value);
}
TestValue value;
ASSERT_TRUE(!bucket_.Get("test_0", value));
ASSERT_TRUE(bucket_.Get("test_10", value));
}
/**
* @tc.name: cap_zero_insert
* @tc.desc: Set the value to the lru bucket, whose capacity is zero.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, cap_zero_insert, TestSize.Level0)
{
bucket_.ResetCapacity(0);
for (size_t i = 0; i <= TEST_CAPACITY; ++i) {
std::string key = std::string("test_") + std::to_string(i);
TestValue value = {key, key, "find"};
bucket_.Set(key, value);
}
TestValue value;
ASSERT_TRUE(!bucket_.Get("test_10", value));
}
/**
* @tc.name: find_head
* @tc.desc: find the head element from the lru bucket.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, find_head, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_9", value));
}
/**
* @tc.name: find_tail
* @tc.desc: find the tail element, then the element will move to head.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, find_tail, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.Get("test_0", value));
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_0", value));
}
/**
* @tc.name: find_mid
* @tc.desc: find the mid element, then the element will move to head.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, find_mid, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.Get("test_5", value));
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_5", value));
}
/**
* @tc.name: find_and_insert
* @tc.desc: find the tail element, then the element will move to head.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, find_and_insert, TestSize.Level0)
{
TestValue value;
if (!bucket_.Get("MyTest", value)) {
bucket_.Set("MyTest", {"MyTest", "MyTest", "case"});
}
ASSERT_TRUE(bucket_.Get("MyTest", value));
if (!bucket_.Get("test_0", value)) {
bucket_.Set("test_0", {"test_0", "test_0", "case"});
}
ASSERT_TRUE(bucket_.Get("test_0", value));
ASSERT_TRUE(bucket_.Get("test_5", value));
ASSERT_TRUE(bucket_.Get("test_4", value));
ASSERT_TRUE(!bucket_.Get("test_1", value));
ASSERT_TRUE(bucket_.Get("test_2", value));
}
/**
* @tc.name: del_head
* @tc.desc: delete the head element, then the next element will move to head.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, del_head, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.Delete("test_9"));
ASSERT_TRUE(!bucket_.Get("test_9", value));
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_8", value));
}
/**
* @tc.name: del_head
* @tc.desc: delete the tail element, then the lru chain keep valid.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, del_tail, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.Delete("test_0"));
ASSERT_TRUE(!bucket_.Get("test_0", value));
ASSERT_TRUE(bucket_.Get("test_4", value));
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_4", value));
}
/**
* @tc.name: del_mid
* @tc.desc: delete the mid element, then the lru chain keep valid.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, del_mid, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.Delete("test_5"));
ASSERT_TRUE(!bucket_.Get("test_5", value));
ASSERT_TRUE(bucket_.Get("test_4", value));
ASSERT_TRUE(bucket_.Get("test_6", value));
ASSERT_TRUE(bucket_.ResetCapacity(2));
ASSERT_TRUE(bucket_.Capacity() == 2);
ASSERT_TRUE(bucket_.Size() <= 2);
ASSERT_TRUE(bucket_.Get("test_4", value));
ASSERT_TRUE(bucket_.Get("test_6", value));
}
/**
* @tc.name: del_mid
* @tc.desc: the lru bucket has only one element, then delete it.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, cap_one_del, TestSize.Level0)
{
TestValue value;
bucket_.ResetCapacity(1);
ASSERT_TRUE(bucket_.Delete("test_9"));
ASSERT_TRUE(!bucket_.Get("test_9", value));
}
/**
* @tc.name: del_mid
* @tc.desc: the lru bucket has no element.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, cap_zero_del, TestSize.Level0)
{
TestValue value;
bucket_.ResetCapacity(0);
ASSERT_TRUE(!bucket_.Delete("test_9"));
ASSERT_TRUE(!bucket_.Get("test_9", value));
}
/**
* @tc.name: update_one
* @tc.desc: update the value and the lru chain won't change.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, update_one, TestSize.Level0)
{
TestValue value;
ASSERT_TRUE(bucket_.Update("test_4", {"test_4", "test_4", "update"}));
ASSERT_TRUE(bucket_.Get("test_4", value));
ASSERT_TRUE(value.testCase == "update");
ASSERT_TRUE(bucket_.Update("test_9", {"test_9", "test_9", "update"}));
ASSERT_TRUE(bucket_.ResetCapacity(1));
ASSERT_TRUE(bucket_.Capacity() == 1);
ASSERT_TRUE(bucket_.Size() <= 1);
ASSERT_TRUE(bucket_.Get("test_4", value));
ASSERT_TRUE(!bucket_.Get("test_9", value));
}
/**
* @tc.name: update_several
* @tc.desc: update several values and the lru chain won't change.
* @tc.type: FUNC
* @tc.require:
* @tc.author: Sven Wang
*/
HWTEST_F(LRUBucketTest, update_several, TestSize.Level0)
{
TestValue value;
std::map<std::string, TestValue> values = {{"test_2", {"test_2", "test_2", "update"}},
{"test_3", {"test_3", "test_3", "update"}},
{"test_6", {"test_6", "test_6", "update"}}};
ASSERT_TRUE(bucket_.Update(values));
ASSERT_TRUE(bucket_.ResetCapacity(3));
ASSERT_TRUE(bucket_.Capacity() == 3);
ASSERT_TRUE(bucket_.Size() <= 3);
ASSERT_TRUE(!bucket_.Get("test_2", value));
ASSERT_TRUE(!bucket_.Get("test_3", value));
ASSERT_TRUE(!bucket_.Get("test_6", value));
ASSERT_TRUE(bucket_.Get("test_9", value));
ASSERT_TRUE(bucket_.Get("test_8", value));
ASSERT_TRUE(bucket_.Get("test_7", value));
}

View File

@ -1,26 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_VISIBILITY_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_VISIBILITY_H
#ifndef API_EXPORT
#define API_EXPORT __attribute__((visibility ("default")))
#endif
#ifndef KVSTORE_API
#define KVSTORE_API API_EXPORT
#endif
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_VISIBILITY_H

View File

@ -1,118 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_INNERKITSIMPL_NATIVE_PREFERENCES_INCLUDE_COV_UTIL_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_INNERKITSIMPL_NATIVE_PREFERENCES_INCLUDE_COV_UTIL_H
#include <string>
#include <variant>
#include <set>
#include "data_query.h"
namespace OHOS {
namespace DistributedKv {
class CovUtil final {
public:
template<typename _VTp, typename _TTp, typename _First>
static auto FillField(const std::string &field, const _VTp &data, _TTp &target)
{
return target();
}
template<typename _VTp, typename _TTp, typename _First, typename _Second, typename ..._Rest>
static auto FillField(const std::string &field, const _VTp &data, _TTp &target)
{
if ((sizeof ...(_Rest) + 1) == data.index()) {
return target(field, std::get<(sizeof ...(_Rest) + 1)>(data));
}
return FillField<_VTp, _TTp, _Second, _Rest...>(field, data, target);
}
template<typename _TTp, typename ..._Types>
static auto FillField(const std::string &field, const std::variant<_Types...> &data, _TTp &target)
{
return FillField<decltype(data), _TTp, _Types...>(field, data, target);
}
};
enum class QueryType {
EQUAL = 0,
NOT_EQUAL = 1,
GREATER = 2,
LESS = 3,
GREATER_OR_EQUAL = 4,
LESS_OR_EQUAL = 5,
IN = 6,
NOT_IN = 7
};
class Querys {
public:
Querys(OHOS::DistributedKv::DataQuery *dataQuery, QueryType type) : dataQuery_(dataQuery), type_(type) {};
template<typename T>
int operator()(const std::string &field, const T &value)
{
if (type_ == QueryType::EQUAL) {
dataQuery_->EqualTo(field, value);
} else if (type_ == QueryType::NOT_EQUAL) {
dataQuery_->NotEqualTo(field, value);
} else if (type_ == QueryType::GREATER) {
dataQuery_->GreaterThan(field, value);
} else if (type_ == QueryType::LESS) {
dataQuery_->LessThan(field, value);
} else if (type_ == QueryType::GREATER_OR_EQUAL) {
dataQuery_->GreaterThanOrEqualTo(field, value);
} else if (type_ == QueryType::LESS_OR_EQUAL) {
dataQuery_->LessThanOrEqualTo(field, value);
}
return 0;
}
int operator()()
{
return 0;
}
private:
OHOS::DistributedKv::DataQuery *dataQuery_;
QueryType type_;
};
class InOrNotIn {
public:
InOrNotIn(OHOS::DistributedKv::DataQuery *dataQuery, QueryType type) : dataQuery_(dataQuery), type_(type) {};
template<typename T>
int operator()(const std::string &field, const std::vector<T> &value)
{
if (type_ == QueryType::IN) {
dataQuery_->In(field, value);
} else if (type_ == QueryType::NOT_IN) {
dataQuery_->NotIn(field, value);
}
return 0;
}
int operator()()
{
return 0;
}
private:
OHOS::DistributedKv::DataQuery *dataQuery_;
QueryType type_;
};
}
}
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_INNERKITSIMPL_NATIVE_PREFERENCES_INCLUDE_COV_UTIL_H

View File

@ -1,48 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 DEV_IDEVICE_STATUS_CHANGE_LISTENER_H
#define DEV_IDEVICE_STATUS_CHANGE_LISTENER_H
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
#include "types.h"
namespace OHOS {
namespace DistributedKv {
class IDeviceStatusChangeListener : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IDeviceStatusChangeListener");
virtual void OnChange(const DeviceInfo &results, const DeviceChangeType &type) = 0;
};
class DeviceStatusChangeListenerStub : public IRemoteStub<IDeviceStatusChangeListener> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
};
class DeviceStatusChangeListenerProxy : public IRemoteProxy<IDeviceStatusChangeListener> {
public:
explicit DeviceStatusChangeListenerProxy(const sptr<IRemoteObject> &impl);
~DeviceStatusChangeListenerProxy() = default;
void OnChange(const DeviceInfo &results, const DeviceChangeType &type) override;
private:
static inline BrokerDelegator<DeviceStatusChangeListenerProxy> delegator_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // DEV_IDEVICE_STATUS_CHANGE_LISTENER_H

View File

@ -1,44 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 I_KVSTORE_CLIENT_DEATH_OBSERVER_H
#define I_KVSTORE_CLIENT_DEATH_OBSERVER_H
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
namespace OHOS {
namespace DistributedKv {
class IKvStoreClientDeathObserver : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreClientDeathObserver");
};
class KvStoreClientDeathObserverStub : public IRemoteStub<IKvStoreClientDeathObserver> {
public:
};
class KvStoreClientDeathObserverProxy : public IRemoteProxy<IKvStoreClientDeathObserver> {
public:
explicit KvStoreClientDeathObserverProxy(const sptr<IRemoteObject> &impl);
~KvStoreClientDeathObserverProxy() = default;
private:
static inline BrokerDelegator<KvStoreClientDeathObserverProxy> delegator_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // I_KVSTORE_CLIENT_DEATH_OBSERVER_H

View File

@ -1,178 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 I_KV_STORE_DATA_SERVICE_H
#define I_KV_STORE_DATA_SERVICE_H
#include "iremote_broker.h"
#include "ikvstore_client_death_observer.h"
#include "ikvstore_observer.h"
#include "ikvstore_single.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
#include "message_parcel.h"
#include "types.h"
#include "idevice_status_change_listener.h"
namespace OHOS::DistributedKv {
/*
* IPC-friendly Options struct without std::string schema field.
* Passing a struct with an std::string field is a potential security exploit.
*
*/
struct OptionsIpc {
bool createIfMissing;
bool encrypt;
bool persistent;
bool backup;
bool autoSync;
int securityLevel;
SyncPolicy syncPolicy;
KvStoreType kvStoreType;
bool syncable; // let bms delete first
bool dataOwnership; // true indicates the ownership of distributed data is DEVICE, otherwise, ACCOUNT
};
class IKvStoreDataService : public IRemoteBroker {
public:
enum {
GETALLKVSTOREID,
CLOSEKVSTORE,
CLOSEALLKVSTORE,
DELETEKVSTORE,
DELETEALLKVSTORE,
REGISTERCLIENTDEATHOBSERVER,
GETSINGLEKVSTORE,
GETLOCALDEVICE,
GETREMOTEDEVICES,
STARTWATCHDEVICECHANGE,
STOPWATCHDEVICECHANGE,
GET_RDB_SERVICE,
GET_KVDB_SERVICE,
GET_OBJECT_SERVICE,
SERVICE_CMD_LAST,
DATAUSAGESTART = 20,
DATAUSAGEEND = 40,
};
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreDataService");
virtual Status GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
std::function<void(sptr<ISingleKvStore>)> callback) = 0;
/* get all kv store names */
virtual void GetAllKvStoreId(const AppId &appId, std::function<void(Status, std::vector<StoreId> &)> callback) = 0;
/* open kv store instance will not receive subscribe any more. */
virtual Status CloseKvStore(const AppId &appId, const StoreId &id) = 0;
/* close all kvstore. */
virtual Status CloseAllKvStore(const AppId &appId) = 0;
/* delete kv store */
virtual Status DeleteKvStore(const AppId &appId, const StoreId &id) = 0;
/* delete kv store */
virtual Status DeleteAllKvStore(const AppId &appId) = 0;
virtual Status RegisterClientDeathObserver(const AppId &appId, sptr<IRemoteObject> observer) = 0;
virtual Status GetLocalDevice(DeviceInfo &device) = 0;
virtual Status GetRemoteDevices(std::vector<DeviceInfo> &deviceInfoList, DeviceFilterStrategy strategy) = 0;
virtual Status StartWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer,
DeviceFilterStrategy strategy) = 0;
virtual Status StopWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer) = 0;
virtual sptr<IRemoteObject> GetRdbService() = 0;
virtual sptr<IRemoteObject> GetKVdbService() = 0;
virtual sptr<IRemoteObject> GetObjectService() = 0;
};
class KvStoreDataServiceStub : public IRemoteStub<IKvStoreDataService> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
private:
int32_t GetAllKvStoreIdOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t CloseKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t CloseAllKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t DeleteKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t DeleteAllKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t RegisterClientDeathObserverOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t GetLocalDeviceOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t GetRemoteDevicesOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t StartWatchDeviceChangeOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t StopWatchDeviceChangeOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t GetSingleKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int32_t GetRdbServiceOnRemote(MessageParcel& data, MessageParcel& reply);
int32_t GetKVdbServiceOnRemote(MessageParcel& data, MessageParcel& reply);
int32_t GetObjectServiceOnRemote(MessageParcel &data, MessageParcel &reply);
using RequestHandler = int32_t(KvStoreDataServiceStub::*)(MessageParcel&, MessageParcel&);
static constexpr RequestHandler HANDLERS[SERVICE_CMD_LAST] = {
[GETALLKVSTOREID] = &KvStoreDataServiceStub::GetAllKvStoreIdOnRemote,
[CLOSEKVSTORE] = &KvStoreDataServiceStub::CloseKvStoreOnRemote,
[CLOSEALLKVSTORE] = &KvStoreDataServiceStub::CloseAllKvStoreOnRemote,
[DELETEKVSTORE] = &KvStoreDataServiceStub::DeleteKvStoreOnRemote,
[DELETEALLKVSTORE] = &KvStoreDataServiceStub::DeleteAllKvStoreOnRemote,
[REGISTERCLIENTDEATHOBSERVER] = &KvStoreDataServiceStub::RegisterClientDeathObserverOnRemote,
[GETSINGLEKVSTORE] = &KvStoreDataServiceStub::GetSingleKvStoreOnRemote,
[GETLOCALDEVICE] = &KvStoreDataServiceStub::GetLocalDeviceOnRemote,
[GETREMOTEDEVICES] = &KvStoreDataServiceStub::GetRemoteDevicesOnRemote,
[STARTWATCHDEVICECHANGE] = &KvStoreDataServiceStub::StartWatchDeviceChangeOnRemote,
[STOPWATCHDEVICECHANGE] = &KvStoreDataServiceStub::StopWatchDeviceChangeOnRemote,
[GET_RDB_SERVICE] = &KvStoreDataServiceStub::GetRdbServiceOnRemote,
[GET_KVDB_SERVICE] = &KvStoreDataServiceStub::GetKVdbServiceOnRemote,
[GET_OBJECT_SERVICE] = &KvStoreDataServiceStub::GetObjectServiceOnRemote,
};
};
class KvStoreDataServiceProxy : public IRemoteProxy<IKvStoreDataService> {
public:
explicit KvStoreDataServiceProxy(const sptr<IRemoteObject> &impl);
~KvStoreDataServiceProxy() = default;
virtual Status GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
std::function<void(sptr<ISingleKvStore>)> callback);
/* get all kv store names */
virtual void GetAllKvStoreId(const AppId &appId, std::function<void(Status, std::vector<StoreId> &)> callback);
/* open kv store instance will not receive subscribe any more. */
virtual Status CloseKvStore(const AppId &appId, const StoreId &storeId);
/* close all kvstore. */
virtual Status CloseAllKvStore(const AppId &appId);
/* delete kv store */
virtual Status DeleteKvStore(const AppId &appId, const StoreId &id);
/* delete kv store */
virtual Status DeleteAllKvStore(const AppId &appId);
virtual Status RegisterClientDeathObserver(const AppId &appId, sptr<IRemoteObject> observer);
virtual Status GetLocalDevice(DeviceInfo &device);
virtual Status GetRemoteDevices(std::vector<DeviceInfo> &deviceInfoList, DeviceFilterStrategy strategy);
virtual Status StartWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer, DeviceFilterStrategy strategy);
virtual Status StopWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer);
virtual sptr<IRemoteObject> GetRdbService();
virtual sptr<IRemoteObject> GetKVdbService();
virtual sptr<IRemoteObject> GetObjectService();
private:
static inline BrokerDelegator<KvStoreDataServiceProxy> delegator_;
};
} // namespace OHOS::DistributedKv
#endif // I_KV_STORE_DATA_SERVICE_H

View File

@ -1,50 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 I_KVSTORE_OBSERVER_H
#define I_KVSTORE_OBSERVER_H
#include "change_notification.h"
#include "iremote_broker.h"
#include "ikvstore_observer.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
namespace OHOS {
namespace DistributedKv {
class IKvStoreObserver : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreObserver");
virtual void OnChange(const ChangeNotification &changeNotification) = 0;
};
class KvStoreObserverStub : public IRemoteStub<IKvStoreObserver> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
};
class KvStoreObserverProxy : public IRemoteProxy<IKvStoreObserver> {
public:
explicit KvStoreObserverProxy(const sptr<IRemoteObject> &impl);
~KvStoreObserverProxy() = default;
void OnChange(const ChangeNotification &changeNotification) override;
private:
static inline BrokerDelegator<KvStoreObserverProxy> delegator_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // I_KVSTORE_OBSERVER_H

View File

@ -1,102 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 I_KVSTORE_RESULTSET_H
#define I_KVSTORE_RESULTSET_H
#include "message_parcel.h"
#include "iremote_broker.h"
#include "ikvstore_observer.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
#include "types.h"
namespace OHOS::DistributedKv {
class IKvStoreResultSet : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreResultSet")
virtual int GetCount() = 0;
virtual int GetPosition() = 0;
virtual bool MoveToFirst() = 0;
virtual bool MoveToLast() = 0;
virtual bool MoveToNext() = 0;
virtual bool MoveToPrevious() = 0;
virtual bool Move(int offset) = 0;
virtual bool MoveToPosition(int position) = 0;
virtual bool IsFirst() = 0;
virtual bool IsLast() = 0;
virtual bool IsBeforeFirst() = 0;
virtual bool IsAfterLast() = 0;
virtual Status GetEntry(Entry &entry) = 0;
};
class KvStoreResultSetStub : public IRemoteStub<IKvStoreResultSet> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
private:
int GetEntryOnRemote(MessageParcel &reply);
};
class KvStoreResultSetProxy : public IRemoteProxy<IKvStoreResultSet> {
public:
explicit KvStoreResultSetProxy(const sptr<IRemoteObject> &impl);
~KvStoreResultSetProxy() = default;
virtual int GetCount();
virtual int GetPosition();
virtual bool MoveToFirst();
virtual bool MoveToLast();
virtual bool MoveToNext();
virtual bool MoveToPrevious();
virtual bool Move(int offset);
virtual bool MoveToPosition(int position);
virtual bool IsFirst();
virtual bool IsLast();
virtual bool IsBeforeFirst();
virtual bool IsAfterLast();
virtual Status GetEntry(Entry &entry);
private:
virtual int SendRequest(uint32_t code);
virtual bool SendRequestRetBool(uint32_t code);
static inline BrokerDelegator<KvStoreResultSetProxy> delegator_;
};
} // namespace OHOS::DistributedKv
#endif // I_KVSTORE_RESULTSET_H

View File

@ -1,214 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 I_SINGLE_KVSTORE_H
#define I_SINGLE_KVSTORE_H
#include <map>
#include "message_parcel.h"
#include "iremote_broker.h"
#include "ikvstore_observer.h"
#include "ikvstore_sync_callback.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
#include "types.h"
#include "ikvstore_resultset.h"
namespace OHOS {
namespace DistributedKv {
class ISingleKvStore : public IRemoteBroker {
public:
enum {
PUT,
DELETE,
GET,
SUBSCRIBEKVSTORE,
UNSUBSCRIBEKVSTORE,
GETENTRIES,
GETRESULTSET,
CLOSERESULTSET,
REMOVEDEVICEDATA,
SYNC,
REGISTERSYNCCALLBACK,
UNREGISTERSYNCCALLBACK,
PUTBATCH,
DELETEBATCH,
STARTTRANSACTION,
COMMIT,
ROLLBACK,
GETENTRIESWITHQUERY,
GETRESULTSETWITHQUERY,
GETCOUNTWITHQUERY,
CONTROL,
SETCAPABILITYENABLED,
SETCAPABILITYRANGE,
SETSECURITLEVEL,
SYNC_WITH_CONDITION,
SUBSCRIBE,
UNSUBSCRIBE,
SINGLE_CMD_LAST,
};
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.ISingleKvStore")
virtual Status Put(const Key &key, const Value &value) = 0;
virtual Status Delete(const Key &key) = 0;
virtual Status Get(const Key &key, Value &value) = 0;
virtual Status SubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer) = 0;
virtual Status UnSubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer) = 0;
virtual Status GetEntries(const Key &prefixKey, std::vector<Entry> &entries) = 0;
virtual Status GetEntriesWithQuery(const std::string &query, std::vector<Entry> &entries) = 0;
virtual void GetResultSet(const Key &prefixKey,
std::function<void(Status, sptr<IKvStoreResultSet>)> callback) = 0;
virtual void GetResultSetWithQuery(const std::string &query,
std::function<void(Status, sptr<IKvStoreResultSet>)> callback) = 0;
virtual Status CloseResultSet(sptr<IKvStoreResultSet> resultSet) = 0;
virtual Status GetCountWithQuery(const std::string &query, int &result) = 0;
virtual Status Sync(const std::vector<std::string> &deviceIds, SyncMode mode,
uint32_t allowedDelayMs, uint64_t sequenceId) = 0;
virtual Status RemoveDeviceData(const std::string &device) = 0;
virtual Status RegisterSyncCallback(sptr<IKvStoreSyncCallback> callback) = 0;
virtual Status UnRegisterSyncCallback() = 0;
virtual Status PutBatch(const std::vector<Entry> &entries) = 0;
virtual Status DeleteBatch(const std::vector<Key> &keys) = 0;
virtual Status StartTransaction() = 0;
virtual Status Commit() = 0;
virtual Status Rollback() = 0;
virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, sptr<KvParam> &output) = 0;
virtual Status SetCapabilityEnabled(bool enabled) = 0;
virtual Status SetCapabilityRange(const std::vector<std::string> &localLabels,
const std::vector<std::string> &remoteSupportLabels) = 0;
virtual Status GetSecurityLevel(SecurityLevel &securityLevel) = 0;
virtual Status Sync(const std::vector<std::string> &deviceIds, SyncMode mode,
const std::string &query, uint64_t sequenceId) = 0;
virtual Status Subscribe(const std::vector<std::string> &deviceIds, const std::string &query,
uint64_t sequenceId) = 0;
virtual Status UnSubscribe(const std::vector<std::string> &deviceIds, const std::string &query,
uint64_t sequenceId) = 0;
};
class SingleKvStoreStub : public IRemoteStub<ISingleKvStore> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
private:
int PutOnRemote(MessageParcel &data, MessageParcel &reply);
int DeleteOnRemote(MessageParcel &data, MessageParcel &reply);
int GetOnRemote(MessageParcel &data, MessageParcel &reply);
int SubscribeKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int UnSubscribeKvStoreOnRemote(MessageParcel &data, MessageParcel &reply);
int GetEntriesOnRemote(MessageParcel &data, MessageParcel &reply);
int GetEntriesWithQueryOnRemote(MessageParcel &data, MessageParcel &reply);
int SyncOnRemote(MessageParcel &data, MessageParcel &reply);
int GetResultSetOnRemote(MessageParcel &data, MessageParcel &reply);
int GetResultSetWithQueryOnRemote(MessageParcel &data, MessageParcel &reply);
int GetCountWithQueryOnRemote(MessageParcel &data, MessageParcel &reply);
int CloseResultSetOnRemote(MessageParcel &data, MessageParcel &reply);
int RemoveDeviceDataOnRemote(MessageParcel &data, MessageParcel &reply);
int RegisterSyncCallbackOnRemote(MessageParcel &data, MessageParcel &reply);
int UnRegisterSyncCallbackOnRemote(MessageParcel &data, MessageParcel &reply);
int PutBatchOnRemote(MessageParcel &data, MessageParcel &reply);
int DeleteBatchOnRemote(MessageParcel &data, MessageParcel &reply);
int StartTransactionOnRemote(MessageParcel &data, MessageParcel &reply);
int CommitOnRemote(MessageParcel &data, MessageParcel &reply);
int RollbackOnRemote(MessageParcel &data, MessageParcel &reply);
int ControlOnRemote(MessageParcel &data, MessageParcel &reply);
int OnCapabilityEnableRequest(MessageParcel &data, MessageParcel &reply);
int OnCapabilityRangeRequest(MessageParcel &data, MessageParcel &reply);
int OnSecurityLevelRequest(MessageParcel &data, MessageParcel &reply);
int OnSyncRequest(MessageParcel &data, MessageParcel &reply);
int OnSubscribeRequest(MessageParcel &data, MessageParcel &reply);
int OnUnSubscribeRequest(MessageParcel &data, MessageParcel &reply);
int WriteEntriesParcelable(MessageParcel &reply, Status status, std::vector<Entry> entries, int bufferSize);
int GetTotalEntriesSize(std::vector<Entry> entries);
using RequestHandler = int(SingleKvStoreStub::*)(MessageParcel&, MessageParcel&);
static constexpr RequestHandler HANDLERS[SINGLE_CMD_LAST] = {
[PUT] = &SingleKvStoreStub::PutOnRemote,
[DELETE] = &SingleKvStoreStub::DeleteOnRemote,
[GET] = &SingleKvStoreStub::GetOnRemote,
[SUBSCRIBEKVSTORE] = &SingleKvStoreStub::SubscribeKvStoreOnRemote,
[UNSUBSCRIBEKVSTORE] = &SingleKvStoreStub::UnSubscribeKvStoreOnRemote,
[GETENTRIES] = &SingleKvStoreStub::GetEntriesOnRemote,
[GETRESULTSET] = &SingleKvStoreStub::GetResultSetOnRemote,
[CLOSERESULTSET] = &SingleKvStoreStub::CloseResultSetOnRemote,
[REMOVEDEVICEDATA] = &SingleKvStoreStub::RemoveDeviceDataOnRemote,
[SYNC] = &SingleKvStoreStub::SyncOnRemote,
[REGISTERSYNCCALLBACK] = &SingleKvStoreStub::RegisterSyncCallbackOnRemote,
[UNREGISTERSYNCCALLBACK] = &SingleKvStoreStub::UnRegisterSyncCallbackOnRemote,
[PUTBATCH] = &SingleKvStoreStub::PutBatchOnRemote,
[DELETEBATCH] = &SingleKvStoreStub::DeleteBatchOnRemote,
[STARTTRANSACTION] = &SingleKvStoreStub::StartTransactionOnRemote,
[COMMIT] = &SingleKvStoreStub::CommitOnRemote,
[ROLLBACK] = &SingleKvStoreStub::RollbackOnRemote,
[GETENTRIESWITHQUERY] = &SingleKvStoreStub::GetEntriesWithQueryOnRemote,
[GETRESULTSETWITHQUERY] = &SingleKvStoreStub::GetResultSetWithQueryOnRemote,
[GETCOUNTWITHQUERY] = &SingleKvStoreStub::GetCountWithQueryOnRemote,
[CONTROL] = &SingleKvStoreStub::ControlOnRemote,
[SETCAPABILITYENABLED] = &SingleKvStoreStub::OnCapabilityEnableRequest,
[SETCAPABILITYRANGE] = &SingleKvStoreStub::OnCapabilityRangeRequest,
[SETSECURITLEVEL] = &SingleKvStoreStub::OnSecurityLevelRequest,
[SYNC_WITH_CONDITION] = &SingleKvStoreStub::OnSyncRequest,
[SUBSCRIBE] = &SingleKvStoreStub::OnSubscribeRequest,
[UNSUBSCRIBE] = &SingleKvStoreStub::OnUnSubscribeRequest,
};
};
class SingleKvStoreProxy : public IRemoteProxy<ISingleKvStore> {
public:
explicit SingleKvStoreProxy(const sptr<IRemoteObject> &impl);
~SingleKvStoreProxy() = default;
virtual Status Put(const Key &key, const Value &value);
virtual Status Delete(const Key &key);
virtual Status Get(const Key &key, Value &value);
virtual Status SubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer);
virtual Status UnSubscribeKvStore(const SubscribeType subscribeType, sptr<IKvStoreObserver> observer);
virtual Status GetEntries(const Key &prefixKey, std::vector<Entry> &entries);
virtual Status GetEntriesWithQuery(const std::string &query, std::vector<Entry> &entries);
virtual void GetResultSet(const Key &prefixKey, std::function<void(Status, sptr<IKvStoreResultSet>)> callback);
virtual void GetResultSetWithQuery(const std::string &query,
std::function<void(Status, sptr<IKvStoreResultSet>)> callback);
virtual Status CloseResultSet(sptr<IKvStoreResultSet> resultSet);
virtual Status GetCountWithQuery(const std::string &query, int &result);
virtual Status Sync(const std::vector<std::string> &deviceIds, SyncMode mode, uint32_t allowedDelayMs,
uint64_t sequenceId);
virtual Status Sync(const std::vector<std::string> &deviceIds, SyncMode mode,
const std::string &query, uint64_t sequenceId);
virtual Status RemoveDeviceData(const std::string &device);
virtual Status RegisterSyncCallback(sptr<IKvStoreSyncCallback> callback);
virtual Status UnRegisterSyncCallback();
virtual Status PutBatch(const std::vector<Entry> &entries);
virtual Status DeleteBatch(const std::vector<Key> &keys);
virtual Status StartTransaction();
virtual Status Commit();
virtual Status Rollback();
virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, sptr<KvParam> &output);
virtual Status SetCapabilityEnabled(bool enabled);
virtual Status SetCapabilityRange(const std::vector<std::string> &localLabels,
const std::vector<std::string> &remoteSupportLabels);
virtual Status GetSecurityLevel(SecurityLevel &securityLevel);
virtual Status Subscribe(const std::vector<std::string> &deviceIds, const std::string &query,
uint64_t sequenceId);
virtual Status UnSubscribe(const std::vector<std::string> &deviceIds, const std::string &query,
uint64_t sequenceId);
private:
static inline BrokerDelegator<SingleKvStoreProxy> delegator_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // I_SINGLE_KVSTORE_H

View File

@ -1,50 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 I_KVSTORE_SYNC_CALLBACK_H
#define I_KVSTORE_SYNC_CALLBACK_H
#include <map>
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
#include "types.h"
namespace OHOS {
namespace DistributedKv {
class IKvStoreSyncCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreSyncCallback");
virtual void SyncCompleted(const std::map<std::string, Status> &results, uint64_t sequenceId) = 0;
};
class KvStoreSyncCallbackStub : public IRemoteStub<IKvStoreSyncCallback> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option) override;
};
class KvStoreSyncCallbackProxy : public IRemoteProxy<IKvStoreSyncCallback> {
public:
explicit KvStoreSyncCallbackProxy(const sptr<IRemoteObject> &impl);
~KvStoreSyncCallbackProxy() = default;
void SyncCompleted(const std::map<std::string, Status> &results, uint64_t sequenceId) override;
private:
static inline BrokerDelegator<KvStoreSyncCallbackProxy> delegator_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // I_KVSTORE_SYNC_CALLBACK_H

View File

@ -1,28 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 INNER_TYPES_H
#define INNER_TYPES_H
namespace OHOS {
namespace DistributedKv {
enum class InnerStatus {
SUCCESS = 0,
DECREASE_REFCOUNT,
ERROR,
};
} // namespace DistributedKv
} // namespace OHOS
#endif

View File

@ -1,299 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 DISTRIBUTED_DATA_FRAMEWORKS_COMMON_ITYPES_UTIL_H
#define DISTRIBUTED_DATA_FRAMEWORKS_COMMON_ITYPES_UTIL_H
#include <climits>
#include <memory>
#include "change_notification.h"
#include "message_parcel.h"
#include "rdb_types.h"
#include "types.h"
namespace OHOS::DistributedKv {
class ITypesUtil final {
public:
static bool Marshal(MessageParcel &data);
static bool Unmarshal(MessageParcel &data);
static bool Marshalling(uint32_t input, MessageParcel &data);
static bool Unmarshalling(uint32_t &output, MessageParcel &data);
static bool Marshalling(int32_t input, MessageParcel &data);
static bool Unmarshalling(int32_t &output, MessageParcel &data);
static bool Marshalling(uint64_t input, MessageParcel &data);
static bool Unmarshalling(uint64_t &output, MessageParcel &data);
static bool Marshalling(const std::string &input, MessageParcel &data);
static bool Unmarshalling(std::string &output, MessageParcel &data);
static bool Marshalling(const std::vector<uint8_t> &input, MessageParcel &data);
static bool Unmarshalling(std::vector<uint8_t> &output, MessageParcel &data);
static bool Marshalling(const Blob &blob, MessageParcel &data);
static bool Unmarshalling(Blob &output, MessageParcel &data);
static bool Marshalling(const Entry &entry, MessageParcel &data);
static bool Unmarshalling(Entry &output, MessageParcel &data);
static bool Marshalling(const DeviceInfo &entry, MessageParcel &data);
static bool Unmarshalling(DeviceInfo &output, MessageParcel &data);
static bool Marshalling(const ChangeNotification &notification, MessageParcel &parcel);
static bool Unmarshalling(ChangeNotification &output, MessageParcel &parcel);
static bool Marshalling(const DistributedRdb::RdbSyncerParam &param, MessageParcel &parcel);
static bool Unmarshalling(DistributedRdb::RdbSyncerParam &param, MessageParcel &parcel);
static bool Marshalling(const DistributedRdb::SyncOption &option, MessageParcel &parcel);
static bool Unmarshalling(DistributedRdb::SyncOption &option, MessageParcel &parcel);
static bool Marshalling(const DistributedRdb::RdbPredicates &predicates, MessageParcel &parcel);
static bool Unmarshalling(DistributedRdb::RdbPredicates &predicates, MessageParcel &parcel);
static bool Marshalling(const Options &input, MessageParcel &data);
static bool Unmarshalling(Options &output, MessageParcel &data);
static bool Marshalling(const sptr<IRemoteObject> &input, MessageParcel &data);
static bool Unmarshalling(sptr<IRemoteObject> &output, MessageParcel &data);
static int64_t GetTotalSize(const std::vector<Entry> &entries);
static int64_t GetTotalSize(const std::vector<Key> &entries);
template<class T>
static bool Marshalling(const std::vector<T> &val, MessageParcel &parcel);
template<class T>
static bool Unmarshalling(std::vector<T> &val, MessageParcel &parcel);
template<class K, class V>
static bool Marshalling(const std::map<K, V> &val, MessageParcel &parcel);
template<class K, class V>
static bool Unmarshalling(std::map<K, V> &val, MessageParcel &parcel);
template<typename T, typename... Types>
static bool Marshal(MessageParcel &parcel, const T &first, const Types &...others);
template<typename T, typename... Types>
static bool Unmarshal(MessageParcel &parcel, T &first, Types &...others);
template<typename T>
static Status MarshalToBuffer(const T &input, int size, MessageParcel &data);
template<typename T>
static Status MarshalToBuffer(const std::vector<T> &input, int size, MessageParcel &data);
template<typename T>
static Status UnmarshalFromBuffer(MessageParcel &data, int size, T &output);
template<typename T>
static Status UnmarshalFromBuffer(MessageParcel &data, int size, std::vector<T> &output);
};
template<class T>
bool ITypesUtil::Marshalling(const std::vector<T> &val, MessageParcel &parcel)
{
if (val.size() > INT_MAX) {
return false;
}
if (!parcel.WriteInt32(static_cast<int32_t>(val.size()))) {
return false;
}
for (auto &v : val) {
if (!Marshalling(v, parcel)) {
return false;
}
}
return true;
}
template<class T>
bool ITypesUtil::Unmarshalling(std::vector<T> &val, MessageParcel &parcel)
{
int32_t len = parcel.ReadInt32();
if (len < 0) {
return false;
}
size_t readAbleSize = parcel.GetReadableBytes();
size_t size = static_cast<size_t>(len);
if ((size > readAbleSize) || (size > val.max_size())) {
return false;
}
val.resize(size);
if (val.size() < size) {
return false;
}
for (auto &v : val) {
if (!Unmarshalling(v, parcel)) {
return false;
}
}
return true;
}
template<typename T>
Status ITypesUtil::MarshalToBuffer(const T &input, int size, MessageParcel &data)
{
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(size);
if (!data.WriteBool(buffer != nullptr)) {
return Status::IPC_ERROR;
}
if (buffer == nullptr) {
return Status::ILLEGAL_STATE;
}
int leftSize = size;
uint8_t *cursor = buffer.get();
if (!input.WriteToBuffer(cursor, leftSize)) {
return Status::IPC_ERROR;
}
return data.WriteRawData(buffer.get(), size) ? Status::SUCCESS : Status::IPC_ERROR;
}
template<typename T>
Status ITypesUtil::MarshalToBuffer(const std::vector<T> &input, int size, MessageParcel &data)
{
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(size);
if (!data.WriteBool(buffer != nullptr)) {
return Status::IPC_ERROR;
}
if (buffer == nullptr) {
return Status::ILLEGAL_STATE;
}
uint8_t *cursor = buffer.get();
for (const auto &entry : input) {
if (!entry.WriteToBuffer(cursor, size)) {
return Status::IPC_ERROR;
}
}
if (!data.WriteInt32(input.size())) {
return Status::IPC_ERROR;
}
return data.WriteRawData(buffer.get(), size) ? Status::SUCCESS : Status::IPC_ERROR;
}
template<typename T>
Status ITypesUtil::UnmarshalFromBuffer(MessageParcel &data, int size, T &output)
{
if (size < 0) {
return Status::INVALID_ARGUMENT;
}
if (!data.ReadBool()) {
return Status::ILLEGAL_STATE;
}
const uint8_t *buffer = reinterpret_cast<const uint8_t *>(data.ReadRawData(size));
if (buffer == nullptr) {
return Status::INVALID_ARGUMENT;
}
return output.ReadFromBuffer(buffer, size) ? Status::SUCCESS : Status::IPC_ERROR;
}
template<typename T>
Status ITypesUtil::UnmarshalFromBuffer(MessageParcel &data, int size, std::vector<T> &output)
{
if (size < 0) {
return Status::INVALID_ARGUMENT;
}
if (!data.ReadBool()) {
return Status::ILLEGAL_STATE;
}
int count = data.ReadInt32();
const uint8_t *buffer = reinterpret_cast<const uint8_t *>(data.ReadRawData(size));
if (count < 0 || buffer == nullptr) {
return Status::INVALID_ARGUMENT;
}
output.resize(count);
for (auto &entry : output) {
if (!entry.ReadFromBuffer(buffer, size)) {
output.clear();
return Status::IPC_ERROR;
}
}
return Status::SUCCESS;
}
template<typename T, typename... Types>
bool ITypesUtil::Marshal(MessageParcel &parcel, const T &first, const Types &...others)
{
if (!Marshalling(first, parcel)) {
return false;
}
return Marshal(parcel, others...);
}
template<typename T, typename... Types>
bool ITypesUtil::Unmarshal(MessageParcel &parcel, T &first, Types &...others)
{
if (!Unmarshalling(first, parcel)) {
return false;
}
return Unmarshal(parcel, others...);
}
template<class K, class V>
bool ITypesUtil::Marshalling(const std::map<K, V> &result, MessageParcel &parcel)
{
if (!parcel.WriteInt32(static_cast<int32_t>(result.size()))) {
return false;
}
for (const auto &entry : result) {
if (!Marshalling(entry.first, parcel)) {
return false;
}
if (!Marshalling(entry.second, parcel)) {
return false;
}
}
return true;
}
template<class K, class V>
bool ITypesUtil::Unmarshalling(std::map<K, V> &val, MessageParcel &parcel)
{
int32_t size = 0;
if (!parcel.ReadInt32(size)) {
return false;
}
if (size < 0) {
return false;
}
size_t readAbleSize = parcel.GetReadableBytes();
size_t len = static_cast<size_t>(size);
if ((len > readAbleSize) || len > val.max_size()) {
return false;
}
for (int32_t i = 0; i < size; i++) {
K key;
if (!Unmarshalling(key, parcel)) {
return false;
}
V value;
if (!Unmarshalling(value, parcel)) {
return false;
}
val.insert({ key, value });
}
return true;
}
} // namespace OHOS::DistributedKv
#endif

View File

@ -1,51 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 KVSTORE_DATASHARE_BRIDGE_H
#define KVSTORE_DATASHARE_BRIDGE_H
#include "kvstore_result_set.h"
#include "single_kvstore.h"
#include "result_set_bridge.h"
#include "datashare_errno.h"
namespace OHOS {
namespace DistributedKv {
class KvStoreDataShareBridge : public DataShare::ResultSetBridge {
public:
KvStoreDataShareBridge(std::shared_ptr<KvStoreResultSet> kvResultSet);
~KvStoreDataShareBridge() = default;
int GetRowCount(int32_t &count) override;
int GetAllColumnNames(std::vector<std::string> &columnNames) override;
bool OnGo(int32_t startRowIndex, int32_t targetRowIndex, DataShare::ResultSetBridge::Writer &writer) override;
private:
int Count();
bool FillBlock(int startRowIndex, DataShare::ResultSetBridge::Writer &writer);
static constexpr int32_t INVALID_COUNT = -1;
int32_t resultRowCount {INVALID_COUNT};
std::shared_ptr<KvStoreResultSet> kvResultSet_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // KVSTORE_DATASHARE_BRIDGE_H

View File

@ -1,235 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "Blob"
#include "blob.h"
#include <securec.h>
#include "log_print.h"
namespace OHOS {
namespace DistributedKv {
Blob::Blob() { }
Blob::Blob(const Blob &blob)
{
blob_ = blob.Data();
}
Blob::Blob(Blob &&blob)
{
blob_.swap(blob.blob_);
}
Blob &Blob::operator=(const Blob &blob)
{
// Self-assignment detection
if (&blob == this) {
return *this;
}
blob_ = blob.Data();
return *this;
}
Blob &Blob::operator=(Blob &&blob)
{
// Self-assignment detection
if (&blob == this) {
return *this;
}
blob_.swap(blob.blob_);
return *this;
}
Blob::Blob(const char *str, size_t n)
: blob_()
{
if (str != nullptr) {
blob_ = std::vector<uint8_t>(str, str + n);
}
}
Blob::Blob(const std::string &str)
: blob_(str.begin(), str.end())
{
}
Blob &Blob::operator=(const std::string &str)
{
blob_ = { str.begin(), str.end() };
return *this;
}
Blob::Blob(const char *str)
: blob_()
{
if (str != nullptr) {
blob_ = std::vector<uint8_t>(str, str + strlen(str));
}
}
Blob &Blob::operator=(const char *str)
{
if (str != nullptr) {
blob_ = std::vector<uint8_t>(str, str + strlen(str));
}
return *this;
}
Blob::Blob(const std::vector<uint8_t> &bytes)
: blob_(bytes)
{
}
Blob::Blob(std::vector<uint8_t> &&bytes)
: blob_(std::move(bytes))
{
}
const std::vector<uint8_t> &Blob::Data() const
{
return blob_;
}
Blob::operator const std::vector<uint8_t> &() const
{
return Data();
}
Blob::operator std::vector<uint8_t> &&() noexcept
{
return std::move(blob_);
}
size_t Blob::Size() const
{
return blob_.size();
}
int Blob::RawSize() const
{
return sizeof(int) + blob_.size();
}
bool Blob::Empty() const
{
return blob_.empty();
}
uint8_t Blob::operator[](size_t n) const
{
if (n >= Size()) {
ZLOGE("Trying to get a out-of-range Blob member.");
return 0;
}
return blob_[n];
}
bool Blob::operator==(const Blob &blob) const
{
return blob_ == blob.blob_;
}
void Blob::Clear()
{
blob_.clear();
}
std::string Blob::ToString() const
{
std::string str(blob_.begin(), blob_.end());
return str;
}
int Blob::Compare(const Blob &blob) const
{
if (blob_ < blob.blob_) {
return -1;
}
if (blob_ == blob.blob_) {
return 0;
}
return 1;
}
bool Blob::StartsWith(const Blob &blob) const
{
size_t len = blob.Size();
if (Size() < len) {
return false;
}
for (size_t i = 0; i < len; ++i) {
if (blob_[i] != blob.blob_[i]) {
return false;
}
}
return true;
}
bool Blob::Marshalling(Parcel &parcel) const
{
return parcel.WriteUInt8Vector(this->blob_);
}
Blob *Blob::Unmarshalling(Parcel &parcel)
{
std::vector<uint8_t> blobData;
if (!parcel.ReadUInt8Vector(&blobData)) {
return nullptr;
}
return new Blob(blobData);
}
/* write blob size and data to memory buffer. return error when bufferLeftSize not enough. */
bool Blob::WriteToBuffer(uint8_t *&cursorPtr, int &bufferLeftSize) const
{
if (cursorPtr == nullptr || bufferLeftSize < static_cast<int>(blob_.size() + sizeof(int))) {
return false;
}
*reinterpret_cast<int32_t *>(cursorPtr) = static_cast<int32_t>(blob_.size());
bufferLeftSize -= sizeof(int32_t);
cursorPtr += sizeof(int32_t);
errno_t err = memcpy_s(cursorPtr, bufferLeftSize, blob_.data(), blob_.size());
if (err != EOK) {
return false;
}
cursorPtr += blob_.size();
bufferLeftSize -= blob_.size();
return true;
}
/* read a blob from memory buffer. */
bool Blob::ReadFromBuffer(const uint8_t *&cursorPtr, int &bufferLeftSize)
{
if (cursorPtr == nullptr || bufferLeftSize < static_cast<int>(sizeof(int))) {
return false;
}
int blobSize = *reinterpret_cast<const int *>(cursorPtr);
bufferLeftSize -= sizeof(int) + blobSize;
if (blobSize < 0 || bufferLeftSize < 0) {
return false;
}
cursorPtr += sizeof(int);
blob_ = std::vector<uint8_t>(cursorPtr, cursorPtr + blobSize);
cursorPtr += blobSize;
return true;
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,154 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "ChangeNotification"
#include "change_notification.h"
#include "constant.h"
#include "log_print.h"
namespace OHOS {
namespace DistributedKv {
ChangeNotification::ChangeNotification(std::vector<Entry> &&insertEntries, std::vector<Entry> &&updateEntries,
std::vector<Entry> &&deleteEntries, const std::string &deviceId, bool isClear)
: insertEntries_(std::move(insertEntries)), updateEntries_(std::move(updateEntries)),
deleteEntries_(std::move(deleteEntries)), deviceId_(deviceId), isClear_(isClear)
{}
ChangeNotification::~ChangeNotification()
{}
const std::vector<Entry> &ChangeNotification::GetInsertEntries() const
{
return insertEntries_;
}
const std::vector<Entry> &ChangeNotification::GetUpdateEntries() const
{
return updateEntries_;
}
const std::vector<Entry> &ChangeNotification::GetDeleteEntries() const
{
return deleteEntries_;
}
const std::string &ChangeNotification::GetDeviceId() const
{
return deviceId_;
}
bool ChangeNotification::IsClear() const
{
return isClear_;
}
bool ChangeNotification::Marshalling(Parcel &parcel) const
{
if (!parcel.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
return false;
}
int32_t lenInsert = static_cast<int32_t>(insertEntries_.size());
if (!parcel.WriteInt32(lenInsert)) {
return false;
}
for (const auto &entry : insertEntries_) {
if (!parcel.WriteParcelable(&entry)) {
return false;
}
}
int32_t lenUpdate = static_cast<int32_t>(updateEntries_.size());
if (!parcel.WriteInt32(lenUpdate)) {
return false;
}
for (const auto &entry : updateEntries_) {
if (!parcel.WriteParcelable(&entry)) {
return false;
}
}
int32_t lenDelete = static_cast<int32_t>(deleteEntries_.size());
if (!parcel.WriteInt32(lenDelete)) {
return false;
}
for (const auto &entry : deleteEntries_) {
if (!parcel.WriteParcelable(&entry)) {
return false;
}
}
if (!parcel.WriteString(deviceId_)) {
ZLOGE("WriteString deviceId_ failed.");
return false;
}
return parcel.WriteBool(isClear_);
}
ChangeNotification *ChangeNotification::Unmarshalling(Parcel &parcel)
{
std::vector<Entry> insertEntries;
std::vector<Entry> updateEntries;
std::vector<Entry> deleteEntries;
int lenInsert = parcel.ReadInt32();
if (lenInsert < 0) {
ZLOGE("lenInsert is %d", lenInsert);
return nullptr;
}
for (int i = 0; i < lenInsert; i++) {
sptr<Entry> entryTmp = parcel.ReadParcelable<Entry>();
if (entryTmp != nullptr) {
insertEntries.push_back(*entryTmp);
} else {
ZLOGE("insertEntries get nullptr");
return nullptr;
}
}
int lenUpdate = parcel.ReadInt32();
if (lenUpdate < 0) {
ZLOGE("lenUpdate is %d", lenUpdate);
return nullptr;
}
for (int i = 0; i < lenUpdate; i++) {
sptr<Entry> entryTmp = parcel.ReadParcelable<Entry>();
if (entryTmp != nullptr) {
updateEntries.push_back(*entryTmp);
} else {
ZLOGE("updateEntries get nullptr");
return nullptr;
}
}
int lenDelete = parcel.ReadInt32();
if (lenDelete < 0) {
ZLOGE("lenDelete is %d", lenDelete);
return nullptr;
}
for (int i = 0; i < lenDelete; i++) {
sptr<Entry> entryTmp = parcel.ReadParcelable<Entry>();
if (entryTmp != nullptr) {
deleteEntries.push_back(*entryTmp);
} else {
ZLOGE("deleteEntries get nullptr");
return nullptr;
}
}
std::string deviceId = parcel.ReadString();
bool isClear = parcel.ReadBool();
return new(std::nothrow) ChangeNotification(std::move(insertEntries), std::move(updateEntries),
std::move(deleteEntries), deviceId, isClear);
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,787 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "DataQuery"
#include "data_query.h"
#include "log_print.h"
#include "query.h"
namespace OHOS {
namespace DistributedKv {
const char * const DataQuery::EQUAL_TO = "^EQUAL";
const char * const DataQuery::NOT_EQUAL_TO = "^NOT_EQUAL";
const char * const DataQuery::GREATER_THAN = "^GREATER";
const char * const DataQuery::LESS_THAN = "^LESS";
const char * const DataQuery::GREATER_THAN_OR_EQUAL_TO = "^GREATER_EQUAL";
const char * const DataQuery::LESS_THAN_OR_EQUAL_TO = "^LESS_EQUAL";
const char * const DataQuery::IS_NULL = "^IS_NULL";
const char * const DataQuery::IN = "^IN";
const char * const DataQuery::NOT_IN = "^NOT_IN";
const char * const DataQuery::LIKE = "^LIKE";
const char * const DataQuery::NOT_LIKE = "^NOT_LIKE";
const char * const DataQuery::AND = "^AND";
const char * const DataQuery::OR = "^OR";
const char * const DataQuery::ORDER_BY_ASC = "^ASC";
const char * const DataQuery::ORDER_BY_DESC = "^DESC";
const char * const DataQuery::LIMIT = "^LIMIT";
const char * const DataQuery::SPACE = " ";
const char * const DataQuery::SPECIAL = "^";
const char * const DataQuery::SPECIAL_ESCAPE = "(^)";
const char * const DataQuery::SPACE_ESCAPE = "^^";
const char * const DataQuery::EMPTY_STRING = "^EMPTY_STRING";
const char * const DataQuery::START_IN = "^START";
const char * const DataQuery::END_IN = "^END";
const char * const DataQuery::BEGIN_GROUP = "^BEGIN_GROUP";
const char * const DataQuery::END_GROUP = "^END_GROUP";
const char * const DataQuery::KEY_PREFIX = "^KEY_PREFIX";
const char * const DataQuery::DEVICE_ID = "^DEVICE_ID";
const char * const DataQuery::IS_NOT_NULL = "^IS_NOT_NULL";
const char * const DataQuery::TYPE_STRING = "STRING";
const char * const DataQuery::TYPE_INTEGER = "INTEGER";
const char * const DataQuery::TYPE_LONG = "LONG";
const char * const DataQuery::TYPE_DOUBLE = "DOUBLE";
const char * const DataQuery::TYPE_BOOLEAN = "BOOL";
const char * const DataQuery::VALUE_TRUE = "true";
const char * const DataQuery::VALUE_FALSE = "false";
const char * const DataQuery::SUGGEST_INDEX = "^SUGGEST_INDEX";
const char * const DataQuery::IN_KEYS = "^IN_KEYS";
constexpr int MAX_QUERY_LENGTH = 5 * 1024; // Max query string length 5k
DataQuery::DataQuery()
{
query_ = std::make_shared<DistributedDB::Query>();
}
DataQuery& DataQuery::Reset()
{
str_ = "";
hasKeys_ = false;
hasPrefix_ = false;
deviceId_ = "";
prefix_ = "";
query_ = std::make_shared<DistributedDB::Query>();
return *this;
}
DataQuery& DataQuery::EqualTo(const std::string &field, const int value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(EQUAL_TO, TYPE_INTEGER, myField, value);
query_->EqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::EqualTo(const std::string &field, const int64_t value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(EQUAL_TO, TYPE_LONG, myField, value);
query_->EqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::EqualTo(const std::string &field, const double value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(EQUAL_TO, TYPE_DOUBLE, myField, value);
query_->EqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::EqualTo(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(EQUAL_TO, TYPE_STRING, myField, myValue);
query_->EqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::EqualTo(const std::string &field, const bool value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonBoolean(EQUAL_TO, TYPE_BOOLEAN, myField, value);
query_->EqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::NotEqualTo(const std::string &field, const int value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(NOT_EQUAL_TO, TYPE_INTEGER, myField, value);
query_->NotEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::NotEqualTo(const std::string &field, const int64_t value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(NOT_EQUAL_TO, TYPE_LONG, myField, value);
query_->NotEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::NotEqualTo(const std::string &field, const double value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(NOT_EQUAL_TO, TYPE_DOUBLE, myField, value);
query_->NotEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::NotEqualTo(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(NOT_EQUAL_TO, TYPE_STRING, myField, myValue);
query_->NotEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::NotEqualTo(const std::string &field, const bool value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonBoolean(NOT_EQUAL_TO, TYPE_BOOLEAN, myField, value);
query_->NotEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThan(const std::string &field, const int value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(GREATER_THAN, TYPE_INTEGER, myField, value);
query_->GreaterThan(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThan(const std::string &field, const int64_t value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(GREATER_THAN, TYPE_LONG, myField, value);
query_->GreaterThan(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThan(const std::string &field, const double value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(GREATER_THAN, TYPE_DOUBLE, myField, value);
query_->GreaterThan(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThan(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(GREATER_THAN, TYPE_STRING, myField, myValue);
query_->GreaterThan(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThan(const std::string &field, const int value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(LESS_THAN, TYPE_INTEGER, myField, value);
query_->LessThan(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThan(const std::string &field, const int64_t value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(LESS_THAN, TYPE_LONG, myField, value);
query_->LessThan(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThan(const std::string &field, const double value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(LESS_THAN, TYPE_DOUBLE, myField, value);
query_->LessThan(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThan(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(LESS_THAN, TYPE_STRING, myField, myValue);
query_->LessThan(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThanOrEqualTo(const std::string &field, const int value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(GREATER_THAN_OR_EQUAL_TO, TYPE_INTEGER, myField, value);
query_->GreaterThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThanOrEqualTo(const std::string &field, const int64_t value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(GREATER_THAN_OR_EQUAL_TO, TYPE_LONG, myField, value);
query_->GreaterThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThanOrEqualTo(const std::string &field, const double value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(GREATER_THAN_OR_EQUAL_TO, TYPE_DOUBLE, myField, value);
query_->GreaterThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::GreaterThanOrEqualTo(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(GREATER_THAN_OR_EQUAL_TO, TYPE_STRING, myField, myValue);
query_->GreaterThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThanOrEqualTo(const std::string &field, const int value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(LESS_THAN_OR_EQUAL_TO, TYPE_INTEGER, myField, value);
query_->LessThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThanOrEqualTo(const std::string &field, const int64_t value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(LESS_THAN_OR_EQUAL_TO, TYPE_LONG, myField, value);
query_->LessThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThanOrEqualTo(const std::string &field, const double value)
{
std::string myField = field;
if (ValidateField(myField)) {
AppendCommon(LESS_THAN_OR_EQUAL_TO, TYPE_DOUBLE, myField, value);
query_->LessThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::LessThanOrEqualTo(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(LESS_THAN_OR_EQUAL_TO, TYPE_STRING, myField, myValue);
query_->LessThanOrEqualTo(field, value);
}
return *this;
}
DataQuery& DataQuery::IsNull(const std::string &field)
{
std::string myField = field;
if (ValidateField(myField)) {
str_.append(SPACE);
str_.append(IS_NULL);
str_.append(SPACE);
EscapeSpace(myField);
str_.append(myField);
query_->IsNull(field);
}
return *this;
}
DataQuery& DataQuery::IsNotNull(const std::string &field)
{
std::string myField = field;
if (ValidateField(myField)) {
str_.append(SPACE);
str_.append(IS_NOT_NULL);
str_.append(SPACE);
EscapeSpace(myField);
str_.append(myField);
query_->IsNotNull(field);
}
return *this;
}
DataQuery& DataQuery::In(const std::string &field, const std::vector<int> &valueList)
{
ZLOGD("DataQuery::In int");
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonList(IN, TYPE_INTEGER, myField, valueList);
query_->In(field, valueList);
}
return *this;
}
DataQuery& DataQuery::In(const std::string &field, const std::vector<int64_t> &valueList)
{
ZLOGD("DataQuery::In int64_t");
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonList(IN, TYPE_LONG, myField, valueList);
query_->In(field, valueList);
}
return *this;
}
DataQuery& DataQuery::In(const std::string &field, const std::vector<double> &valueList)
{
ZLOGD("DataQuery::In double");
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonList(IN, TYPE_DOUBLE, myField, valueList);
query_->In(field, valueList);
}
return *this;
}
DataQuery& DataQuery::In(const std::string &field, const std::vector<std::string> &valueList)
{
ZLOGD("DataQuery::In string");
std::string myField = field;
std::vector<std::string> myValueList(valueList);
if (ValidateField(myField)) {
AppendCommonListString(IN, TYPE_STRING, myField, myValueList);
query_->In(field, valueList);
}
return *this;
}
DataQuery& DataQuery::NotIn(const std::string &field, const std::vector<int> &valueList)
{
ZLOGD("DataQuery::NotIn int");
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonList(NOT_IN, TYPE_INTEGER, myField, valueList);
query_->NotIn(field, valueList);
}
return *this;
}
DataQuery& DataQuery::NotIn(const std::string &field, const std::vector<int64_t> &valueList)
{
ZLOGD("DataQuery::NotIn int64_t");
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonList(NOT_IN, TYPE_LONG, myField, valueList);
query_->NotIn(field, valueList);
}
return *this;
}
DataQuery& DataQuery::NotIn(const std::string &field, const std::vector<double> &valueList)
{
ZLOGD("DataQuery::NotIn double");
std::string myField = field;
if (ValidateField(myField)) {
AppendCommonList(NOT_IN, TYPE_DOUBLE, myField, valueList);
query_->NotIn(field, valueList);
}
return *this;
}
DataQuery& DataQuery::NotIn(const std::string &field, const std::vector<std::string> &valueList)
{
ZLOGD("DataQuery::NotIn string");
std::string myField = field;
std::vector<std::string> myValueList(valueList);
if (ValidateField(myField)) {
AppendCommonListString(NOT_IN, TYPE_STRING, myField, myValueList);
query_->NotIn(field, valueList);
}
return *this;
}
DataQuery& DataQuery::Like(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(LIKE, myField, myValue);
query_->Like(field, value);
}
return *this;
}
DataQuery& DataQuery::Unlike(const std::string &field, const std::string &value)
{
std::string myField = field;
std::string myValue = value;
if (ValidateField(myField)) {
AppendCommonString(NOT_LIKE, myField, myValue);
query_->NotLike(field, value);
}
return *this;
}
DataQuery& DataQuery::And()
{
str_.append(SPACE);
str_.append(AND);
query_->And();
return *this;
}
DataQuery& DataQuery::Or()
{
str_.append(SPACE);
str_.append(OR);
query_->Or();
return *this;
}
DataQuery& DataQuery::OrderByAsc(const std::string &field)
{
std::string myField = field;
if (ValidateField(myField)) {
str_.append(SPACE);
str_.append(ORDER_BY_ASC);
str_.append(SPACE);
EscapeSpace(myField);
str_.append(myField);
query_->OrderBy(field);
}
return *this;
}
DataQuery& DataQuery::OrderByDesc(const std::string &field)
{
std::string myField = field;
if (ValidateField(myField)) {
str_.append(SPACE);
str_.append(ORDER_BY_DESC);
str_.append(SPACE);
EscapeSpace(myField);
str_.append(myField);
query_->OrderBy(field, false);
}
return *this;
}
DataQuery& DataQuery::Limit(const int number, const int offset)
{
if (number < 0 || offset < 0) {
ZLOGE("Invalid number param");
return *this;
}
str_.append(SPACE);
str_.append(LIMIT);
str_.append(SPACE);
str_.append(BasicToString(number));
str_.append(SPACE);
str_.append(BasicToString(offset));
query_->Limit(number, offset);
return *this;
}
DataQuery& DataQuery::BeginGroup()
{
str_.append(SPACE);
str_.append(BEGIN_GROUP);
query_->BeginGroup();
return *this;
}
DataQuery& DataQuery::EndGroup()
{
str_.append(SPACE);
str_.append(END_GROUP);
query_->EndGroup();
return *this;
}
DataQuery& DataQuery::KeyPrefix(const std::string &prefix)
{
std::string myPrefix = prefix;
if (ValidateField(myPrefix)) {
str_.append(SPACE);
str_.append(KEY_PREFIX);
str_.append(SPACE);
EscapeSpace(myPrefix);
str_.append(myPrefix);
prefix_ = prefix;
hasPrefix_ = true;
}
return *this;
}
DataQuery& DataQuery::DeviceId(const std::string &deviceId)
{
std::string device = deviceId;
if (ValidateField(device)) {
std::string start;
start.append(SPACE);
start.append(DEVICE_ID);
start.append(SPACE);
EscapeSpace(device);
start.append(device);
str_ = start + str_; // start with diveceId
deviceId_ = deviceId;
}
return *this;
}
DataQuery& DataQuery::SetSuggestIndex(const std::string &index)
{
std::string suggestIndex = index;
if (ValidateField(suggestIndex)) {
str_.append(SPACE);
str_.append(SUGGEST_INDEX);
str_.append(SPACE);
EscapeSpace(suggestIndex);
str_.append(suggestIndex);
query_->SuggestIndex(index);
}
return *this;
}
DataQuery& DataQuery::InKeys(const std::vector<std::string> &keys)
{
if (keys.empty()) {
ZLOGE("Invalid number param");
return *this;
}
if (hasKeys_) {
ZLOGE("cannot set inkeys more than once");
return *this;
}
hasKeys_ = true;
str_.append(SPACE);
str_.append(IN_KEYS);
str_.append(SPACE);
str_.append(START_IN);
str_.append(SPACE);
for (std::string key : keys) {
if (ValidateField(key)) {
EscapeSpace(key);
str_.append(key);
str_.append(SPACE);
}
}
str_.append(END_IN);
keys_ = keys;
return *this;
}
std::string DataQuery::ToString() const
{
if (str_.length() > MAX_QUERY_LENGTH) {
ZLOGE("Query is too long");
return std::string();
}
std::string str(str_.begin(), str_.end());
return str;
}
template<typename T>
void DataQuery::AppendCommon(const std::string &keyword, const std::string &fieldType,
std::string &field, const T &value)
{
str_.append(SPACE);
str_.append(keyword);
str_.append(SPACE);
str_.append(fieldType);
str_.append(SPACE);
EscapeSpace(field);
str_.append(field);
str_.append(SPACE);
str_.append(BasicToString(value));
}
void DataQuery::AppendCommonString(const std::string &keyword, const std::string &fieldType,
std::string &field, std::string &value)
{
str_.append(SPACE);
str_.append(keyword);
str_.append(SPACE);
str_.append(fieldType);
str_.append(SPACE);
EscapeSpace(field);
str_.append(field);
str_.append(SPACE);
EscapeSpace(value);
str_.append(value);
}
void DataQuery::AppendCommonBoolean(const std::string &keyword, const std::string &fieldType,
std::string &field, const bool &value)
{
str_.append(SPACE);
str_.append(keyword);
str_.append(SPACE);
str_.append(fieldType);
str_.append(SPACE);
EscapeSpace(field);
str_.append(field);
str_.append(SPACE);
if (value) {
str_.append(VALUE_TRUE);
} else {
str_.append(VALUE_FALSE);
}
}
void DataQuery::AppendCommonString(const std::string &keyword, std::string &field, std::string &value)
{
str_.append(SPACE);
str_.append(keyword);
str_.append(SPACE);
EscapeSpace(field);
str_.append(field);
str_.append(SPACE);
EscapeSpace(value);
str_.append(value);
}
template<typename T>
void DataQuery::AppendCommonList(const std::string &keyword, const std::string &fieldType,
std::string &field, const std::vector<T> &valueList)
{
str_.append(SPACE);
str_.append(keyword);
str_.append(SPACE);
str_.append(fieldType);
str_.append(SPACE);
EscapeSpace(field);
str_.append(field);
str_.append(SPACE);
str_.append(START_IN);
str_.append(SPACE);
for (T object : valueList) {
str_.append(BasicToString(object));
str_.append(SPACE);
}
str_.append(END_IN);
}
void DataQuery::AppendCommonListString(const std::string &keyword, const std::string &fieldType,
std::string &field, std::vector<std::string> &valueList)
{
str_.append(SPACE);
str_.append(keyword);
str_.append(SPACE);
str_.append(fieldType);
str_.append(SPACE);
EscapeSpace(field);
str_.append(field);
str_.append(SPACE);
str_.append(START_IN);
str_.append(SPACE);
for (std::string str : valueList) {
EscapeSpace(str);
str_.append(str);
str_.append(SPACE);
}
str_.append(END_IN);
}
void DataQuery::EscapeSpace(std::string &input)
{
if (input.length() == 0) {
input = EMPTY_STRING;
}
size_t index = 0; // search from the beginning of the string
while (true) {
index = input.find(DataQuery::SPECIAL, index);
if (index == std::string::npos) {
break;
}
input.replace(index, 1, DataQuery::SPECIAL_ESCAPE); // 1 char to be replaced
index += 3; // replaced with 3 chars, keep searching the remaining string
}
index = 0; // search from the beginning of the string
while (true) {
index = input.find(DataQuery::SPACE, index);
if (index == std::string::npos) {
break;
}
input.replace(index, 1, DataQuery::SPACE_ESCAPE); // 1 char to be replaced
index += 2; // replaced with 2 chars, keep searching the remaining string
}
}
bool DataQuery::ValidateField(const std::string &field)
{
if (field.empty() || field.find(DataQuery::SPECIAL) != std::string::npos) {
ZLOGE("invalid string argument");
return false;
}
return true;
}
template<typename T>
std::string DataQuery::BasicToString(const T &value)
{
std::ostringstream oss;
oss << value;
return oss.str();
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,53 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 DISTRIBUTEDDATAMGR_DELEGATE_MGR_CALLBACK_H
#define DISTRIBUTEDDATAMGR_DELEGATE_MGR_CALLBACK_H
#include "db_meta_callback_delegate.h"
namespace OHOS {
namespace AppDistributedKv {
class DelegateMgrCallback : public DistributedKv::DbMetaCallbackDelegate {
public:
virtual ~DelegateMgrCallback() {}
explicit DelegateMgrCallback(DistributedDB::KvStoreDelegateManager *delegate)
: delegate_(delegate) {}
bool GetKvStoreDiskSize(const std::string &storeId, uint64_t &size) override
{
if (IsDestruct()) {
return false;
}
return delegate_->GetKvStoreDiskSize(storeId, size) == DistributedDB::DBStatus::OK;
}
void GetKvStoreKeys(std::vector<DistributedKv::StoreInfo> &entries) override
{
(void) entries;
}
bool IsDestruct()
{
return delegate_ == nullptr;
}
private:
DistributedDB::KvStoreDelegateManager *delegate_ {};
};
} // namespace AppDistributedKv
} // namespace OHOS
#endif // DISTRIBUTEDDATAMGR_DELEGATE_MGR_CALLBACK_H

View File

@ -1,30 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 "device_status_change_listener_client.h"
#include <utility>
namespace OHOS::DistributedKv {
DeviceStatusChangeListenerClient::DeviceStatusChangeListenerClient(
std::shared_ptr<DeviceStatusChangeListener> listener) : listener_(std::move(listener))
{}
void DeviceStatusChangeListenerClient::OnChange(const DeviceInfo &results, const DeviceChangeType &type)
{
if (listener_ != nullptr) {
listener_->OnDeviceChanged(results, type);
}
}
} // namespace OHOS::DistributedKv

View File

@ -1,32 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 DEV_DEVICE_STATUS_CHANGE_LISTENER_IMPL_H
#define DEV_DEVICE_STATUS_CHANGE_LISTENER_IMPL_H
#include "idevice_status_change_listener.h"
#include "device_status_change_listener.h"
namespace OHOS::DistributedKv {
class DeviceStatusChangeListenerClient : public DeviceStatusChangeListenerStub {
public:
explicit DeviceStatusChangeListenerClient(std::shared_ptr<DeviceStatusChangeListener> listener);
void OnChange(const DeviceInfo &results, const DeviceChangeType &type) override;
~DeviceStatusChangeListenerClient() {}
private:
std::shared_ptr<DeviceStatusChangeListener> listener_;
};
}
#endif // DEV_DEVICE_STATUS_CHANGE_LISTENER_IMPL_H

View File

@ -1,331 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "DistributedKvDataManager"
#include "distributed_kv_data_manager.h"
#include "communication_provider.h"
#include "constant.h"
#include "dds_trace.h"
#include "device_status_change_listener_client.h"
#include "ikvstore_data_service.h"
#include "kvstore_service_death_notifier.h"
#include "log_print.h"
#include "refbase.h"
#include "single_kvstore_client.h"
#include "store_manager.h"
namespace OHOS {
namespace DistributedKv {
using namespace OHOS::DistributedDataDfx;
DistributedKvDataManager::DistributedKvDataManager()
{}
DistributedKvDataManager::~DistributedKvDataManager()
{}
Status DistributedKvDataManager::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
std::shared_ptr<SingleKvStore> &singleKvStore)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::API_PERFORMANCE_TRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
singleKvStore = nullptr;
std::string storeIdTmp = Constant::TrimCopy<std::string>(storeId.storeId);
if (storeIdTmp.size() == 0 || storeIdTmp.size() > Constant::MAX_STORE_ID_LENGTH) {
ZLOGE("invalid storeId.");
return Status::INVALID_ARGUMENT;
}
KvStoreServiceDeathNotifier::SetAppId(appId);
if (!options.baseDir.empty()) {
Status status = Status::INVALID_ARGUMENT;
singleKvStore = StoreManager::GetInstance().GetKVStore(appId, storeId, options, status);
return status;
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
Status status = Status::SERVER_UNAVAILABLE;
if (kvDataServiceProxy == nullptr) {
ZLOGE("proxy is nullptr.");
return status;
}
ZLOGD("call proxy.");
sptr<ISingleKvStore> proxyTmp;
status = kvDataServiceProxy->GetSingleKvStore(options, appId, storeId,
[&](sptr<ISingleKvStore> proxy) { proxyTmp = std::move(proxy); });
if (status == Status::RECOVER_SUCCESS) {
ZLOGE("proxy recover success: %d", static_cast<int>(status));
singleKvStore = std::make_shared<SingleKvStoreClient>(std::move(proxyTmp), storeIdTmp);
return status;
}
if (status != Status::SUCCESS) {
ZLOGE("proxy return error: %d", static_cast<int>(status));
return status;
}
if (proxyTmp == nullptr) {
ZLOGE("proxy return nullptr.");
return status;
}
singleKvStore = std::make_shared<SingleKvStoreClient>(std::move(proxyTmp), storeIdTmp);
return status;
}
Status DistributedKvDataManager::GetAllKvStoreId(const AppId &appId, std::vector<StoreId> &storeIds)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
KvStoreServiceDeathNotifier::SetAppId(appId);
auto status = StoreManager::GetInstance().GetStoreIds(appId, storeIds);
if (status == Status::SUCCESS) {
return status;
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy == nullptr) {
ZLOGE("proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
kvDataServiceProxy->GetAllKvStoreId(appId, [&status, &storeIds](auto statusTmp, auto &ids) {
status = statusTmp;
storeIds = std::move(ids);
});
return status;
}
Status DistributedKvDataManager::CloseKvStore(const AppId &appId, const StoreId &storeId)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
KvStoreServiceDeathNotifier::SetAppId(appId);
std::string storeIdTmp = Constant::TrimCopy<std::string>(storeId.storeId);
if (storeIdTmp.size() == 0 || storeIdTmp.size() > Constant::MAX_STORE_ID_LENGTH) {
ZLOGE("invalid storeId.");
return Status::INVALID_ARGUMENT;
}
auto status = StoreManager::GetInstance().CloseKVStore(appId, storeId);
if (status == SUCCESS) {
return status;
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy != nullptr) {
return kvDataServiceProxy->CloseKvStore(appId, storeId);
}
ZLOGE("proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status DistributedKvDataManager::CloseKvStore(const AppId &appId, std::shared_ptr<SingleKvStore> &kvStorePtr)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
if (kvStorePtr == nullptr) {
ZLOGE("kvStorePtr is nullptr.");
return Status::INVALID_ARGUMENT;
}
KvStoreServiceDeathNotifier::SetAppId(appId);
StoreId storeId = kvStorePtr->GetStoreId();
kvStorePtr = nullptr;
auto status = StoreManager::GetInstance().CloseKVStore(appId, storeId);
if (status == SUCCESS) {
return status;
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy != nullptr) {
return kvDataServiceProxy->CloseKvStore(appId, storeId);
}
ZLOGE("proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status DistributedKvDataManager::CloseAllKvStore(const AppId &appId)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
KvStoreServiceDeathNotifier::SetAppId(appId);
auto status = StoreManager::GetInstance().CloseAllKVStore(appId);
Status remote = SERVER_UNAVAILABLE;
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy != nullptr) {
remote = kvDataServiceProxy->CloseAllKvStore(appId);
}
if (status != SUCCESS && status != STORE_NOT_OPEN) {
return status;
}
if (remote != SUCCESS && remote != STORE_NOT_OPEN) {
return remote;
}
if (status == STORE_NOT_OPEN && remote == STORE_NOT_OPEN) {
return STORE_NOT_OPEN;
}
return SUCCESS;
}
Status DistributedKvDataManager::DeleteKvStore(const AppId &appId, const StoreId &storeId, const std::string &path)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
std::string storeIdTmp = Constant::TrimCopy<std::string>(storeId.storeId);
if (storeIdTmp.size() == 0 || storeIdTmp.size() > Constant::MAX_STORE_ID_LENGTH) {
ZLOGE("invalid storeId.");
return Status::INVALID_ARGUMENT;
}
KvStoreServiceDeathNotifier::SetAppId(appId);
if (!path.empty()) {
return StoreManager::GetInstance().Delete(appId, storeId, path);
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy != nullptr) {
return kvDataServiceProxy->DeleteKvStore(appId, storeId);
}
ZLOGE("proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status DistributedKvDataManager::DeleteAllKvStore(const AppId &appId, const std::string &path)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
KvStoreServiceDeathNotifier::SetAppId(appId);
if (!path.empty()) {
std::vector<StoreId> storeIds;
Status status = GetAllKvStoreId(appId, storeIds);
if (status != SUCCESS) {
return status;
}
for (auto &storeId : storeIds) {
status = StoreManager::GetInstance().Delete(appId, storeId, path);
if (status != SUCCESS) {
return status;
}
}
return SUCCESS;
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy != nullptr) {
return kvDataServiceProxy->DeleteAllKvStore(appId);
}
ZLOGE("proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
void DistributedKvDataManager::RegisterKvStoreServiceDeathRecipient(
std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipient)
{
ZLOGD("begin");
if (kvStoreDeathRecipient == nullptr) {
ZLOGW("Register KvStoreService Death Recipient input is null.");
return;
}
KvStoreServiceDeathNotifier::AddServiceDeathWatcher(kvStoreDeathRecipient);
}
void DistributedKvDataManager::UnRegisterKvStoreServiceDeathRecipient(
std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipient)
{
ZLOGD("begin");
if (kvStoreDeathRecipient == nullptr) {
ZLOGW("UnRegister KvStoreService Death Recipient input is null.");
return;
}
KvStoreServiceDeathNotifier::RemoveServiceDeathWatcher(kvStoreDeathRecipient);
}
Status DistributedKvDataManager::GetLocalDevice(DeviceInfo &localDevice)
{
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy == nullptr) {
ZLOGE("proxy is nullptr.");
return Status::ERROR;
}
return kvDataServiceProxy->GetLocalDevice(localDevice);
}
Status DistributedKvDataManager::GetDeviceList(std::vector<DeviceInfo> &deviceInfoList, DeviceFilterStrategy strategy)
{
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy == nullptr) {
ZLOGE("proxy is nullptr.");
return Status::ERROR;
}
return kvDataServiceProxy->GetRemoteDevices(deviceInfoList, strategy);
}
static std::map<DeviceStatusChangeListener *, sptr<IDeviceStatusChangeListener>> deviceObservers_;
static std::mutex deviceObserversMapMutex_;
Status DistributedKvDataManager::StartWatchDeviceChange(std::shared_ptr<DeviceStatusChangeListener> observer)
{
sptr<DeviceStatusChangeListenerClient> ipcObserver = new(std::nothrow) DeviceStatusChangeListenerClient(observer);
if (ipcObserver == nullptr) {
ZLOGW("new DeviceStatusChangeListenerClient failed");
return Status::ERROR;
}
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy == nullptr) {
ZLOGE("proxy is nullptr.");
return Status::ERROR;
}
Status status = kvDataServiceProxy->StartWatchDeviceChange(ipcObserver, observer->GetFilterStrategy());
if (status == Status::SUCCESS) {
{
std::lock_guard<std::mutex> lck(deviceObserversMapMutex_);
deviceObservers_.insert({observer.get(), ipcObserver});
}
return Status::SUCCESS;
}
ZLOGE("watch failed.");
return Status::ERROR;
}
Status DistributedKvDataManager::StopWatchDeviceChange(std::shared_ptr<DeviceStatusChangeListener> observer)
{
sptr<IKvStoreDataService> kvDataServiceProxy = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (kvDataServiceProxy == nullptr) {
ZLOGE("proxy is nullptr.");
return Status::ERROR;
}
std::lock_guard<std::mutex> lck(deviceObserversMapMutex_);
auto it = deviceObservers_.find(observer.get());
if (it == deviceObservers_.end()) {
ZLOGW(" not start watch device change.");
return Status::ERROR;
}
Status status = kvDataServiceProxy->StopWatchDeviceChange(it->second);
if (status == Status::SUCCESS) {
deviceObservers_.erase(it->first);
} else {
ZLOGW("stop watch failed code=%d.", static_cast<int>(status));
}
return status;
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,77 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "DevChangeStatusListener"
#include "idevice_status_change_listener.h"
#include <ipc_skeleton.h>
#include "log_print.h"
#include "itypes_util.h"
namespace OHOS {
namespace DistributedKv {
enum {
ONCHANGE,
};
DeviceStatusChangeListenerProxy::DeviceStatusChangeListenerProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<IDeviceStatusChangeListener>(impl)
{}
void DeviceStatusChangeListenerProxy::OnChange(const DeviceInfo &results, const DeviceChangeType &type)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(DeviceStatusChangeListenerProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return;
}
if (!data.WriteInt32(static_cast<int>(type)) || !ITypesUtil::Marshalling(results, data)) {
ZLOGW("SendRequest write parcel type failed.");
return;
}
MessageOption mo { MessageOption::TF_ASYNC };
int error = Remote()->SendRequest(ONCHANGE, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest failed, error %d", error);
}
}
int DeviceStatusChangeListenerStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option)
{
ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid());
std::u16string descriptor = DeviceStatusChangeListenerStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
ZLOGE("local descriptor is not equal to remote");
return -1;
}
switch (code) {
case ONCHANGE: {
DeviceChangeType type = static_cast<DeviceChangeType>(data.ReadInt32());
DeviceInfo deviceInfo;
if (ITypesUtil::Unmarshal(data, deviceInfo)) {
OnChange(deviceInfo, type);
} else {
ZLOGW("device info is null");
}
return 0;
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,24 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 "ikvstore_client_death_observer.h"
namespace OHOS {
namespace DistributedKv {
KvStoreClientDeathObserverProxy::KvStoreClientDeathObserverProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<IKvStoreClientDeathObserver>(impl)
{}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,635 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "KvStoreDataServiceProxy"
#include "ikvstore_data_service.h"
#include <ipc_skeleton.h>
#include "constant.h"
#include "irdb_service.h"
#include "rdb_service_proxy.h"
#include "itypes_util.h"
#include "message_parcel.h"
#include "types.h"
#include "log_print.h"
namespace OHOS {
namespace DistributedKv {
constexpr KvStoreDataServiceStub::RequestHandler KvStoreDataServiceStub::HANDLERS[SERVICE_CMD_LAST];
KvStoreDataServiceProxy::KvStoreDataServiceProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<IKvStoreDataService>(impl)
{
ZLOGI("init data service proxy.");
}
Status KvStoreDataServiceProxy::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId,
std::function<void(sptr<ISingleKvStore>)> callback)
{
ZLOGI("%s %s", appId.appId.c_str(), storeId.storeId.c_str());
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
ZLOGW("SetMaxCapacity failed.");
return Status::IPC_ERROR;
}
// Passing a struct with an std::string field is a potential security exploit.
OptionsIpc optionsIpc;
optionsIpc.createIfMissing = options.createIfMissing;
optionsIpc.encrypt = options.encrypt;
optionsIpc.persistent = options.persistent;
optionsIpc.backup = options.backup;
optionsIpc.autoSync = options.autoSync;
optionsIpc.securityLevel = options.securityLevel;
optionsIpc.syncPolicy = options.syncPolicy;
optionsIpc.kvStoreType = options.kvStoreType;
optionsIpc.syncable = options.syncable;
std::string schemaString = options.schema;
if (!data.WriteBuffer(&optionsIpc, sizeof(OptionsIpc)) ||
!data.WriteString(appId.appId) ||
!data.WriteString(storeId.storeId) ||
!data.WriteString(schemaString)) {
ZLOGW("failed to write parcel.");
return Status::IPC_ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GETSINGLEKVSTORE, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
return Status::IPC_ERROR;
}
Status status = static_cast<Status>(reply.ReadInt32());
if (status == Status::SUCCESS) {
sptr<IRemoteObject> remote = reply.ReadRemoteObject();
if (remote != nullptr) {
sptr<ISingleKvStore> kvstoreImplProxy = iface_cast<ISingleKvStore>(remote);
callback(std::move(kvstoreImplProxy));
}
} else {
callback(nullptr);
}
return status;
}
void KvStoreDataServiceProxy::GetAllKvStoreId(const AppId &appId,
std::function<void(Status, std::vector<StoreId> &)> callback)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return;
}
if (!data.WriteString(appId.appId)) {
ZLOGW("failed to write parcel.");
return;
}
std::vector<StoreId> storeIds;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GETALLKVSTOREID, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
callback(Status::IPC_ERROR, storeIds);
return;
}
std::vector<std::string> stores;
reply.ReadStringVector(&stores);
for (const auto &id: stores) {
storeIds.push_back({id});
}
Status status = static_cast<Status>(reply.ReadInt32());
callback(status, storeIds);
}
Status KvStoreDataServiceProxy::CloseKvStore(const AppId &appId, const StoreId &storeId)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteString(appId.appId) ||
!data.WriteString(storeId.storeId)) {
ZLOGW("failed to write parcel.");
return Status::IPC_ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(CLOSEKVSTORE, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
/* close all opened kvstore */
Status KvStoreDataServiceProxy::CloseAllKvStore(const AppId &appId)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteString(appId.appId)) {
ZLOGW("failed to write parcel.");
return Status::IPC_ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(CLOSEALLKVSTORE, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
Status KvStoreDataServiceProxy::DeleteKvStore(const AppId &appId, const StoreId &storeId)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteString(appId.appId) ||
!data.WriteString(storeId.storeId)) {
ZLOGW("failed to write parcel.");
return Status::IPC_ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(DELETEKVSTORE, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
/* delete all kv store */
Status KvStoreDataServiceProxy::DeleteAllKvStore(const AppId &appId)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteString(appId.appId)) {
ZLOGW("failed to write parcel.");
return Status::IPC_ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(DELETEALLKVSTORE, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
Status KvStoreDataServiceProxy::RegisterClientDeathObserver(const AppId &appId, sptr<IRemoteObject> observer)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteString(appId.appId)) {
ZLOGW("failed to write string.");
return Status::IPC_ERROR;
}
if (observer != nullptr) {
if (!data.WriteRemoteObject(observer)) {
ZLOGW("failed to write parcel.");
return Status::IPC_ERROR;
}
} else {
return Status::INVALID_ARGUMENT;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(REGISTERCLIENTDEATHOBSERVER, data, reply, mo);
if (error != 0) {
ZLOGW("failed during IPC. errCode %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
Status KvStoreDataServiceProxy::GetLocalDevice(OHOS::DistributedKv::DeviceInfo &device)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GETLOCALDEVICE, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d", error);
return Status::IPC_ERROR;
}
Status status = static_cast<Status>(reply.ReadInt32());
if (status == Status::SUCCESS) {
device = {reply.ReadString(), reply.ReadString(), reply.ReadString()};
}
return status;
}
Status KvStoreDataServiceProxy::GetRemoteDevices(std::vector<DeviceInfo> &deviceInfoList, DeviceFilterStrategy strategy)
{
MessageParcel data;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteInt32(static_cast<int>(strategy))) {
ZLOGW("write int failed.");
return Status::IPC_ERROR;
}
MessageParcel reply;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GETREMOTEDEVICES, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d", error);
return Status::IPC_ERROR;
}
Status status = static_cast<Status>(reply.ReadInt32());
if (status == Status::SUCCESS) {
int len = reply.ReadInt32();
for (int i = 0; i < len; i++) {
DeviceInfo deviceInfo = {
.deviceId = reply.ReadString(),
.deviceName = reply.ReadString(),
.deviceType = reply.ReadString()
};
deviceInfoList.push_back(std::move(deviceInfo));
}
}
return status;
}
Status KvStoreDataServiceProxy::StartWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer,
DeviceFilterStrategy strategy)
{
MessageParcel data;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (!data.WriteInt32(static_cast<int>(strategy))) {
ZLOGW("write int failed.");
return Status::IPC_ERROR;
}
if (observer != nullptr) {
if (!data.WriteRemoteObject(observer->AsObject().GetRefPtr())) {
return Status::IPC_ERROR;
}
} else {
return Status::INVALID_ARGUMENT;
}
MessageParcel reply;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(STARTWATCHDEVICECHANGE, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
Status KvStoreDataServiceProxy::StopWatchDeviceChange(sptr<IDeviceStatusChangeListener> observer)
{
MessageParcel data;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
if (observer != nullptr) {
if (!data.WriteRemoteObject(observer->AsObject().GetRefPtr())) {
return Status::IPC_ERROR;
}
} else {
return Status::INVALID_ARGUMENT;
}
MessageParcel reply;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(STOPWATCHDEVICECHANGE, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d", error);
return Status::IPC_ERROR;
}
return static_cast<Status>(reply.ReadInt32());
}
sptr<IRemoteObject> KvStoreDataServiceProxy::GetRdbService()
{
ZLOGI("enter");
MessageParcel data;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return nullptr;
}
MessageParcel reply;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GET_RDB_SERVICE, data, reply, mo);
if (error != 0) {
ZLOGE("SendRequest returned %{public}d", error);
return nullptr;
}
auto remoteObject = reply.ReadRemoteObject();
if (remoteObject == nullptr) {
ZLOGE("remote object is nullptr");
return nullptr;
}
return remoteObject;
}
sptr<IRemoteObject> KvStoreDataServiceProxy::GetObjectService()
{
ZLOGI("enter");
MessageParcel data;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return nullptr;
}
MessageParcel reply;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GET_OBJECT_SERVICE, data, reply, mo);
if (error != 0) {
ZLOGE("SendRequest returned %{public}d", error);
return nullptr;
}
auto remoteObject = reply.ReadRemoteObject();
if (remoteObject == nullptr) {
ZLOGE("remote object is nullptr");
return nullptr;
}
return remoteObject;
}
sptr<IRemoteObject> KvStoreDataServiceProxy::GetKVdbService()
{
ZLOGI("enter");
MessageParcel data;
if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return nullptr;
}
MessageParcel reply;
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(GET_KVDB_SERVICE, data, reply, mo);
if (error != 0) {
ZLOGE("SendRequest returned %{public}d", error);
return nullptr;
}
auto remoteObject = reply.ReadRemoteObject();
if (remoteObject == nullptr) {
ZLOGE("remote object is nullptr");
return nullptr;
}
return remoteObject;
}
int32_t KvStoreDataServiceStub::GetAllKvStoreIdOnRemote(MessageParcel &data, MessageParcel &reply)
{
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
std::vector<std::string> storeIdList;
Status statusTmp;
GetAllKvStoreId(appId, [&](Status status, std::vector<StoreId> &storeIds) {
for (const auto &id : storeIds) {
storeIdList.push_back(id.storeId);
}
statusTmp = status;
});
if (!reply.WriteStringVector(storeIdList)) {
return -1;
}
if (!reply.WriteInt32(static_cast<int>(statusTmp))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::GetRemoteDevicesOnRemote(MessageParcel &data, MessageParcel &reply)
{
std::vector<DeviceInfo> infos;
DeviceFilterStrategy strategy = static_cast<DeviceFilterStrategy>(data.ReadInt32());
Status status = GetRemoteDevices(infos, strategy);
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
if (status == Status::SUCCESS) {
if (!reply.WriteInt32(infos.size())) {
return -1;
}
for (DeviceInfo const &info : infos) {
if (!reply.WriteString(info.deviceId) || !reply.WriteString(info.deviceName) ||
!reply.WriteString(info.deviceType)) {
return -1;
}
}
}
return 0;
}
int32_t KvStoreDataServiceStub::StartWatchDeviceChangeOnRemote(MessageParcel &data, MessageParcel &reply)
{
DeviceFilterStrategy strategy = static_cast<DeviceFilterStrategy>(data.ReadInt32());
sptr<IRemoteObject> remote = data.ReadRemoteObject();
if (remote == nullptr) {
ZLOGW("observerProxy nullptr after ipc");
if (!reply.WriteInt32(static_cast<int>(Status::IPC_ERROR))) {
return -1;
}
return 0;
}
sptr<IDeviceStatusChangeListener> observerProxy = iface_cast<IDeviceStatusChangeListener>(remote);
Status status = StartWatchDeviceChange(std::move(observerProxy), strategy);
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::StopWatchDeviceChangeOnRemote(MessageParcel &data, MessageParcel &reply)
{
sptr<IRemoteObject> remote = data.ReadRemoteObject();
if (remote == nullptr) {
ZLOGW("observerProxy nullptr after ipc");
if (!reply.WriteInt32(static_cast<int>(Status::IPC_ERROR))) {
return -1;
}
return 0;
}
sptr<IDeviceStatusChangeListener> observerProxy = iface_cast<IDeviceStatusChangeListener>(remote);
Status status = StopWatchDeviceChange(std::move(observerProxy));
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::GetSingleKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
{
const OptionsIpc *optionIpcPtr = reinterpret_cast<const OptionsIpc *>(data.ReadBuffer(sizeof(OptionsIpc)));
if (optionIpcPtr == nullptr) {
ZLOGW("optionPtr is nullptr");
if (!reply.WriteInt32(static_cast<int>(Status::INVALID_ARGUMENT))) {
return -1;
}
return 0;
}
OptionsIpc optionsIpc = *optionIpcPtr;
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
StoreId storeId = { Constant::TrimCopy<std::string>(data.ReadString())};
Options options;
options.createIfMissing = optionsIpc.createIfMissing;
options.encrypt = optionsIpc.encrypt;
options.persistent = optionsIpc.persistent;
options.backup = optionsIpc.backup;
options.autoSync = optionsIpc.autoSync;
options.securityLevel = optionsIpc.securityLevel;
options.syncPolicy = optionsIpc.syncPolicy;
options.kvStoreType = optionsIpc.kvStoreType;
options.syncable = optionsIpc.syncable;
options.schema = data.ReadString();
sptr<ISingleKvStore> proxyTmp;
Status status = GetSingleKvStore(options, appId, storeId,
[&](sptr<ISingleKvStore> proxy) { proxyTmp = std::move(proxy); });
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
if (status == Status::SUCCESS && proxyTmp != nullptr) {
if (!reply.WriteRemoteObject(proxyTmp->AsObject().GetRefPtr())) {
return -1;
}
}
return 0;
}
int32_t KvStoreDataServiceStub::CloseKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
{
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
StoreId storeId = { Constant::TrimCopy<std::string>(data.ReadString())};
Status status = CloseKvStore(appId, storeId);
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::CloseAllKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
{
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
Status status = CloseAllKvStore(appId);
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::DeleteKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
{
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
StoreId storeId = { Constant::TrimCopy<std::string>(data.ReadString())};
Status status = DeleteKvStore(appId, storeId);
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::DeleteAllKvStoreOnRemote(MessageParcel &data, MessageParcel &reply)
{
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
Status status = DeleteAllKvStore(appId);
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::RegisterClientDeathObserverOnRemote(MessageParcel &data, MessageParcel &reply)
{
AppId appId = { Constant::TrimCopy<std::string>(data.ReadString())};
sptr<IRemoteObject> kvStoreClientDeathObserverProxy = data.ReadRemoteObject();
if (kvStoreClientDeathObserverProxy == nullptr) {
return -1;
}
Status status = RegisterClientDeathObserver(appId, std::move(kvStoreClientDeathObserverProxy));
if (!reply.WriteInt32(static_cast<int>(status))) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::GetLocalDeviceOnRemote(MessageParcel &data, MessageParcel &reply)
{
DeviceInfo info;
Status status = GetLocalDevice(info);
if (!reply.WriteInt32(static_cast<int>(status)) || !reply.WriteString(info.deviceId) ||
!reply.WriteString(info.deviceName) || !reply.WriteString(info.deviceType)) {
return -1;
}
return 0;
}
int32_t KvStoreDataServiceStub::GetRdbServiceOnRemote(MessageParcel &data, MessageParcel &reply)
{
reply.WriteRemoteObject(GetRdbService());
return 0;
}
int32_t KvStoreDataServiceStub::GetKVdbServiceOnRemote(MessageParcel &data, MessageParcel &reply)
{
reply.WriteRemoteObject(GetKVdbService());
return 0;
}
int32_t KvStoreDataServiceStub::GetObjectServiceOnRemote(MessageParcel &data, MessageParcel &reply)
{
reply.WriteRemoteObject(GetObjectService());
return 0;
}
int32_t KvStoreDataServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option)
{
ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid());
std::u16string descriptor = KvStoreDataServiceStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
ZLOGE("local descriptor is not equal to remote");
return -1;
}
if (code >= 0 && code < SERVICE_CMD_LAST) {
return (this->*HANDLERS[code])(data, reply);
} else {
MessageOption mo { MessageOption::TF_SYNC };
return IPCObjectStub::OnRemoteRequest(code, data, reply, mo);
}
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,223 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "KvStoreObserverProxy"
#include "ikvstore_observer.h"
#include <chrono>
#include <cinttypes>
#include <ipc_skeleton.h>
#include "constant.h"
#include "log_print.h"
#include "message_parcel.h"
namespace OHOS {
namespace DistributedKv {
using namespace std::chrono;
enum {
ONCHANGE,
};
KvStoreObserverProxy::KvStoreObserverProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<IKvStoreObserver>(impl)
{}
int64_t GetBufferSize(const std::vector<Entry> &entries)
{
int64_t bufferSize = 0;
for (const auto &item : entries) {
bufferSize += item.key.RawSize() + item.value.RawSize();
}
return bufferSize;
}
bool WriteEntryToParcelByBuf(MessageParcel &data, const int64_t &bufferSize, const std::vector<Entry> &list)
{
std::unique_ptr<uint8_t, void(*)(uint8_t *)> buffer(new uint8_t[bufferSize], [](uint8_t *ptr) { delete[] ptr; });
if (buffer == nullptr) {
ZLOGE("buffer is null");
return false;
}
int bufLeftSize = bufferSize;
uint8_t *cursor = buffer.get();
for (const auto &item : list) {
if (!item.key.WriteToBuffer(cursor, bufLeftSize) ||
!item.value.WriteToBuffer(cursor, bufLeftSize)) {
ZLOGE("write item to buff failed");
return false;
}
}
if (!data.WriteRawData(buffer.get(), bufferSize)) {
ZLOGE("bigDataOnchange write RawData from buff failed");
return false;
}
return true;
}
bool WriteListToParcelByBuf(MessageParcel &data, const int64_t &bufferSize, const std::vector<Entry> &list)
{
if (!data.WriteInt32(list.size()) ||
!data.WriteInt32(bufferSize)) {
ZLOGE("write entriesLen or bufferSize fails");
return false;
}
if (bufferSize == 0) {
return true;
}
if (!WriteEntryToParcelByBuf(data, bufferSize, list)) {
ZLOGE("bigDataOnchange write RawData to parcel failed");
return false;
}
return true;
}
void KvStoreObserverProxy::OnChange(const ChangeNotification &changeNotification)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreObserverProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return;
}
int64_t insertBufferSize = GetBufferSize(changeNotification.GetInsertEntries());
int64_t updateBufferSize = GetBufferSize(changeNotification.GetUpdateEntries());
int64_t deleteBufferSize = GetBufferSize(changeNotification.GetDeleteEntries());
int64_t totalBufferSize = insertBufferSize + updateBufferSize + deleteBufferSize + sizeof(bool);
if (!data.WriteInt32(totalBufferSize)) {
ZLOGE("Write ChangeNotification buffer size to parcel failed.");
return;
}
ZLOGD("I(%" PRId64") U(%" PRId64") D(%" PRId64") T(%" PRId64")",
insertBufferSize, updateBufferSize, deleteBufferSize, totalBufferSize);
if (totalBufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
if (!data.WriteParcelable(&changeNotification)) {
ZLOGW("Write ChangeNotification to parcel failed.");
return;
}
} else {
if (!WriteListToParcelByBuf(data, insertBufferSize, changeNotification.GetInsertEntries()) ||
!WriteListToParcelByBuf(data, updateBufferSize, changeNotification.GetUpdateEntries()) ||
!WriteListToParcelByBuf(data, deleteBufferSize, changeNotification.GetDeleteEntries()) ||
!data.WriteString(changeNotification.GetDeviceId()) ||
!data.WriteBool(changeNotification.IsClear())) {
ZLOGE("WriteChangeList to Parcel by buffer failed");
return;
}
}
MessageOption mo { MessageOption::TF_WAIT_TIME };
int error = Remote()->SendRequest(ONCHANGE, data, reply, mo);
if (error != 0) {
ZLOGE("SendRequest failed, error %d", error);
}
}
bool ReadFromBuff(MessageParcel &data, const int &len, const int &bufferSize, std::vector<Entry> &entries)
{
const uint8_t *buffer = reinterpret_cast<const uint8_t *>(data.ReadRawData(bufferSize));
if (buffer == nullptr) {
ZLOGE("new buffer failed");
return false;
}
int bufferLeftSize = bufferSize;
const uint8_t *cursor = buffer;
Entry entry;
for (int i = 0; i < len; i++) {
if (!entry.key.ReadFromBuffer(cursor, bufferLeftSize) ||
!entry.value.ReadFromBuffer(cursor, bufferLeftSize)) {
ZLOGE("read key and value from buff failed");
return false;
}
entries.push_back(std::move(entry));
}
return true;
}
bool ReadListFromBuf(MessageParcel &data, std::vector<Entry> &entries)
{
int len = data.ReadInt32();
if (len < 0) {
ZLOGE("read onChangeLen failed len %d", len);
return false;
}
int bufferSize = data.ReadInt32();
if (bufferSize == 0) {
return true;
}
if (!ReadFromBuff(data, len, bufferSize, entries)) {
ZLOGE("bigDataOnchange read buff from parcel filed");
return false;
}
return true;
}
int32_t KvStoreObserverStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option)
{
ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid());
std::u16string descriptor = KvStoreObserverStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
ZLOGE("local descriptor is not equal to remote");
return -1;
}
switch (code) {
case ONCHANGE: {
const int errorResult = -1;
int totalBuffSize = data.ReadInt32();
if (totalBuffSize < Constant::SWITCH_RAW_DATA_SIZE) {
sptr<ChangeNotification> changeNotification = data.ReadParcelable<ChangeNotification>();
if (changeNotification == nullptr) {
ZLOGE("changeNotification is nullptr");
return errorResult;
}
OnChange(*changeNotification);
} else {
std::vector<Entry> insertEntries;
bool result = ReadListFromBuf(data, insertEntries);
if (!result) {
ZLOGE("read insertList from buff filed");
return errorResult;
}
std::vector<Entry> updateEntries;
result = ReadListFromBuf(data, updateEntries);
if (!result) {
ZLOGE("read updateList from buff filed");
return errorResult;
}
std::vector<Entry> deleteEntries;
result = ReadListFromBuf(data, deleteEntries);
if (!result) {
ZLOGE("read deleteList from buff filed");
return errorResult;
}
std::string deviceId = data.ReadString();
bool isClear = data.ReadBool();
ChangeNotification change(std::move(insertEntries), std::move(updateEntries), std::move(deleteEntries),
deviceId, isClear);
OnChange(change);
}
return 0;
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,367 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "KvStoreResultSetProxy"
#include "ikvstore_resultset.h"
#include <ipc_skeleton.h>
#include "constant.h"
#include "message_parcel.h"
#include "log_print.h"
#include "itypes_util.h"
namespace OHOS::DistributedKv {
enum {
GETCOUNT,
GETPOSITION,
MOVETOFIRST,
MOVETOLAST,
MOVETONEXT,
MOVETOPREVIOUS,
MOVE,
MOVETOPOSITION,
ISFIRST,
ISLAST,
ISBEFOREFIRST,
ISAFTERLAST,
GETENTRY,
};
KvStoreResultSetProxy::KvStoreResultSetProxy(const sptr<IRemoteObject> &impl) : IRemoteProxy<IKvStoreResultSet>(impl)
{}
int KvStoreResultSetProxy::GetCount()
{
return SendRequest(GETCOUNT);
}
int KvStoreResultSetProxy::GetPosition()
{
return SendRequest(GETPOSITION);
}
bool KvStoreResultSetProxy::MoveToFirst()
{
return SendRequestRetBool(MOVETOFIRST);
}
bool KvStoreResultSetProxy::MoveToLast()
{
return SendRequestRetBool(MOVETOLAST);
}
bool KvStoreResultSetProxy::MoveToNext()
{
return SendRequestRetBool(MOVETONEXT);
}
bool KvStoreResultSetProxy::MoveToPrevious()
{
return SendRequestRetBool(MOVETOPREVIOUS);
}
bool KvStoreResultSetProxy::Move(int offset)
{
MessageParcel data, reply;
if (!data.WriteInterfaceToken(KvStoreResultSetProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return false;
}
bool ret = data.WriteInt32(offset);
if (!ret) {
return ret;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(MOVE, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d, code=%d", error, MOVE);
return false;
}
return reply.ReadBool();
}
bool KvStoreResultSetProxy::MoveToPosition(int position)
{
MessageParcel data, reply;
if (!data.WriteInterfaceToken(KvStoreResultSetProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return false;
}
bool ret = data.WriteInt32(position);
if (!ret) {
return ret;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(MOVETOPOSITION, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d, code=%d", error, MOVETOPOSITION);
return false;
}
return reply.ReadBool();
}
bool KvStoreResultSetProxy::IsFirst()
{
return SendRequestRetBool(ISFIRST);
}
bool KvStoreResultSetProxy::IsLast()
{
return SendRequestRetBool(ISLAST);
}
bool KvStoreResultSetProxy::IsBeforeFirst()
{
return SendRequestRetBool(ISBEFOREFIRST);
}
bool KvStoreResultSetProxy::IsAfterLast()
{
return SendRequestRetBool(ISAFTERLAST);
}
Status KvStoreResultSetProxy::GetEntry(Entry &entry)
{
MessageParcel data, reply;
if (!data.WriteInterfaceToken(KvStoreResultSetProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return Status::IPC_ERROR;
}
bool ret = reply.SetMaxCapacity(Constant::MAX_IPC_CAPACITY); // 800K
if (!ret) {
ZLOGE("set max capacity failed.");
return Status::ERROR;
}
MessageOption mo { MessageOption::TF_SYNC };
ZLOGI("start");
int32_t error = Remote()->SendRequest(GETENTRY, data, reply, mo);
if (error != 0) {
ZLOGE("SendRequest failed, error is %d", error);
return Status::IPC_ERROR;
}
int32_t status = 0;
int32_t bufferSize = 0;
if (!ITypesUtil::Unmarshal(reply, status, bufferSize)) {
ZLOGE("read status or bufferSize failed");
return Status::ERROR;
}
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
if (!ITypesUtil::Unmarshal(reply, entry)) {
ZLOGE("read entry failed");
return Status::ERROR;
}
return Status::SUCCESS;
}
ZLOGI("getting large data");
if (bufferSize > static_cast<int64_t>(reply.GetRawDataCapacity())) {
ZLOGW("bufferSize %d larger than message parcel limit", bufferSize);
return Status::ERROR;
}
status = ITypesUtil::UnmarshalFromBuffer(reply, bufferSize, entry);
if (status != Status::SUCCESS) {
ZLOGE("read entry failed (%{public}d).", status);
return Status::ERROR;
}
return Status::SUCCESS;
}
int KvStoreResultSetProxy::SendRequest(uint32_t code)
{
MessageParcel data, reply;
if (!data.WriteInterfaceToken(KvStoreResultSetProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return -1;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(code, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest returned %d, code=%d", error, code);
return -1;
}
return reply.ReadInt32();
}
bool KvStoreResultSetProxy::SendRequestRetBool(uint32_t code)
{
MessageParcel data, reply;
if (!data.WriteInterfaceToken(KvStoreResultSetProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return false;
}
MessageOption mo { MessageOption::TF_SYNC };
int32_t error = Remote()->SendRequest(code, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequestRetBool returned %d, code=%d", error, code);
return false;
}
return reply.ReadBool();
}
int KvStoreResultSetStub::GetEntryOnRemote(MessageParcel &reply)
{
if (!reply.SetMaxCapacity(Constant::MAX_IPC_CAPACITY)) {
ZLOGE("set reply MessageParcel capacity failed");
return -1;
}
Entry entry;
int32_t status = GetEntry(entry);
int32_t bufferSize = entry.RawSize();
if (!ITypesUtil::Marshal(reply, status, bufferSize)) {
ZLOGE("write status or bufferSize failed.");
return -1;
}
if (bufferSize < Constant::SWITCH_RAW_DATA_SIZE) {
if (!ITypesUtil::Marshal(reply, entry)) {
ZLOGE("write entry failed.");
return -1;
}
return 0;
}
ZLOGI("getting big data");
if (bufferSize > static_cast<int64_t>(reply.GetRawDataCapacity())) {
ZLOGW("bufferSize %d larger than message parcel limit", bufferSize);
return 0;
}
status = ITypesUtil::MarshalToBuffer(entry, bufferSize, reply);
if (status != Status::SUCCESS) {
ZLOGE("write entry failed (%{public}d).", status);
return -1;
}
return 0;
}
int KvStoreResultSetStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply,
MessageOption &option)
{
ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid());
std::u16string descriptor = KvStoreResultSetStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
ZLOGE("local descriptor is not equal to remote");
return -1;
}
switch (code) {
case GETCOUNT: {
int count = GetCount();
bool ret = reply.WriteInt32(count);
if (!ret) {
ZLOGW("ResultSet service side GetCount fail.");
}
return 0;
}
case GETPOSITION: {
int position = GetPosition();
bool ret = reply.WriteInt32(position);
if (!ret) {
ZLOGW("ResultSet service side GetPosition fail.");
}
return 0;
}
case MOVETOFIRST: {
bool isFirst = MoveToFirst();
bool ret = reply.WriteBool(isFirst);
if (!ret) {
ZLOGW("ResultSet service side GetPosition fail.");
}
return 0;
}
case MOVETOLAST: {
bool isLast = MoveToLast();
bool ret = reply.WriteBool(isLast);
if (!ret) {
ZLOGW("ResultSet service side GetPosition fail.");
}
return 0;
}
case MOVETONEXT: {
bool isNext = MoveToNext();
bool ret = reply.WriteBool(isNext);
if (!ret) {
ZLOGW("ResultSet service side MoveToNext fail.");
}
return 0;
}
case MOVETOPREVIOUS: {
bool boolRet = MoveToPrevious();
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side MoveToPrevious fail.");
}
return 0;
}
case MOVE: {
uint32_t offset = data.ReadUint32();
bool boolRet = Move(offset);
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side Move fail.");
}
return 0;
}
case MOVETOPOSITION: {
uint32_t position = data.ReadUint32();
bool boolRet = MoveToPosition(position);
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side MoveToPosition fail.");
}
return 0;
}
case ISFIRST: {
bool boolRet = IsFirst();
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side IsFirst fail.");
}
return 0;
}
case ISLAST: {
bool boolRet = IsLast();
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side IsLast fail.");
}
return 0;
}
case ISBEFOREFIRST: {
bool boolRet = IsBeforeFirst();
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side IsBeforeFirst fail.");
}
return 0;
}
case ISAFTERLAST: {
bool boolRet = IsAfterLast();
bool ret = reply.WriteBool(boolRet);
if (!ret) {
ZLOGW("ResultSet service side IsAfterLast fail.");
}
return 0;
}
case GETENTRY: {
return GetEntryOnRemote(reply);
}
default: {
ZLOGW("OnRemoteRequest default %{public}u", code);
MessageOption mo { MessageOption::TF_SYNC };
return IPCObjectStub::OnRemoteRequest(code, data, reply, mo);
}
}
}
} // namespace OHOS::DistributedKv

View File

@ -1,99 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "KvStoreSyncCallbackProxy"
#include "ikvstore_sync_callback.h"
#include <chrono>
#include <ctime>
#include <ipc_skeleton.h>
#include <map>
#include "log_print.h"
#include "message_parcel.h"
#include "message_option.h"
#include "types.h"
namespace OHOS {
namespace DistributedKv {
enum {
SYNCCOMPLETED,
};
constexpr int32_t MAX_DEVICES = 4096;
KvStoreSyncCallbackProxy::KvStoreSyncCallbackProxy(const sptr<IRemoteObject> &impl)
: IRemoteProxy<IKvStoreSyncCallback>(impl)
{}
void KvStoreSyncCallbackProxy::SyncCompleted(const std::map<std::string, Status> &results, uint64_t sequenceId)
{
MessageParcel data;
MessageParcel reply;
if (!data.WriteInterfaceToken(KvStoreSyncCallbackProxy::GetDescriptor())) {
ZLOGE("write descriptor failed");
return;
}
if (!data.WriteInt32(static_cast<int>(results.size()))) {
ZLOGW("write results size error.");
return;
}
for (auto const &[k, v] : results) {
if (!data.WriteString(k) ||
!data.WriteInt32(static_cast<int>(v))) {
ZLOGW("write results error.");
return;
}
}
if (!data.WriteUint64(sequenceId)) {
ZLOGW("write label error.");
return;
}
MessageOption mo { MessageOption::TF_SYNC };
int error = Remote()->SendRequest(SYNCCOMPLETED, data, reply, mo);
if (error != 0) {
ZLOGW("SendRequest failed, error %d", error);
}
}
int32_t KvStoreSyncCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option)
{
ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid());
std::u16string descriptor = KvStoreSyncCallbackStub::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
if (descriptor != remoteDescriptor) {
ZLOGE("local descriptor is not equal to remote");
return -1;
}
switch (code) {
case SYNCCOMPLETED: {
std::map<std::string, Status> results;
int32_t size = data.ReadInt32();
if (size < 0 || size > MAX_DEVICES) {
ZLOGW("size < 0(%d)", size);
return 0;
}
for (int32_t i = 0; i < size; i++) {
results.insert(std::pair<std::string, Status>(data.ReadString(),
static_cast<Status>(data.ReadInt32())));
}
uint64_t sequenceId = data.ReadUint64();
SyncCompleted(results, sequenceId);
return 0;
}
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,436 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "ITypesUtil"
#include "itypes_util.h"
#include "iremote_object.h"
#include "autils/constant.h"
#include "log_print.h"
namespace OHOS::DistributedKv {
bool ITypesUtil::Marshal(MessageParcel &data)
{
return true;
}
bool ITypesUtil::Unmarshal(MessageParcel &data)
{
return true;
}
bool ITypesUtil::Marshalling(uint32_t input, MessageParcel &data)
{
return data.WriteUint32(input);
}
bool ITypesUtil::Unmarshalling(uint32_t &output, MessageParcel &data)
{
return data.ReadUint32(output);
}
bool ITypesUtil::Marshalling(int32_t input, MessageParcel &data)
{
return data.WriteInt32(input);
}
bool ITypesUtil::Unmarshalling(int32_t &output, MessageParcel &data)
{
return data.ReadInt32(output);
}
bool ITypesUtil::Marshalling(uint64_t input, MessageParcel &data)
{
return data.WriteUint64(input);
}
bool ITypesUtil::Unmarshalling(uint64_t &output, MessageParcel &data)
{
return data.ReadUint64(output);
}
bool ITypesUtil::Marshalling(const std::string &input, MessageParcel &data)
{
return data.WriteString(input);
}
bool ITypesUtil::Unmarshalling(std::string &output, MessageParcel &data)
{
return data.ReadString(output);
}
bool ITypesUtil::Marshalling(const std::vector<uint8_t> &input, MessageParcel &data)
{
return data.WriteUInt8Vector(input);
}
bool ITypesUtil::Unmarshalling(std::vector<uint8_t> &output, MessageParcel &data)
{
return data.ReadUInt8Vector(&output);
}
bool ITypesUtil::Marshalling(const Blob &blob, MessageParcel &data)
{
return data.WriteUInt8Vector(blob.Data());
}
bool ITypesUtil::Unmarshalling(Blob &output, MessageParcel &data)
{
std::vector<uint8_t> blob;
bool result = data.ReadUInt8Vector(&blob);
output = blob;
return result;
}
bool ITypesUtil::Marshalling(const Entry &entry, MessageParcel &data)
{
if (!Marshalling(entry.key, data)) {
return false;
}
return Marshalling(entry.value, data);
}
bool ITypesUtil::Unmarshalling(Entry &output, MessageParcel &data)
{
if (!Unmarshalling(output.key, data)) {
return false;
}
return Unmarshalling(output.value, data);
}
bool ITypesUtil::Marshalling(const DeviceInfo &entry, MessageParcel &data)
{
if (!data.WriteString(entry.deviceId)) {
return false;
}
if (!data.WriteString(entry.deviceName)) {
return false;
}
return data.WriteString(entry.deviceType);
}
bool ITypesUtil::Unmarshalling(DeviceInfo &output, MessageParcel &data)
{
if (!data.ReadString(output.deviceId)) {
return false;
}
if (!data.ReadString(output.deviceName)) {
return false;
}
return data.ReadString(output.deviceType);
}
bool ITypesUtil::Marshalling(const ChangeNotification &notification, MessageParcel &parcel)
{
if (!Marshalling(notification.GetInsertEntries(), parcel)) {
return false;
}
if (!Marshalling(notification.GetUpdateEntries(), parcel)) {
return false;
}
if (!Marshalling(notification.GetDeleteEntries(), parcel)) {
return false;
}
if (!parcel.WriteString(notification.GetDeviceId())) {
ZLOGE("WriteString deviceId_ failed.");
return false;
}
return parcel.WriteBool(notification.IsClear());
}
bool ITypesUtil::Unmarshalling(ChangeNotification &output, MessageParcel &parcel)
{
std::vector<Entry> insertEntries;
if (!Unmarshalling(insertEntries, parcel)) {
return false;
}
std::vector<Entry> updateEntries;
if (!Unmarshalling(updateEntries, parcel)) {
return false;
}
std::vector<Entry> deleteEntries;
if (!Unmarshalling(deleteEntries, parcel)) {
return false;
}
std::string deviceId;
if (!parcel.ReadString(deviceId)) {
ZLOGE("WriteString deviceId_ failed.");
return false;
}
bool isClear = false;
if (!parcel.ReadBool(isClear)) {
ZLOGE("WriteString deviceId_ failed.");
return false;
}
output = ChangeNotification(
std::move(insertEntries), std::move(updateEntries), std::move(deleteEntries), deviceId, isClear);
return true;
}
bool ITypesUtil::Marshalling(const DistributedRdb::RdbSyncerParam &param, MessageParcel &parcel)
{
if (!parcel.WriteString(param.bundleName_)) {
ZLOGE("RdbStoreParam write bundle name failed");
return false;
}
if (!parcel.WriteString(param.hapName_)) {
ZLOGE("RdbStoreParam write directory failed");
return false;
}
if (!parcel.WriteString(param.storeName_)) {
ZLOGE("RdbStoreParam write store name failed");
return false;
}
if (!parcel.WriteInt32(param.area_)) {
ZLOGE("RdbStoreParam write security level failed");
return false;
}
if (!parcel.WriteInt32(param.level_)) {
ZLOGE("RdbStoreParam write security level failed");
return false;
}
if (!parcel.WriteInt32(param.type_)) {
ZLOGE("RdbStoreParam write type failed");
return false;
}
if (!parcel.WriteBool(param.isAutoSync_)) {
ZLOGE("RdbStoreParam write auto sync failed");
return false;
}
return true;
}
bool ITypesUtil::Unmarshalling(DistributedRdb::RdbSyncerParam &param, MessageParcel &parcel)
{
if (!parcel.ReadString(param.bundleName_)) {
ZLOGE("RdbStoreParam read bundle name failed");
return false;
}
if (!parcel.ReadString(param.hapName_)) {
ZLOGE("RdbStoreParam read directory failed");
return false;
}
if (!parcel.ReadString(param.storeName_)) {
ZLOGE("RdbStoreParam read store name failed");
return false;
}
if (!parcel.ReadInt32(param.area_)) {
ZLOGE("RdbStoreParam read security level failed");
return false;
}
if (!parcel.ReadInt32(param.level_)) {
ZLOGE("RdbStoreParam read security level failed");
return false;
}
if (!parcel.ReadInt32(param.type_)) {
ZLOGE("RdbStoreParam read type failed");
return false;
}
if (!parcel.ReadBool(param.isAutoSync_)) {
ZLOGE("RdbStoreParam read auto sync failed");
return false;
}
return true;
}
bool ITypesUtil::Marshalling(const DistributedRdb::SyncOption &option, MessageParcel &parcel)
{
if (!parcel.WriteInt32(option.mode)) {
ZLOGE("SyncOption write mode failed");
return false;
}
if (!parcel.WriteBool(option.isBlock)) {
ZLOGE("SyncOption write isBlock failed");
return false;
}
return true;
}
bool ITypesUtil::Unmarshalling(DistributedRdb::SyncOption &option, MessageParcel &parcel)
{
int32_t mode;
if (!parcel.ReadInt32(mode)) {
ZLOGE("SyncOption read mode failed");
return false;
}
option.mode = static_cast<DistributedRdb::SyncMode>(mode);
if (!parcel.ReadBool(option.isBlock)) {
ZLOGE("SyncOption read isBlock failed");
return false;
}
return true;
}
bool ITypesUtil::Marshalling(const DistributedRdb::RdbPredicates &predicates, MessageParcel &parcel)
{
if (!parcel.WriteString(predicates.table_)) {
ZLOGE("predicate write table failed");
return false;
}
if (!parcel.WriteStringVector(predicates.devices_)) {
ZLOGE("predicate write devices failed");
return false;
}
if (!parcel.WriteUint32(predicates.operations_.size())) {
ZLOGE("predicate write operation size failed");
return false;
}
for (const auto &operation : predicates.operations_) {
if (!parcel.WriteInt32(operation.operator_)) {
ZLOGE("predicate write operator failed");
return false;
}
if (!parcel.WriteString(operation.field_)) {
ZLOGE("predicate write field failed");
return false;
}
if (!parcel.WriteStringVector(operation.values_)) {
ZLOGE("predicate write values failed");
return false;
}
}
return true;
}
bool ITypesUtil::Unmarshalling(DistributedRdb::RdbPredicates &predicates, MessageParcel &parcel)
{
if (!parcel.ReadString(predicates.table_)) {
ZLOGE("predicate read table failed");
return false;
}
if (!parcel.ReadStringVector(&predicates.devices_)) {
ZLOGE("predicate read devices failed");
return false;
}
uint32_t size = 0;
if (!parcel.ReadUint32(size)) {
ZLOGE("predicate read operation size failed");
return false;
}
for (uint32_t i = 0; i < size; i++) {
int32_t op;
if (!parcel.ReadInt32(op)) {
ZLOGE("predicate read operator failed");
return false;
}
DistributedRdb::RdbPredicateOperation operation;
operation.operator_ = static_cast<DistributedRdb::RdbPredicateOperator>(op);
if (!parcel.ReadString(operation.field_)) {
ZLOGE("predicate read field failed");
return false;
}
if (!parcel.ReadStringVector(&operation.values_)) {
ZLOGE("predicate read values failed");
return false;
}
predicates.operations_.push_back(std::move(operation));
}
return true;
}
bool ITypesUtil::Marshalling(const Options &input, MessageParcel &data)
{
if (!data.WriteString(input.schema)) {
ZLOGE("schema is failed");
return false;
}
if (!data.WriteString(input.hapName)) {
ZLOGE("hapName is failed");
return false;
}
std::unique_ptr<uint8_t[]> buffer = std::make_unique<uint8_t[]>(sizeof(input));
Options *target = reinterpret_cast<Options *>(buffer.get());
target->createIfMissing = input.createIfMissing;
target->encrypt = input.encrypt;
target->persistent = input.persistent;
target->backup = input.backup;
target->autoSync = input.autoSync;
target->syncable = input.syncable;
target->securityLevel = input.securityLevel;
target->area = input.area;
target->syncPolicy = input.syncPolicy;
target->kvStoreType = input.kvStoreType;
return data.WriteRawData(buffer.get(), sizeof(input));
}
bool ITypesUtil::Unmarshalling(Options &output, MessageParcel &data)
{
if (!data.ReadString(output.schema)) {
ZLOGE("read schema failed");
return false;
}
if (!data.ReadString(output.hapName)) {
ZLOGE("read hapName failed");
return false;
}
const Options *source = reinterpret_cast<const Options *>(data.ReadRawData(sizeof(output)));
if (source == nullptr) {
return false;
}
output.createIfMissing = source->createIfMissing;
output.encrypt = source->encrypt;
output.persistent = source->persistent;
output.backup = source->backup;
output.autoSync = source->autoSync;
output.securityLevel = source->securityLevel;
output.area = source->area;
output.syncPolicy = source->syncPolicy;
output.kvStoreType = source->kvStoreType;
output.syncable = source->syncable;
return true;
}
bool ITypesUtil::Marshalling(const sptr<IRemoteObject> &input, MessageParcel &data)
{
return data.WriteRemoteObject(input);
}
bool ITypesUtil::Unmarshalling(sptr<IRemoteObject> &output, MessageParcel &data)
{
output = data.ReadRemoteObject();
return true;
}
int64_t ITypesUtil::GetTotalSize(const std::vector<Entry> &entries)
{
int64_t bufferSize = 1;
for (const auto &item : entries) {
if (item.key.Size() > Constant::MAX_KEY_LENGTH || item.value.Size() > Constant::MAX_VALUE_LENGTH) {
return -bufferSize;
}
bufferSize += item.key.RawSize() + item.value.RawSize();
}
return bufferSize - 1;
}
int64_t ITypesUtil::GetTotalSize(const std::vector<Key> &entries)
{
int64_t bufferSize = 1;
for (const auto &item : entries) {
if (item.Size() > Constant::MAX_KEY_LENGTH) {
return -bufferSize;
}
bufferSize += item.RawSize();
}
return bufferSize - 1;
}
} // namespace OHOS::DistributedKv

View File

@ -1,262 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "KvUtils"
#include "kv_utils.h"
#include <endian.h>
#include "cov_util.h"
#include "log_print.h"
#include "data_query.h"
#include "kvstore_datashare_bridge.h"
namespace OHOS {
namespace DistributedKv {
using namespace DataShare;
using namespace DistributedData;
const std::string KvUtils::KEY = "key";
const std::string KvUtils::VALUE = "value";
constexpr KvUtils::QueryHandler KvUtils::HANDLERS[LAST_TYPE];
std::shared_ptr<ResultSetBridge> KvUtils::ToResultSetBridge(std::shared_ptr<KvStoreResultSet> resultSet)
{
if (resultSet == nullptr) {
ZLOGE("param error, kvResultSet nullptr");
return nullptr;
}
return std::make_shared<KvStoreDataShareBridge>(resultSet);
}
Status KvUtils::ToQuery(const DataShareAbsPredicates &predicates, DataQuery &query)
{
const auto &operations = predicates.GetOperationList();
for (const auto &oper : operations) {
if (oper.operation < 0 || oper.operation >= LAST_TYPE) {
ZLOGE("operation param error");
return Status::NOT_SUPPORT;
}
(*HANDLERS[oper.operation])(oper, query);
}
return Status::SUCCESS;
}
std::vector<Entry> KvUtils::ToEntries(const std::vector<DataShareValuesBucket> &valueBuckets)
{
std::vector<Entry> entries;
for (const auto &val : valueBuckets) {
Entry entry = ToEntry(val);
entries.push_back(entry);
}
return entries;
}
Entry KvUtils::ToEntry(const DataShareValuesBucket &valueBucket)
{
const auto &values = valueBucket.valuesMap;
if (values.empty()) {
ZLOGE("valuesMap is null");
return {};
}
Entry entry;
Status status = ToEntryData(values, KEY, entry.key);
if (status != Status::SUCCESS) {
ZLOGE("GetEntry key failed: %{public}d", status);
return {};
}
status = ToEntryData(values, VALUE, entry.value);
if (status != Status::SUCCESS) {
ZLOGE("GetEntry value failed: %{public}d", status);
return {};
}
return entry;
}
Status KvUtils::GetKeys(const DataShareAbsPredicates &predicates, std::vector<Key> &keys)
{
const auto &operations = predicates.GetOperationList();
if (operations.empty()) {
ZLOGE("operations is null");
return Status::ERROR;
}
std::vector<std::string> myKeys;
for (const auto &oper : operations) {
if (oper.operation != IN_KEY) {
ZLOGE("find operation failed");
return Status::NOT_SUPPORT;
}
std::vector<std::string> val = oper.multiParams[0];
myKeys.insert(myKeys.end(), val.begin(), val.end());
}
for (const auto &it : myKeys) {
keys.push_back(it.c_str());
}
return Status::SUCCESS;
}
Status KvUtils::ToEntryData(const std::map<std::string, DataShareValueObject> &valuesMap,
const std::string field, Blob &blob)
{
auto it = valuesMap.find(field);
if (it == valuesMap.end()) {
ZLOGE("field is not find!");
return Status::ERROR;
}
DataShareValueObjectType type = it->second.type;
std::vector<uint8_t> uData;
if (type == DataShareValueObjectType::TYPE_BLOB) {
ZLOGE("Value bucket type blob");
std::vector<uint8_t> data = it->second;
uData.push_back(KvUtils::BYTE_ARRAY);
uData.insert(uData.end(), data.begin(), data.end());
} else if (type == DataShareValueObjectType::TYPE_INT) {
ZLOGE("Value bucket type int");
int64_t data = it->second;
uint64_t data64 = htobe64(*reinterpret_cast<uint64_t*>(&data));
uint8_t *dataU8 = reinterpret_cast<uint8_t*>(&data64);
uData.push_back(KvUtils::INTEGER);
uData.insert(uData.end(), dataU8, dataU8 + sizeof(int64_t) / sizeof(uint8_t));
} else if (type == DataShareValueObjectType::TYPE_DOUBLE) {
ZLOGE("Value bucket type double");
double data = it->second;
uint64_t data64 = htobe64(*reinterpret_cast<uint64_t*>(&data));
uint8_t *dataU8 = reinterpret_cast<uint8_t*>(&data64);
uData.push_back(KvUtils::DOUBLE);
uData.insert(uData.end(), dataU8, dataU8 + sizeof(double) / sizeof(uint8_t));
} else if (type == DataShareValueObjectType::TYPE_BOOL) {
ZLOGE("Value bucket type bool");
bool data = it->second;
uData.push_back(KvUtils::BOOLEAN);
uData.push_back(static_cast<uint8_t>(data));
} else if (type == DataShareValueObjectType::TYPE_STRING) {
ZLOGE("Value bucket type string");
std::string data = it->second;
uData.push_back(KvUtils::STRING);
uData.insert(uData.end(), data.begin(), data.end());
}
blob = Blob(uData);
return Status::SUCCESS;
}
void KvUtils::NoSupport(const DataShare::OperationItem &oper, DataQuery &query)
{
ZLOGE("invalid operation:%{public}d", oper.operation);
}
void KvUtils::InKeys(const OperationItem &oper, DataQuery &query)
{
query.InKeys(oper.multiParams[0]);
}
void KvUtils::KeyPrefix(const OperationItem &oper, DataQuery &query)
{
query.KeyPrefix(oper.singleParams[0]);
}
void KvUtils::EqualTo(const OperationItem &oper, DataQuery &query)
{
Querys equal(&query, QueryType::EQUAL);
CovUtil::FillField(oper.singleParams[0], oper.singleParams[1].value, equal);
}
void KvUtils::NotEqualTo(const OperationItem &oper, DataQuery &query)
{
Querys notEqual(&query, QueryType::NOT_EQUAL);
CovUtil::FillField(oper.singleParams[0], oper.singleParams[1].value, notEqual);
}
void KvUtils::GreaterThan(const OperationItem &oper, DataQuery &query)
{
Querys greater(&query, QueryType::GREATER);
CovUtil::FillField(oper.singleParams[0], oper.singleParams[1].value, greater);
}
void KvUtils::LessThan(const OperationItem &oper, DataQuery &query)
{
Querys less(&query, QueryType::LESS);
CovUtil::FillField(oper.singleParams[0], oper.singleParams[1].value, less);
}
void KvUtils::GreaterThanOrEqualTo(const OperationItem &oper, DataQuery &query)
{
Querys greaterOrEqual(&query, QueryType::GREATER_OR_EQUAL);
CovUtil::FillField(oper.singleParams[0], oper.singleParams[1].value, greaterOrEqual);
}
void KvUtils::LessThanOrEqualTo(const OperationItem &oper, DataQuery &query)
{
Querys lessOrEqual(&query, QueryType::LESS_OR_EQUAL);
CovUtil::FillField(oper.singleParams[0], oper.singleParams[1].value, lessOrEqual);
}
void KvUtils::And(const OperationItem &oper, DataQuery &query)
{
query.And();
}
void KvUtils::Or(const OperationItem &oper, DataQuery &query)
{
query.Or();
}
void KvUtils::IsNull(const OperationItem &oper, DataQuery &query)
{
query.IsNull(oper.singleParams[0]);
}
void KvUtils::IsNotNull(const OperationItem &oper, DataQuery &query)
{
query.IsNotNull(oper.singleParams[0]);
}
void KvUtils::In(const OperationItem &oper, DataQuery &query)
{
InOrNotIn in(&query, QueryType::IN);
CovUtil::FillField(oper.singleParams[0], oper.multiParams[0].value, in);
}
void KvUtils::NotIn(const OperationItem &oper, DataQuery &query)
{
InOrNotIn notIn(&query, QueryType::NOT_IN);
CovUtil::FillField(oper.singleParams[0], oper.multiParams[0].value, notIn);
}
void KvUtils::Like(const OperationItem &oper, DataQuery &query)
{
query.Like(oper.singleParams[0], oper.singleParams[1]);
}
void KvUtils::Unlike(const OperationItem &oper, DataQuery &query)
{
query.Unlike(oper.singleParams[0], oper.singleParams[1]);
}
void KvUtils::OrderByAsc(const OperationItem &oper, DataQuery &query)
{
query.OrderByAsc(oper.singleParams[0]);
}
void KvUtils::OrderByDesc(const OperationItem &oper, DataQuery &query)
{
query.OrderByDesc(oper.singleParams[0]);
}
void KvUtils::Limit(const OperationItem &oper, DataQuery &query)
{
query.Limit(oper.singleParams[0], oper.singleParams[1]);
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,33 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "KvStoreClientDeathObserver"
#include "kvstore_client_death_observer.h"
#include "log_print.h"
namespace OHOS {
namespace DistributedKv {
KvStoreClientDeathObserver::KvStoreClientDeathObserver()
{
ZLOGI("this client death observer");
}
KvStoreClientDeathObserver::~KvStoreClientDeathObserver()
{
ZLOGI("destructor this client death observer");
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,31 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 KVSTORE_CLIENT_DEATH_OBSERVER_H
#define KVSTORE_CLIENT_DEATH_OBSERVER_H
#include "ikvstore_client_death_observer.h"
namespace OHOS {
namespace DistributedKv {
class KvStoreClientDeathObserver : public KvStoreClientDeathObserverStub {
public:
KvStoreClientDeathObserver();
virtual ~KvStoreClientDeathObserver();
};
} // namespace DistributedKv
} // namespace OHOS
#endif // KVSTORE_CLIENT_DEATH_OBSERVER_H

View File

@ -1,107 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "KvStoreDataShareBridge"
#include "constant.h"
#include "log_print.h"
#include "kvstore_datashare_bridge.h"
namespace OHOS {
namespace DistributedKv {
using namespace DataShare;
KvStoreDataShareBridge::KvStoreDataShareBridge(std::shared_ptr<KvStoreResultSet> kvResultSet)
:kvResultSet_(kvResultSet) {};
int KvStoreDataShareBridge::GetRowCount(int32_t &count)
{
count = Count();
return count == INVALID_COUNT ? E_ERROR : E_OK;
}
int KvStoreDataShareBridge::GetAllColumnNames(std::vector<std::string> &columnsName)
{
columnsName = { "key", "value" };
return E_OK;
}
bool KvStoreDataShareBridge::FillBlock(int pos, ResultSetBridge::Writer &writer)
{
if (kvResultSet_ == nullptr) {
ZLOGE("kvResultSet_ nullptr");
return false;
}
bool isMoved = kvResultSet_->MoveToPosition(pos);
if (!isMoved) {
ZLOGE("MoveToPosition failed");
return false;
}
Entry entry;
Status status = kvResultSet_->GetEntry(entry);
if (status != Status::SUCCESS) {
ZLOGE("GetEntry failed %{public}d", status);
return false;
}
int statusAlloc = writer.AllocRow();
if (statusAlloc != E_OK) {
ZLOGE("SharedBlock is full: %{public}d", statusAlloc);
return false;
}
int keyStatus = writer.Write(0, entry.key.ToString().c_str(), entry.key.Size() + 1);
if (keyStatus != E_OK) {
ZLOGE("WriteBlob key error: %{public}d", keyStatus);
return false;
}
int valueStatus = writer.Write(1, entry.value.ToString().c_str(), entry.value.Size() + 1);
if (valueStatus != E_OK) {
ZLOGE("WriteBlob value error: %{public}d", valueStatus);
return false;
}
return true;
}
int KvStoreDataShareBridge::Count()
{
if (kvResultSet_ == nullptr) {
ZLOGE("kvResultSet_ nullptr");
return INVALID_COUNT;
}
if (resultRowCount != INVALID_COUNT) {
return resultRowCount;
}
int count = kvResultSet_->GetCount();
if (count < 0) {
ZLOGE("kvResultSet count invalid: %{public}d", count);
return INVALID_COUNT;
}
resultRowCount = count;
return count;
}
bool KvStoreDataShareBridge::OnGo(int32_t start, int32_t target, ResultSetBridge::Writer &writer)
{
if ((start < 0) || (target < 0) || (start > target) || (target >= Count())) {
ZLOGE("nowRowIndex out of line: %{public}d", target);
return false;
}
for (int pos = start; pos <= target; pos++) {
bool ret = FillBlock(pos, writer);
if (!ret) {
ZLOGE("nowRowIndex out of line: %{public}d", target);
return ret;
}
}
return true;
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,43 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "KvStoreObserverClient"
#include "kvstore_observer_client.h"
#include "log_print.h"
namespace OHOS {
namespace DistributedKv {
KvStoreObserverClient::KvStoreObserverClient(std::shared_ptr<KvStoreObserver> kvStoreObserver)
: kvStoreObserver_(kvStoreObserver)
{
ZLOGI("start");
}
KvStoreObserverClient::~KvStoreObserverClient()
{
ZLOGI("end");
}
void KvStoreObserverClient::OnChange(const ChangeNotification &changeNotification)
{
ZLOGI("start");
if (kvStoreObserver_ != nullptr) {
ZLOGI("SINGLE_VERSION start");
kvStoreObserver_->OnChange(changeNotification);
}
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,43 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 KVSTORE_OBSERVER_CLIENT_H
#define KVSTORE_OBSERVER_CLIENT_H
#include <memory>
#include "change_notification.h"
#include "ikvstore_observer.h"
#include "kvstore_observer.h"
#include "refbase.h"
namespace OHOS {
namespace DistributedKv {
class KvStoreObserverClient : public KvStoreObserverStub {
public:
explicit KvStoreObserverClient(std::shared_ptr<KvStoreObserver> kvStoreObserver);
~KvStoreObserverClient();
void OnChange(const ChangeNotification &changeNotification) override;
private:
static const int MAX_TRY_COUNT = 10;
// client is responsible for free it when call UnSubscribeKvStore.
std::shared_ptr<KvStoreObserver> kvStoreObserver_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // KVSTORE_OBSERVER_CLIENT_H

View File

@ -1,87 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 KVSTORE_OBSERVER_IMPL_H
#define KVSTORE_OBSERVER_IMPL_H
#include <list>
#include "app_types.h"
#include "kv_store_observer.h"
#include "log_print.h"
namespace OHOS {
namespace AppDistributedKv {
class KvStoreObserverNbImpl : public DistributedDB::KvStoreObserver {
public:
KvStoreObserverNbImpl(AppKvStoreObserver *appKvStoreObserver, const SubscribeType &subscribeType)
{
appKvStoreObserver_ = appKvStoreObserver;
subscribeType_ = subscribeType;
}
virtual void OnChange(const DistributedDB::KvStoreChangedData &data)
{
if (appKvStoreObserver_ == nullptr) {
ZLOGE("appKvStoreObserver_ is nullptr.");
return;
}
std::list<DistributedDB::Entry> insertList = data.GetEntriesInserted();
std::list<DistributedDB::Entry> updateList = data.GetEntriesUpdated();
std::list<DistributedDB::Entry> deletedList = data.GetEntriesDeleted();
std::list<Entry> insertListTmp;
std::list<Entry> updateListTmp;
std::list<Entry> deletedListTmp;
for (const auto &entry : insertList) {
Key key(entry.key);
Value value(entry.value);
Entry tmpEntry;
tmpEntry.key = key;
tmpEntry.value = value;
insertListTmp.push_back(tmpEntry);
}
for (const auto &entry : updateList) {
Key key(entry.key);
Value value(entry.value);
Entry tmpEntry;
tmpEntry.key = key;
tmpEntry.value = value;
updateListTmp.push_back(tmpEntry);
}
for (const auto &entry : deletedList) {
Key key(entry.key);
Value value(entry.value);
Entry tmpEntry;
tmpEntry.key = key;
tmpEntry.value = value;
deletedListTmp.push_back(tmpEntry);
}
AppChangeNotification changeNotification(insertListTmp, updateListTmp, deletedListTmp, std::string(), false);
appKvStoreObserver_->OnChange(changeNotification);
}
virtual ~KvStoreObserverNbImpl()
{}
private:
AppKvStoreObserver *appKvStoreObserver_;
SubscribeType subscribeType_;
};
} // namespace AppDistributedKv
} // namespace OHOS
#endif // APP_KV_STORE_OBSERVER_H

View File

@ -1,108 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "KvStoreResultSetClient"
#include "dds_trace.h"
#include "kvstore_resultset_client.h"
namespace OHOS::DistributedKv {
using namespace OHOS::DistributedDataDfx;
KvStoreResultSetClient::KvStoreResultSetClient(sptr<IKvStoreResultSet> kvStoreProxy)
:kvStoreResultSetProxy_(kvStoreProxy)
{}
int KvStoreResultSetClient::GetCount() const
{
return kvStoreResultSetProxy_->GetCount();
}
int KvStoreResultSetClient::GetPosition() const
{
return kvStoreResultSetProxy_->GetPosition();
}
bool KvStoreResultSetClient::MoveToFirst()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->MoveToFirst();
}
bool KvStoreResultSetClient::MoveToLast()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->MoveToLast();
}
bool KvStoreResultSetClient::MoveToNext()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->MoveToNext();
}
bool KvStoreResultSetClient::MoveToPrevious()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->MoveToPrevious();
}
bool KvStoreResultSetClient::Move(int offset)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->Move(offset);
}
bool KvStoreResultSetClient::MoveToPosition(int position)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->MoveToPosition(position);
}
bool KvStoreResultSetClient::IsFirst() const
{
return kvStoreResultSetProxy_->IsFirst();
}
bool KvStoreResultSetClient::IsLast() const
{
return kvStoreResultSetProxy_->IsLast();
}
bool KvStoreResultSetClient::IsBeforeFirst() const
{
return kvStoreResultSetProxy_->IsBeforeFirst();
}
bool KvStoreResultSetClient::IsAfterLast() const
{
return kvStoreResultSetProxy_->IsAfterLast();
}
Status KvStoreResultSetClient::GetEntry(Entry &entry) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return kvStoreResultSetProxy_->GetEntry(entry);
}
Status KvStoreResultSetClient::Close()
{
return NOT_SUPPORT;
}
sptr<IKvStoreResultSet> KvStoreResultSetClient::GetKvStoreResultSetProxy() const
{
return kvStoreResultSetProxy_;
}
} // namespace OHOS::DistributedKv

View File

@ -1,63 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 DISTRIBUTEDDATAMGR_KVSTORE_RESULTSET_CLIENT_H
#define DISTRIBUTEDDATAMGR_KVSTORE_RESULTSET_CLIENT_H
#include "ikvstore_resultset.h"
#include "kvstore_result_set.h"
namespace OHOS::DistributedKv {
class KvStoreResultSetClient : public KvStoreResultSet {
public:
explicit KvStoreResultSetClient(sptr<IKvStoreResultSet> kvStoreProxy);
~KvStoreResultSetClient()
{}
int GetCount() const override;
int GetPosition() const override;
bool MoveToFirst() override;
bool MoveToLast() override;
bool MoveToNext() override;
bool MoveToPrevious() override;
bool Move(int offset) override;
bool MoveToPosition(int position) override;
bool IsFirst() const override;
bool IsLast() const override;
bool IsBeforeFirst() const override;
bool IsAfterLast() const override;
Status GetEntry(Entry &entry) const override;
Status Close() override;
sptr<IKvStoreResultSet> GetKvStoreResultSetProxy() const;
private:
sptr<IKvStoreResultSet> kvStoreResultSetProxy_;
};
} // namespace OHOS::DistributedKv
#endif // DISTRIBUTEDDATAMGR_KVSTORE_RESULTSET_CLIENT_H

View File

@ -1,155 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "KvStoreServiceDeathNotifier"
#include "kvstore_service_death_notifier.h"
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "iservice_registry.h"
#include "kvstore_client_death_observer.h"
#include "log_print.h"
#include "refbase.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace DistributedKv {
AppId KvStoreServiceDeathNotifier::appId_;
std::mutex KvStoreServiceDeathNotifier::mutex_;
std::mutex KvStoreServiceDeathNotifier::watchMutex_;
sptr<IKvStoreDataService> KvStoreServiceDeathNotifier::kvDataServiceProxy_;
sptr<KvStoreServiceDeathNotifier::ServiceDeathRecipient> KvStoreServiceDeathNotifier::deathRecipientPtr_;
sptr<IRemoteObject> KvStoreServiceDeathNotifier::clientDeathObserverPtr_;
std::set<std::shared_ptr<KvStoreDeathRecipient>> KvStoreServiceDeathNotifier::serviceDeathWatchers_;
void KvStoreServiceDeathNotifier::SetAppId(const AppId &appId)
{
std::lock_guard<decltype(mutex_)> lg(mutex_);
appId_ = appId;
}
AppId KvStoreServiceDeathNotifier::GetAppId()
{
std::lock_guard<decltype(mutex_)> lg(mutex_);
return appId_;
}
sptr<IKvStoreDataService> KvStoreServiceDeathNotifier::GetDistributedKvDataService()
{
ZLOGD("begin.");
std::lock_guard<std::mutex> lg(watchMutex_);
if (kvDataServiceProxy_ != nullptr) {
return kvDataServiceProxy_;
}
ZLOGI("create remote proxy.");
auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (samgr == nullptr) {
ZLOGE("get samgr fail.");
return nullptr;
}
auto remote = samgr->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
kvDataServiceProxy_ = iface_cast<IKvStoreDataService>(remote);
if (kvDataServiceProxy_ == nullptr) {
ZLOGE("initialize proxy failed.");
return nullptr;
}
if (deathRecipientPtr_ == nullptr) {
deathRecipientPtr_ = new (std::nothrow) ServiceDeathRecipient();
if (deathRecipientPtr_ == nullptr) {
ZLOGW("new KvStoreDeathRecipient failed");
return nullptr;
}
}
if ((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipientPtr_))) {
ZLOGE("failed to add death recipient.");
}
RegisterClientDeathObserver();
return kvDataServiceProxy_;
}
void KvStoreServiceDeathNotifier::RegisterClientDeathObserver()
{
if (kvDataServiceProxy_ == nullptr) {
return;
}
if (clientDeathObserverPtr_ == nullptr) {
clientDeathObserverPtr_ = new (std::nothrow) KvStoreClientDeathObserver();
}
if (clientDeathObserverPtr_ == nullptr) {
ZLOGW("new KvStoreClientDeathObserver failed");
return;
}
kvDataServiceProxy_->RegisterClientDeathObserver(GetAppId(), clientDeathObserverPtr_);
}
void KvStoreServiceDeathNotifier::AddServiceDeathWatcher(std::shared_ptr<KvStoreDeathRecipient> watcher)
{
std::lock_guard<std::mutex> lg(watchMutex_);
auto ret = serviceDeathWatchers_.insert(std::move(watcher));
if (ret.second) {
ZLOGI("success set size: %zu", serviceDeathWatchers_.size());
} else {
ZLOGE("failed set size: %zu", serviceDeathWatchers_.size());
}
}
void KvStoreServiceDeathNotifier::RemoveServiceDeathWatcher(std::shared_ptr<KvStoreDeathRecipient> watcher)
{
std::lock_guard<std::mutex> lg(watchMutex_);
auto it = serviceDeathWatchers_.find(std::move(watcher));
if (it != serviceDeathWatchers_.end()) {
serviceDeathWatchers_.erase(it);
ZLOGI("find & erase set size: %zu", serviceDeathWatchers_.size());
} else {
ZLOGE("no found set size: %zu", serviceDeathWatchers_.size());
}
}
void KvStoreServiceDeathNotifier::ServiceDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
{
ZLOGW("DistributedDataMgrService died.");
// Need to do this with the lock held
std::lock_guard<std::mutex> lg(watchMutex_);
kvDataServiceProxy_ = nullptr;
ZLOGI("watcher set size: %zu", serviceDeathWatchers_.size());
for (const auto &watcher : serviceDeathWatchers_) {
if (watcher == nullptr) {
ZLOGI("watcher is nullptr");
continue;
}
std::thread th = std::thread([watcher]() {
watcher->OnRemoteDied();
});
th.detach();
}
}
KvStoreServiceDeathNotifier::ServiceDeathRecipient::ServiceDeathRecipient()
{
ZLOGI("constructor.");
}
KvStoreServiceDeathNotifier::ServiceDeathRecipient::~ServiceDeathRecipient()
{
ZLOGI("destructor.");
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,67 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 KVSTORE_SERVICE_DEATH_NOTIFIER_H
#define KVSTORE_SERVICE_DEATH_NOTIFIER_H
#include <memory>
#include <set>
#include <thread>
#include "ikvstore_data_service.h"
#include "iremote_object.h"
#include "kvstore_death_recipient.h"
#include "refbase.h"
namespace OHOS {
namespace DistributedKv {
class KvStoreServiceDeathNotifier final {
public:
KvStoreServiceDeathNotifier() = delete;
~KvStoreServiceDeathNotifier() = delete;
// get DistributedKvDataService proxy object.
static sptr<IKvStoreDataService> GetDistributedKvDataService();
// temporarily used, should get in service side from binder.
static void SetAppId(const AppId &appId);
static AppId GetAppId();
// add watcher for server die msg.
static void AddServiceDeathWatcher(std::shared_ptr<KvStoreDeathRecipient> watcher);
// remove watcher for server die msg.
static void RemoveServiceDeathWatcher(std::shared_ptr<KvStoreDeathRecipient> watcher);
private:
class ServiceDeathRecipient : public IRemoteObject::DeathRecipient {
public:
ServiceDeathRecipient();
virtual ~ServiceDeathRecipient();
void OnRemoteDied(const wptr<IRemoteObject> &remote) override;
};
// add watcher for server die msg.
static void RegisterClientDeathObserver();
static AppId appId_;
// lock for kvDataServiceProxy_ and serviceDeathWatchers_.
static std::mutex watchMutex_;
static std::mutex mutex_;
static sptr<IKvStoreDataService> kvDataServiceProxy_;
static sptr<ServiceDeathRecipient> deathRecipientPtr_;
static sptr<IRemoteObject> clientDeathObserverPtr_;
// set of watchers for server die msg.
static std::set<std::shared_ptr<KvStoreDeathRecipient>> serviceDeathWatchers_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // KVSTORE_SERVICE_DEATH_NOTIFIER_H

View File

@ -1,60 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "KvStoreSyncCallbackClient"
#include "kvstore_sync_callback_client.h"
#include <cinttypes>
#include <atomic>
#include "dds_trace.h"
#include "log_print.h"
namespace OHOS {
namespace DistributedKv {
using namespace OHOS::DistributedDataDfx;
KvStoreSyncCallbackClient::~KvStoreSyncCallbackClient()
{
syncCallbackInfo_.Clear();
}
void KvStoreSyncCallbackClient::SyncCompleted(const std::map<std::string, Status> &results, uint64_t sequenceId)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
auto finded = syncCallbackInfo_.Find(sequenceId);
if (finded.first) {
finded.second->SyncCompleted(results);
DeleteSyncCallback(sequenceId);
}
}
void KvStoreSyncCallbackClient::AddSyncCallback(
const std::shared_ptr<KvStoreSyncCallback> callback, uint64_t sequenceId)
{
if (callback == nullptr) {
ZLOGE("callback is nullptr");
return;
}
auto inserted = syncCallbackInfo_.Insert(sequenceId, callback);
if (!inserted) {
ZLOGE("The sequeuceId %{public}" PRIu64 "is repeat!", sequenceId);
}
}
void KvStoreSyncCallbackClient::DeleteSyncCallback(uint64_t sequenceId)
{
syncCallbackInfo_.Erase(sequenceId);
}
} // namespace DistributedKv
} // namespace OHOS

View File

@ -1,42 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 KVSTORE_SYNC_CALLBACK_CLIENT_H
#define KVSTORE_SYNC_CALLBACK_CLIENT_H
#include <mutex>
#include "concurrent_map.h"
#include "ikvstore_sync_callback.h"
#include "kvstore_sync_callback.h"
namespace OHOS {
namespace DistributedKv {
class KvStoreSyncCallbackClient : public KvStoreSyncCallbackStub {
public:
KvStoreSyncCallbackClient() = default;
virtual ~KvStoreSyncCallbackClient();
void SyncCompleted(const std::map<std::string, Status> &results, uint64_t sequenceId) override;
void AddSyncCallback(const std::shared_ptr<KvStoreSyncCallback> callback, uint64_t sequenceId);
void DeleteSyncCallback(uint64_t sequenceId);
private:
ConcurrentMap<uint64_t, std::shared_ptr<KvStoreSyncCallback>> syncCallbackInfo_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // KVSTORE_SYNC_CALLBACK_CLIENT_H

View File

@ -1,547 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "SingleKvStoreClient"
#include "single_kvstore_client.h"
#include "constant.h"
#include "dds_trace.h"
#include "kvstore_observer_client.h"
#include "kvstore_resultset_client.h"
#include "kvstore_sync_callback_client.h"
#include "log_print.h"
#include "kvstore_utils.h"
namespace OHOS::DistributedKv {
using namespace OHOS::DistributedDataDfx;
SingleKvStoreClient::SingleKvStoreClient(sptr<ISingleKvStore> kvStoreProxy, const std::string &storeId)
: kvStoreProxy_(kvStoreProxy), storeId_(storeId), syncCallbackClient_(new KvStoreSyncCallbackClient()),
syncObserver_(std::make_shared<SyncObserver>())
{}
SingleKvStoreClient::~SingleKvStoreClient()
{
kvStoreProxy_->UnRegisterSyncCallback();
syncObserver_->Clean();
}
StoreId SingleKvStoreClient::GetStoreId() const
{
StoreId storeId;
storeId.storeId = storeId_;
return storeId;
}
Status SingleKvStoreClient::GetEntries(const Key &prefix, std::vector<Entry> &entries) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
return kvStoreProxy_->GetEntries(prefix, entries);
}
Status SingleKvStoreClient::GetEntries(const DataQuery &query, std::vector<Entry> &entries) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
ZLOGD("Cpp client GetEntries");
return kvStoreProxy_->GetEntriesWithQuery(query.ToString(), entries);
}
Status SingleKvStoreClient::GetResultSet(const Key &prefix, std::shared_ptr<KvStoreResultSet> &resultSet) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
resultSet = nullptr;
Status statusTmp = Status::SERVER_UNAVAILABLE;
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return statusTmp;
}
sptr<IKvStoreResultSet> resultSetTmp;
auto callFun = [&](Status status, sptr<IKvStoreResultSet> proxy) {
statusTmp = status;
resultSetTmp = proxy;
};
kvStoreProxy_->GetResultSet(prefix, callFun);
if (statusTmp != Status::SUCCESS) {
ZLOGE("return error: %d.", static_cast<int>(statusTmp));
return statusTmp;
}
if (resultSetTmp == nullptr) {
ZLOGE("resultSetTmp is nullptr.");
return statusTmp;
}
resultSet = std::shared_ptr<KvStoreResultSetClient>(
new KvStoreResultSetClient(resultSetTmp), [proxy = kvStoreProxy_] (auto result) {
ZLOGE("kvstore proxy ResultSet closed.");
proxy->CloseResultSet(result->GetKvStoreResultSetProxy());
});
return statusTmp;
}
Status SingleKvStoreClient::GetResultSet(const DataQuery &query,
std::shared_ptr<KvStoreResultSet> &resultSet) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
resultSet = nullptr;
Status statusTmp = Status::SERVER_UNAVAILABLE;
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return statusTmp;
}
ZLOGD("Cpp client GetResultSet");
sptr<IKvStoreResultSet> resultSetTmp;
auto callFun = [&](Status status, sptr<IKvStoreResultSet> proxy) {
statusTmp = status;
resultSetTmp = proxy;
};
kvStoreProxy_->GetResultSetWithQuery(query.ToString(), callFun);
if (statusTmp != Status::SUCCESS) {
ZLOGE("return error: %d.", static_cast<int>(statusTmp));
return statusTmp;
}
if (resultSetTmp == nullptr) {
ZLOGE("resultSetTmp is nullptr.");
return statusTmp;
}
resultSet = std::shared_ptr<KvStoreResultSetClient>(
new KvStoreResultSetClient(resultSetTmp), [proxy = kvStoreProxy_] (auto result) {
ZLOGE("kvstore proxy ResultSetwithquery closed.");
proxy->CloseResultSet(result->GetKvStoreResultSetProxy());
});
return statusTmp;
}
Status SingleKvStoreClient::CloseResultSet(std::shared_ptr<KvStoreResultSet> &resultSet)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
auto resultSetTmp = std::move(resultSet);
if (resultSetTmp == nullptr) {
ZLOGE("resultSet is nullptr.");
return Status::INVALID_ARGUMENT;
}
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
auto resultSetClient = reinterpret_cast<KvStoreResultSetClient *>(resultSetTmp.get());
return kvStoreProxy_->CloseResultSet(resultSetClient->GetKvStoreResultSetProxy());
}
Status SingleKvStoreClient::GetCount(const DataQuery &query, int &count) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
ZLOGD("Cpp client GetCount");
return kvStoreProxy_->GetCountWithQuery(query.ToString(), count);
}
Status SingleKvStoreClient::Sync(const std::vector<std::string> &devices, SyncMode mode, uint32_t delay)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::TRACE_CHAIN_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
if (devices.empty()) {
ZLOGW("deviceIds is empty.");
return Status::INVALID_ARGUMENT;
}
uint64_t sequenceId = KvStoreUtils::GenerateSequenceId();
syncCallbackClient_->AddSyncCallback(syncObserver_, sequenceId);
RegisterCallback();
return kvStoreProxy_->Sync(devices, mode, delay, sequenceId);
}
Status SingleKvStoreClient::RemoveDeviceData(const std::string &device)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
if (device.empty()) {
ZLOGW("device is empty.");
return Status::INVALID_ARGUMENT;
}
return kvStoreProxy_->RemoveDeviceData(device);
}
Status SingleKvStoreClient::Delete(const Key &key)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
ZLOGI("begin.");
std::vector<uint8_t> keyData = Constant::TrimCopy<std::vector<uint8_t>>(key.Data());
if (keyData.size() == 0 || keyData.size() > Constant::MAX_KEY_LENGTH) {
ZLOGE("invalid key.");
return Status::INVALID_ARGUMENT;
}
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
return kvStoreProxy_->Delete(key);
}
Status SingleKvStoreClient::Put(const Key &key, const Value &value)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
ZLOGI("key: %zu value: %zu.", key.Size(), value.Size());
std::vector<uint8_t> keyData = Constant::TrimCopy<std::vector<uint8_t>>(key.Data());
if (keyData.size() == 0 || keyData.size() > Constant::MAX_KEY_LENGTH ||
value.Size() > Constant::MAX_VALUE_LENGTH) {
ZLOGE("invalid key or value.");
return Status::INVALID_ARGUMENT;
}
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
return kvStoreProxy_->Put(key, value);
}
Status SingleKvStoreClient::Get(const Key &key, Value &value)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("kvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
return kvStoreProxy_->Get(key, value);
}
Status SingleKvStoreClient::SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr<KvStoreObserver> observer)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
if (observer == nullptr) {
ZLOGW("return INVALID_ARGUMENT.");
return Status::INVALID_ARGUMENT;
}
std::lock_guard<std::mutex> lck(observerMapMutex_);
// change this to map.contains() after c++20
if (registeredObservers_.count(observer.get()) == 1) {
ZLOGW("return STORE_ALREADY_SUBSCRIBE.");
return Status::STORE_ALREADY_SUBSCRIBE;
}
// remove storeId after remove SubscribeKvStore function in manager. currently reserve for convenience.
sptr<KvStoreObserverClient> ipcObserver = new (std::nothrow) KvStoreObserverClient(observer);
if (ipcObserver == nullptr) {
ZLOGW("new KvStoreObserverClient failed");
return Status::ERROR;
}
Status status = kvStoreProxy_->SubscribeKvStore(subscribeType, ipcObserver);
if (status == Status::SUCCESS) {
const auto temp = registeredObservers_.insert({observer.get(), ipcObserver});
if (!temp.second) {
ZLOGW("local insert error");
return Status::ERROR;
}
}
return status;
}
Status SingleKvStoreClient::UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr<KvStoreObserver> observer)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
if (observer == nullptr) {
ZLOGW("return INVALID_ARGUMENT.");
return Status::INVALID_ARGUMENT;
}
std::lock_guard<std::mutex> lck(observerMapMutex_);
auto it = registeredObservers_.find(observer.get());
if (it == registeredObservers_.end()) {
ZLOGW(" STORE NOT SUBSCRIBE.");
return Status::STORE_NOT_SUBSCRIBE;
}
Status status = kvStoreProxy_->UnSubscribeKvStore(subscribeType, it->second);
if (status == Status::SUCCESS) {
registeredObservers_.erase(it);
} else {
ZLOGW("single unSubscribe failed code=%d.", static_cast<int>(status));
}
return status;
}
Status SingleKvStoreClient::RegisterSyncCallback(std::shared_ptr<KvStoreSyncCallback> callback)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
ZLOGI("begin.");
if (callback == nullptr) {
ZLOGW("return INVALID_ARGUMENT.");
return Status::INVALID_ARGUMENT;
}
syncObserver_->Add(callback);
RegisterCallback();
return Status::SUCCESS;
}
Status SingleKvStoreClient::RegisterCallback()
{
if (isRegisterSyncCallback_) {
return Status::SUCCESS;
}
std::lock_guard lg(registerCallbackMutex_);
if (isRegisterSyncCallback_) {
return Status::SUCCESS;
}
auto status = kvStoreProxy_->RegisterSyncCallback(syncCallbackClient_);
if (status != Status::SUCCESS) {
ZLOGE("RegisterSyncCallback is not success.");
return status;
}
isRegisterSyncCallback_ = true;
return Status::SUCCESS;
}
Status SingleKvStoreClient::UnRegisterSyncCallback()
{
ZLOGI("begin.");
syncObserver_->Clean();
return Status::SUCCESS;
}
Status SingleKvStoreClient::PutBatch(const std::vector<Entry> &entries)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
ZLOGI("entry size: %zu", entries.size());
if (entries.size() > Constant::MAX_BATCH_SIZE) {
ZLOGE("batch size must less than 128.");
return Status::INVALID_ARGUMENT;
}
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->PutBatch(entries);
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::DeleteBatch(const std::vector<Key> &keys)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
if (keys.size() > Constant::MAX_BATCH_SIZE) {
ZLOGE("batch size must less than 128.");
return Status::INVALID_ARGUMENT;
}
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->DeleteBatch(keys);
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::StartTransaction()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->StartTransaction();
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::Commit()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->Commit();
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::Rollback()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->Rollback();
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::SetSyncParam(const KvSyncParam &syncParam)
{
KvParam input(TransferTypeToByteArray<uint32_t>(syncParam.allowedDelayMs));
KvParam output;
return Control(KvControlCmd::SET_SYNC_PARAM, input, output);
}
Status SingleKvStoreClient::GetSyncParam(KvSyncParam &syncParam)
{
KvParam inputEmpty;
KvParam output;
Status ret = Control(KvControlCmd::GET_SYNC_PARAM, inputEmpty, output);
if (ret != Status::SUCCESS) {
return ret;
}
if (output.Size() == sizeof(uint32_t)) {
syncParam.allowedDelayMs = TransferByteArrayToType<uint32_t>(output.Data());
return Status::SUCCESS;
}
return Status::ERROR;
}
Status SingleKvStoreClient::Control(KvControlCmd cmd, const KvParam &inputParam, KvParam &output)
{
ZLOGI("begin.");
if (kvStoreProxy_ != nullptr) {
sptr<KvParam> kvParam;
Status status = kvStoreProxy_->Control(cmd, inputParam, kvParam);
if ((status == Status::SUCCESS) && (kvParam != nullptr)) {
output = *kvParam;
}
return status;
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::SetCapabilityEnabled(bool enabled) const
{
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->SetCapabilityEnabled(enabled);
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::SetCapabilityRange(const std::vector<std::string> &localLabels,
const std::vector<std::string> &remoteLabels) const
{
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->SetCapabilityRange(localLabels, remoteLabels);
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::GetSecurityLevel(SecurityLevel &secLevel) const
{
if (kvStoreProxy_ != nullptr) {
return kvStoreProxy_->GetSecurityLevel(secLevel);
}
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
Status SingleKvStoreClient::Sync(const std::vector<std::string> &devices, SyncMode mode,
const DataQuery &query, std::shared_ptr<KvStoreSyncCallback> callback)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
if (devices.empty()) {
ZLOGW("deviceIds is empty.");
return Status::INVALID_ARGUMENT;
}
uint64_t sequenceId = KvStoreUtils::GenerateSequenceId();
if (callback != nullptr) {
syncCallbackClient_->AddSyncCallback(callback, sequenceId);
} else {
syncCallbackClient_->AddSyncCallback(syncObserver_, sequenceId);
}
RegisterCallback();
return kvStoreProxy_->Sync(devices, mode, query.ToString(), sequenceId);
}
Status SingleKvStoreClient::SubscribeWithQuery(const std::vector<std::string> &devices, const DataQuery &query)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
if (devices.empty()) {
ZLOGW("deviceIds is empty.");
return Status::INVALID_ARGUMENT;
}
uint64_t sequenceId = KvStoreUtils::GenerateSequenceId();
syncCallbackClient_->AddSyncCallback(syncObserver_, sequenceId);
RegisterCallback();
return kvStoreProxy_->Subscribe(devices, query.ToString(), sequenceId);
}
Status SingleKvStoreClient::UnsubscribeWithQuery(const std::vector<std::string> &deviceIds, const DataQuery &query)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), TraceSwitch::BYTRACE_ON);
if (kvStoreProxy_ == nullptr) {
ZLOGE("singleKvstore proxy is nullptr.");
return Status::SERVER_UNAVAILABLE;
}
if (deviceIds.empty()) {
ZLOGW("deviceIds is empty.");
return Status::INVALID_ARGUMENT;
}
uint64_t sequenceId = KvStoreUtils::GenerateSequenceId();
syncCallbackClient_->AddSyncCallback(syncObserver_, sequenceId);
return kvStoreProxy_->UnSubscribe(deviceIds, query.ToString(), sequenceId);
}
Status SingleKvStoreClient::Backup(const std::string &file, const std::string &baseDir)
{
(void) file;
(void) baseDir;
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return SUCCESS;
}
Status SingleKvStoreClient::Restore(const std::string &file, const std::string &baseDir)
{
(void) file;
(void) baseDir;
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return SUCCESS;
}
Status SingleKvStoreClient::DeleteBackup(const std::vector<std::string> &files, const std::string &baseDir,
std::map<std::string, DistributedKv::Status> &status)
{
(void) files;
(void) baseDir;
(void) status;
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
return SUCCESS;
}
} // namespace OHOS::DistributedKv

View File

@ -1,110 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 DISTRIBUTEDDATAMGR2_SINGLE_KVSTORE_CLIENT_H
#define DISTRIBUTEDDATAMGR2_SINGLE_KVSTORE_CLIENT_H
#include <atomic>
#include "data_query.h"
#include "ikvstore_single.h"
#include "single_kvstore.h"
#include "kvstore_sync_callback_client.h"
#include "sync_observer.h"
namespace OHOS::DistributedKv {
class SingleKvStoreClient : public SingleKvStore {
public:
explicit SingleKvStoreClient(sptr<ISingleKvStore> kvStoreProxy, const std::string &storeId);
~SingleKvStoreClient();
StoreId GetStoreId() const override;
Status GetEntries(const Key &prefix, std::vector<Entry> &entries) const override;
Status GetEntries(const DataQuery &query, std::vector<Entry> &entries) const override;
Status GetResultSet(const Key &prefix, std::shared_ptr<KvStoreResultSet> &resultSet) const override;
Status GetResultSet(const DataQuery &query, std::shared_ptr<KvStoreResultSet> &resultSet) const override;
Status CloseResultSet(std::shared_ptr<KvStoreResultSet> &resultSet) override;
Status GetCount(const DataQuery &query, int &count) const override;
Status Sync(const std::vector<std::string> &devices, SyncMode mode, uint32_t delay) override;
Status RemoveDeviceData(const std::string &device) override;
Status Delete(const Key &key) override;
Status Put(const Key &key, const Value &value) override;
Status Get(const Key &key, Value &value) override;
Status SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr<KvStoreObserver> observer) override;
Status UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr<KvStoreObserver> observer) override;
Status RegisterSyncCallback(std::shared_ptr<KvStoreSyncCallback> callback) override;
Status RegisterCallback();
Status UnRegisterSyncCallback() override;
Status PutBatch(const std::vector<Entry> &entries) override;
Status DeleteBatch(const std::vector<Key> &keys) override;
Status StartTransaction() override;
Status Commit() override;
Status Rollback() override;
Status SetSyncParam(const KvSyncParam &syncParam) override;
Status GetSyncParam(KvSyncParam &syncParam) override;
Status SetCapabilityEnabled(bool enabled) const override;
Status SetCapabilityRange(const std::vector<std::string> &localLabels,
const std::vector<std::string> &remoteLabels) const override;
Status GetSecurityLevel(SecurityLevel &secLevel) const override;
Status Sync(const std::vector<std::string> &devices, SyncMode mode, const DataQuery &query,
std::shared_ptr<KvStoreSyncCallback> syncCallback) override;
Status SubscribeWithQuery(const std::vector<std::string> &devices, const DataQuery &query) override;
Status UnsubscribeWithQuery(const std::vector<std::string> &devices, const DataQuery &query) override;
Status Backup(const std::string &file, const std::string &baseDir) override;
Status Restore(const std::string &file, const std::string &baseDir) override;
Status DeleteBackup(const std::vector<std::string> &files, const std::string &baseDir,
std::map<std::string, DistributedKv::Status> &status) override;
protected:
Status Control(KvControlCmd cmd, const KvParam &inputParam, KvParam &outputParam);
private:
sptr<ISingleKvStore> kvStoreProxy_;
std::map<KvStoreObserver *, sptr<IKvStoreObserver>> registeredObservers_;
std::mutex observerMapMutex_;
std::string storeId_;
sptr<KvStoreSyncCallbackClient> syncCallbackClient_;
std::shared_ptr<SyncObserver> syncObserver_;
bool isRegisterSyncCallback_ = false;
std::mutex registerCallbackMutex_;
};
} // namespace OHOS::DistributedKv
#endif // DISTRIBUTEDDATAMGR2_SINGLE_KVSTORE_CLIENT_H

View File

@ -1,50 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 "sync_observer.h"
namespace OHOS::DistributedKv {
SyncObserver::SyncObserver(const std::vector<std::shared_ptr<KvStoreSyncCallback>> &callbacks)
:callbacks_(callbacks)
{};
SyncObserver::SyncObserver()
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
callbacks_.clear();
}
bool SyncObserver::Add(const std::shared_ptr<KvStoreSyncCallback> callback)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
callbacks_.push_back(callback);
return true;
}
bool SyncObserver::Clean()
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
callbacks_.clear();
return true;
}
void SyncObserver::SyncCompleted(const std::map<std::string, DistributedKv::Status> &results)
{
std::lock_guard<decltype(mutex_)> lock(mutex_);
for (auto &callback : callbacks_) {
callback->SyncCompleted(results);
}
}
} // namespace OHOS::DistributedKv

View File

@ -1,44 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 DISTRIBUTEDDATAMGR_DATAMGR_SYNC_OBSERVER_H
#define DISTRIBUTEDDATAMGR_DATAMGR_SYNC_OBSERVER_H
#include <vector>
#include <memory>
#include <mutex>
#include "kvstore_sync_callback.h"
namespace OHOS::DistributedKv {
class SyncObserver : public KvStoreSyncCallback {
public:
explicit SyncObserver(const std::vector<std::shared_ptr<KvStoreSyncCallback>> &callbacks);
SyncObserver();
virtual ~SyncObserver() = default;
bool Add(const std::shared_ptr<KvStoreSyncCallback> callback);
bool Clean();
void SyncCompleted(const std::map<std::string, DistributedKv::Status> &results) override;
private:
std::recursive_mutex mutex_;
std::vector<std::shared_ptr<KvStoreSyncCallback>> callbacks_;
};
} // namespace OHOS::DistributedKv
#endif // DISTRIBUTEDDATAMGR_DATAMGR_SYNC_OBSERVER_H

View File

@ -1,213 +0,0 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# 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.
import("//build/test.gni")
module_output_path = "distributeddatamgr/distributeddatafwk"
###############################################################################
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
"../include/",
"../../../../interfaces/innerkits/distributeddata/",
# TEMP MODIFICATION FOR PMS
"../../../../services/distributeddataservice/app/include",
# for ipc_core interfaces.
"//commonlibrary/c_utils/base/include",
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include",
]
}
ohos_unittest("DistributedKvDataManagerTest") {
module_out_path = module_output_path
sources = [ "unittest/distributed_kv_data_manager_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("DistributedKvDataManagerEncryptTest") {
module_out_path = module_output_path
sources = [ "unittest/distributed_kv_data_manager_encrypt_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("LocalSubscribeStoreTest") {
module_out_path = module_output_path
sources = [ "unittest/local_subscribe_store_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("LocalSubscribeDeviceStoreTest") {
module_out_path = module_output_path
sources = [ "unittest/local_subscribe_device_store_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("SingleKvStoreClientQueryTest") {
module_out_path = module_output_path
sources = [ "unittest/single_kvstore_client_query_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("SingleKvStoreClientTest") {
module_out_path = module_output_path
sources = [ "unittest/single_kvstore_client_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("DeviceKvStoreTest") {
module_out_path = module_output_path
sources = [ "unittest/device_kvstore_test.cpp" ]
configs = [ ":module_private_config" ]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr:samgr_proxy",
]
deps = [
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
}
ohos_unittest("BlobTest") {
module_out_path = module_output_path
sources = [ "unittest/blob_test.cpp" ]
configs = [ ":module_private_config" ]
deps = [
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner",
"//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter",
"//third_party/googletest:gtest_main",
]
external_deps = [ "c_utils:utils" ]
}
###############################################################################
group("unittest") {
testonly = true
deps = []
deps += [
":BlobTest",
":DeviceKvStoreTest",
":DistributedKvDataManagerEncryptTest",
":DistributedKvDataManagerTest",
":LocalSubscribeDeviceStoreTest",
":LocalSubscribeStoreTest",
":SingleKvStoreClientQueryTest",
":SingleKvStoreClientTest",
]
}

View File

@ -1,251 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 <gtest/gtest.h>
#include <cstdint>
#include <vector>
#include "types.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
class BlobTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void BlobTest::SetUpTestCase(void)
{}
void BlobTest::TearDownTestCase(void)
{}
void BlobTest::SetUp(void)
{}
void BlobTest::TearDown(void)
{}
/**
* @tc.name: Size001
* @tc.desc: construct a Blob and check its size.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Size001, TestSize.Level0)
{
Blob blob1;
EXPECT_EQ(blob1.Size(), (size_t)0);
Blob blob2 = "1234567890";
EXPECT_EQ(blob2.Size(), (size_t)10);
Blob blob3("12345");
EXPECT_EQ(blob3.Size(), (size_t)5);
std::string strTmp = "123";
const char *chr = strTmp.c_str();
Blob blob4(chr);
EXPECT_EQ(blob4.Size(), (size_t)3);
std::vector<uint8_t> vec = {'1', '2', '3', '4'};
Blob blob5(vec);
EXPECT_EQ(blob5.Size(), (size_t)4);
const char *chr1 = strTmp.c_str();
Blob blob6(chr1, strlen(chr1));
EXPECT_EQ(blob6.Size(), (size_t)3);
}
/**
* @tc.name: Empty001
* @tc.desc: construct a Blob and check its empty.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Empty001, TestSize.Level0)
{
Blob blob1;
EXPECT_EQ(blob1.Empty(), true);
Blob blob2 = "1234567890";
EXPECT_EQ(blob2.Empty(), false);
Blob blob3("12345");
EXPECT_EQ(blob3.Empty(), false);
std::string strTmp = "123";
const char *chr = strTmp.c_str();
Blob blob4(chr);
EXPECT_EQ(blob4.Empty(), false);
std::vector<uint8_t> vec = {'1', '2', '3', '4'};
Blob blob5(vec);
EXPECT_EQ(blob5.Empty(), false);
const char *chr1 = strTmp.c_str();
Blob blob6(chr1, strlen(chr1));
EXPECT_EQ(blob6.Empty(), false);
}
/**
* @tc.name: Clear001
* @tc.desc: construct a Blob and check it clear function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Clear001, TestSize.Level0)
{
Blob blob1 = "1234567890";
blob1.Clear();
EXPECT_EQ(blob1.Empty(), true);
Blob blob2("12345");
blob2.Clear();
EXPECT_EQ(blob2.Empty(), true);
std::string strTmp = "123";
const char *chr = strTmp.c_str();
Blob blob3(chr);
blob3.Clear();
EXPECT_EQ(blob3.Empty(), true);
std::vector<uint8_t> vec = {'1', '2', '3', '4'};
Blob blob4(vec);
blob4.Clear();
EXPECT_EQ(blob4.Empty(), true);
}
/**
* @tc.name: StartsWith001
* @tc.desc: construct a Blob and check it StartsWith function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, StartsWith001, TestSize.Level0)
{
Blob blob1 = "1234567890";
Blob blob2("12345");
EXPECT_EQ(blob1.StartsWith(blob2), true);
EXPECT_EQ(blob2.StartsWith(blob1), false);
Blob blob3("234");
EXPECT_EQ(blob1.StartsWith(blob3), false);
EXPECT_EQ(blob2.StartsWith(blob3), false);
}
/**
* @tc.name: Compare001
* @tc.desc: construct a Blob and check it compare function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Compare001, TestSize.Level0)
{
Blob blob1 = "1234567890";
Blob blob2("12345");
EXPECT_EQ(blob1.Compare(blob2), 1);
EXPECT_EQ(blob2.Compare(blob1), -1);
Blob blob3("12345");
EXPECT_EQ(blob2.Compare(blob3), 0);
}
/**
* @tc.name: Data001
* @tc.desc: construct a Blob and check it Data function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Data001, TestSize.Level0)
{
std::vector<uint8_t> result = {'1', '2', '3', '4'};
Blob blob1("1234");
EXPECT_EQ(blob1.Data(), result);
std::vector<uint8_t> result2 = {'1', '2', '3', '4', '5'};
Blob blob2("12345");
EXPECT_EQ(blob2.Data(), result2);
}
/**
* @tc.name: ToString001
* @tc.desc: construct a Blob and check it ToString function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, ToString001, TestSize.Level0)
{
Blob blob1("1234");
std::string str = "1234";
EXPECT_EQ(blob1.ToString(), str);
}
/**
* @tc.name: OperatorEqual001
* @tc.desc: construct a Blob and check it operator== function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, OperatorEqual001, TestSize.Level0)
{
Blob blob1("1234");
Blob blob2("1234");
EXPECT_EQ(blob1 == blob2, true);
Blob blob3("12345");
EXPECT_EQ(blob1 == blob3, false);
}
/**
* @tc.name: Operator001
* @tc.desc: construct a Blob and check it operator[] function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Operator001, TestSize.Level0)
{
Blob blob1("1234");
EXPECT_EQ(blob1[0], '1');
EXPECT_EQ(blob1[1], '2');
EXPECT_EQ(blob1[2], '3');
EXPECT_EQ(blob1[3], '4');
EXPECT_EQ(blob1[4], 0);
}
/**
* @tc.name: Operator002
* @tc.desc: construct a Blob and check it operator= function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Operator002, TestSize.Level0)
{
Blob blob1("1234");
Blob blob2 = blob1;
EXPECT_EQ(blob1 == blob2, true);
EXPECT_EQ(blob2.ToString(), "1234");
}
/**
* @tc.name: Operator003
* @tc.desc: construct a Blob and check it operator= function.
* @tc.type: FUNC
* @tc.require: AR000C6GBG
* @tc.author: liqiao
*/
HWTEST_F(BlobTest, Operator003, TestSize.Level0)
{
Blob blob1("1234");
Blob blob2 = std::move(blob1);
EXPECT_EQ(blob1 == blob2, false);
EXPECT_EQ(blob1.Empty(), true);
EXPECT_EQ(blob2.ToString(), "1234");
}

View File

@ -1,130 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "DistributedKvDataManagerEncryptTest"
#include <gtest/gtest.h>
#include "distributed_kv_data_manager.h"
#include "kvstore_death_recipient.h"
#include "log_print.h"
#include "types.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
class DistributedKvDataManagerEncryptTest : public testing::Test {
public:
static DistributedKvDataManager manager;
static Options createEnc;
static UserId userId;
static AppId appId;
static StoreId storeId;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
static void RemoveAllStore(DistributedKvDataManager manager);
void SetUp();
void TearDown();
DistributedKvDataManagerEncryptTest();
virtual ~DistributedKvDataManagerEncryptTest();
};
class MyDeathRecipient : public KvStoreDeathRecipient {
public:
MyDeathRecipient() {}
virtual ~MyDeathRecipient() {}
void OnRemoteDied() override {}
};
DistributedKvDataManager DistributedKvDataManagerEncryptTest::manager;
Options DistributedKvDataManagerEncryptTest::createEnc;
UserId DistributedKvDataManagerEncryptTest::userId;
AppId DistributedKvDataManagerEncryptTest::appId;
StoreId DistributedKvDataManagerEncryptTest::storeId;
void DistributedKvDataManagerEncryptTest::RemoveAllStore(DistributedKvDataManager manager)
{
manager.CloseAllKvStore(appId);
manager.DeleteKvStore(appId, storeId, createEnc.baseDir);
manager.DeleteAllKvStore(appId, createEnc.baseDir);
}
void DistributedKvDataManagerEncryptTest::SetUpTestCase(void)
{
createEnc.createIfMissing = true;
createEnc.encrypt = true;
createEnc.autoSync = true;
createEnc.kvStoreType = SINGLE_VERSION;
userId.userId = "account0";
appId.appId = "com.ohos.nb.service";
storeId.storeId = "EncryptStoreId";
createEnc.area = EL1;
createEnc.baseDir = std::string("/data/service/el1/public/database/") + appId.appId;
mkdir(createEnc.baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH));
}
void DistributedKvDataManagerEncryptTest::TearDownTestCase(void)
{
RemoveAllStore(manager);
(void)remove((createEnc.baseDir + "/kvdb").c_str());
(void)remove(createEnc.baseDir.c_str());
}
void DistributedKvDataManagerEncryptTest::SetUp(void)
{}
DistributedKvDataManagerEncryptTest::DistributedKvDataManagerEncryptTest(void)
{}
DistributedKvDataManagerEncryptTest::~DistributedKvDataManagerEncryptTest(void)
{}
void DistributedKvDataManagerEncryptTest::TearDown(void)
{}
/**
* @tc.name: kvstore_ddm_createEncryptedStore_001
* @tc.desc: Create an encrypted KvStore.
* @tc.type: FUNC
* @tc.require: SR000D08K4 AR000D08KQ
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerEncryptTest, kvstore_ddm_createEncryptedStore_001, TestSize.Level1)
{
ZLOGI("kvstore_ddm_createEncryptedStore_001 begin.");
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(createEnc, appId, storeId, kvStore);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore, nullptr);
Key key = "age";
Value value = "18";
status = kvStore->Put(key, value);
EXPECT_EQ(Status::SUCCESS, status) << "KvStore put data return wrong status";
// get value from kvstore.
Value valueRet;
Status statusRet = kvStore->Get(key, valueRet);
EXPECT_EQ(Status::SUCCESS, statusRet) << "get data return wrong status";
EXPECT_EQ(value, valueRet) << "value and valueRet are not equal";
}

View File

@ -1,718 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "DistributedKvDataManagerTest"
#include "distributed_kv_data_manager.h"
#include <gtest/gtest.h>
#include <vector>
#include "kvstore_death_recipient.h"
#include "log_print.h"
#include "types.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
class DistributedKvDataManagerTest : public testing::Test {
public:
static DistributedKvDataManager manager;
static Options create;
static Options noCreate;
static UserId userId;
static AppId appId;
static StoreId storeId64;
static StoreId storeId65;
static StoreId storeIdTest;
static StoreId storeIdEmpty;
static Entry entryA;
static Entry entryB;
static void SetUpTestCase(void);
static void TearDownTestCase(void);
static void RemoveAllStore(DistributedKvDataManager manager);
void SetUp();
void TearDown();
DistributedKvDataManagerTest();
};
class MyDeathRecipient : public KvStoreDeathRecipient {
public:
MyDeathRecipient() {}
virtual ~MyDeathRecipient() {}
void OnRemoteDied() override {}
};
DistributedKvDataManager DistributedKvDataManagerTest::manager;
Options DistributedKvDataManagerTest::create;
Options DistributedKvDataManagerTest::noCreate;
UserId DistributedKvDataManagerTest::userId;
AppId DistributedKvDataManagerTest::appId;
StoreId DistributedKvDataManagerTest::storeId64;
StoreId DistributedKvDataManagerTest::storeId65;
StoreId DistributedKvDataManagerTest::storeIdTest;
StoreId DistributedKvDataManagerTest::storeIdEmpty;
Entry DistributedKvDataManagerTest::entryA;
Entry DistributedKvDataManagerTest::entryB;
void DistributedKvDataManagerTest::RemoveAllStore(DistributedKvDataManager manager)
{
manager.CloseAllKvStore(appId);
manager.DeleteAllKvStore(appId, create.baseDir);
}
void DistributedKvDataManagerTest::SetUpTestCase(void)
{
userId.userId = "account0";
appId.appId = "ohos.kvdatamanager.test";
create.createIfMissing = true;
create.encrypt = false;
create.autoSync = true;
create.kvStoreType = SINGLE_VERSION;
create.area = EL1;
create.baseDir = std::string("/data/service/el1/public/database/") + appId.appId;
mkdir(create.baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH));
noCreate.createIfMissing = false;
noCreate.encrypt = false;
noCreate.autoSync = true;
noCreate.kvStoreType = SINGLE_VERSION;
noCreate.area = EL1;
noCreate.baseDir = create.baseDir;
storeId64.storeId = "a000000000b000000000c000000000d000000000e000000000f000000000g000";
storeId65.storeId = "a000000000b000000000c000000000d000000000e000000000f000000000g000"
"a000000000b000000000c000000000d000000000e000000000f000000000g0000";
storeIdTest.storeId = "test";
storeIdEmpty.storeId = "";
entryA.key = "a";
entryA.value = "valueA";
entryB.key = "b";
entryB.value = "valueB";
RemoveAllStore(manager);
}
void DistributedKvDataManagerTest::TearDownTestCase(void)
{
RemoveAllStore(manager);
(void)remove((create.baseDir + "/kvdb").c_str());
(void)remove(create.baseDir.c_str());
}
void DistributedKvDataManagerTest::SetUp(void)
{}
DistributedKvDataManagerTest::DistributedKvDataManagerTest(void)
{}
void DistributedKvDataManagerTest::TearDown(void)
{
RemoveAllStore(manager);
}
/**
* @tc.name: GetKvStore001
* @tc.desc: Get an exist SingleKvStore
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore001, TestSize.Level1)
{
ZLOGI("GetKvStore001 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, notExistKvStore);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(notExistKvStore, nullptr);
std::shared_ptr<SingleKvStore> existKvStore;
status = manager.GetSingleKvStore(noCreate, appId, storeId64, existKvStore);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(existKvStore, nullptr);
}
/**
* @tc.name: GetKvStore002
* @tc.desc: Create and get a new SingleKvStore
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore002, TestSize.Level1)
{
ZLOGI("GetKvStore002 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, notExistKvStore);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(notExistKvStore, nullptr);
manager.CloseKvStore(appId, storeId64);
manager.DeleteKvStore(appId, storeId64);
}
/**
* @tc.name: GetKvStore003
* @tc.desc: Get a non-existing SingleKvStore, and the callback function should receive STORE_NOT_FOUND and
* get a nullptr.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore003, TestSize.Level1)
{
ZLOGI("GetKvStore003 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
(void)manager.GetSingleKvStore(noCreate, appId, storeId64, notExistKvStore);
EXPECT_EQ(notExistKvStore, nullptr);
}
/**
* @tc.name: GetKvStore004
* @tc.desc: Create a SingleKvStore with an empty storeId, and the callback function should receive
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore004, TestSize.Level1)
{
ZLOGI("GetKvStore004 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(create, appId, storeIdEmpty, notExistKvStore);
ASSERT_EQ(status, Status::INVALID_ARGUMENT);
EXPECT_EQ(notExistKvStore, nullptr);
}
/**
* @tc.name: GetKvStore005
* @tc.desc: Get a SingleKvStore with an empty storeId, and the callback function should receive INVALID_ARGUMENT
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore005, TestSize.Level1)
{
ZLOGI("GetKvStore005 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(noCreate, appId, storeIdEmpty, notExistKvStore);
ASSERT_EQ(status, Status::INVALID_ARGUMENT);
EXPECT_EQ(notExistKvStore, nullptr);
}
/**
* @tc.name: GetKvStore006
* @tc.desc: Create a SingleKvStore with a 65-byte storeId, and the callback function should receive INVALID_ARGUMENT
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore006, TestSize.Level1)
{
ZLOGI("GetKvStore006 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId65, notExistKvStore);
ASSERT_EQ(status, Status::INVALID_ARGUMENT);
EXPECT_EQ(notExistKvStore, nullptr);
}
/**
* @tc.name: GetKvStore007
* @tc.desc: Get a SingleKvStore with a 65-byte storeId, the callback function should receive INVALID_ARGUMENT
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetKvStore007, TestSize.Level1)
{
ZLOGI("GetKvStore007 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(noCreate, appId, storeId65, notExistKvStore);
ASSERT_EQ(status, Status::INVALID_ARGUMENT);
EXPECT_EQ(notExistKvStore, nullptr);
}
/**
* @tc.name: GetAllKvStore001
* @tc.desc: Get all KvStore IDs when no KvStore exists, and the callback function should receive a 0-length vector.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetAllKvStore001, TestSize.Level1)
{
ZLOGI("GetAllKvStore001 begin.");
std::vector<StoreId> storeIds;
Status status = manager.GetAllKvStoreId(appId, storeIds);
EXPECT_EQ(status, Status::SUCCESS);
EXPECT_EQ(storeIds.size(), static_cast<size_t>(0));
}
/**
* @tc.name: GetAllKvStore002
* @tc.desc: Get all SingleKvStore IDs when no KvStore exists, and the callback function should receive a empty vector.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, GetAllKvStore002, TestSize.Level1)
{
ZLOGI("GetAllKvStore002 begin.");
StoreId id1;
id1.storeId = "id1";
StoreId id2;
id2.storeId = "id2";
StoreId id3;
id3.storeId = "id3";
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(create, appId, id1, kvStore);
ASSERT_NE(kvStore, nullptr);
ASSERT_EQ(status, Status::SUCCESS);
status = manager.GetSingleKvStore(create, appId, id2, kvStore);
ASSERT_NE(kvStore, nullptr);
ASSERT_EQ(status, Status::SUCCESS);
status = manager.GetSingleKvStore(create, appId, id3, kvStore);
ASSERT_NE(kvStore, nullptr);
ASSERT_EQ(status, Status::SUCCESS);
std::vector<StoreId> storeIds;
status = manager.GetAllKvStoreId(appId, storeIds);
EXPECT_EQ(status, Status::SUCCESS);
bool haveId1 = false;
bool haveId2 = false;
bool haveId3 = false;
for (StoreId &id : storeIds) {
if (id.storeId == "id1") {
haveId1 = true;
} else if (id.storeId == "id2") {
haveId2 = true;
} else if (id.storeId == "id3") {
haveId3 = true;
} else {
ZLOGI("got an unknown storeId.");
EXPECT_TRUE(false);
}
}
EXPECT_TRUE(haveId1);
EXPECT_TRUE(haveId2);
EXPECT_TRUE(haveId3);
EXPECT_EQ(storeIds.size(), static_cast<size_t>(3));
}
/**
* @tc.name: CloseKvStore001
* @tc.desc: Close an opened KVStore, and the callback function should return SUCCESS.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStore001, TestSize.Level1)
{
ZLOGI("CloseKvStore001 begin.");
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: CloseKvStore002
* @tc.desc: Close a closed SingleKvStore, and the callback function should return SUCCESS.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStore002, TestSize.Level1)
{
ZLOGI("CloseKvStore002 begin.");
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore, nullptr);
manager.CloseKvStore(appId, storeId64);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::STORE_NOT_OPEN);
}
/**
* @tc.name: CloseKvStore003
* @tc.desc: Close a SingleKvStore with an empty storeId, and the callback function should return INVALID_ARGUMENT.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStore003, TestSize.Level1)
{
ZLOGI("CloseKvStore003 begin.");
Status stat = manager.CloseKvStore(appId, storeIdEmpty);
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
}
/**
* @tc.name: CloseKvStore004
* @tc.desc: Close a SingleKvStore with a 65-byte storeId, and the callback function should return INVALID_ARGUMENT.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStore004, TestSize.Level1)
{
ZLOGI("CloseKvStore004 begin.");
Status stat = manager.CloseKvStore(appId, storeId65);
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
}
/**
* @tc.name: CloseKvStore005
* @tc.desc: Close a non-existing SingleKvStore, and the callback function should return STORE_NOT_OPEN.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStore005, TestSize.Level1)
{
ZLOGI("CloseKvStore005 begin.");
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::STORE_NOT_OPEN);
}
/**
* @tc.name: CloseKvStoreMulti001
* @tc.desc: Open a SingleKvStore several times and close them one by one.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000CSKRU
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStoreMulti001, TestSize.Level1)
{
ZLOGI("CloseKvStoreMulti001 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, notExistKvStore);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(notExistKvStore, nullptr);
std::shared_ptr<SingleKvStore> existKvStore;
manager.GetSingleKvStore(noCreate, appId, storeId64, existKvStore);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(existKvStore, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: CloseKvStoreMulti002
* @tc.desc: Open a SingleKvStore several times and close them one by one.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000CSKRU
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseKvStoreMulti002, TestSize.Level1)
{
ZLOGI("CloseKvStoreMulti002 begin.");
std::shared_ptr<SingleKvStore> notExistKvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, notExistKvStore);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(notExistKvStore, nullptr);
std::shared_ptr<SingleKvStore> existKvStore1;
status = manager.GetSingleKvStore(noCreate, appId, storeId64, existKvStore1);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(existKvStore1, nullptr);
std::shared_ptr<SingleKvStore> existKvStore2;
status = manager.GetSingleKvStore(noCreate, appId, storeId64, existKvStore2);
ASSERT_EQ(status, Status::SUCCESS);
EXPECT_NE(existKvStore2, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseKvStore(appId, storeId64);
EXPECT_NE(stat, Status::SUCCESS);
}
/**
* @tc.name: CloseAllKvStore001
* @tc.desc: Close all opened KvStores, and the callback function should return SUCCESS.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseAllKvStore001, TestSize.Level1)
{
ZLOGI("CloseAllKvStore001 begin.");
std::shared_ptr<SingleKvStore> kvStore1;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore1);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore1, nullptr);
std::shared_ptr<SingleKvStore> kvStore2;
status = manager.GetSingleKvStore(create, appId, storeIdTest, kvStore2);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore2, nullptr);
Status stat = manager.CloseAllKvStore(appId);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: CloseAllKvStore002
* @tc.desc: Close all KvStores which exist but are not opened, and the callback function should return STORE_NOT_OPEN.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, CloseAllKvStore002, TestSize.Level1)
{
ZLOGI("CloseAllKvStore002 begin.");
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore, nullptr);
std::shared_ptr<SingleKvStore> kvStore2;
status = manager.GetSingleKvStore(create, appId, storeIdTest, kvStore2);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore2, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseAllKvStore(appId);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: DeleteKvStore001
* @tc.desc: Delete a closed KvStore, and the callback function should return SUCCESS.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteKvStore001, TestSize.Level1)
{
ZLOGI("DeleteKvStore001 begin.");
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
ASSERT_EQ(stat, Status::SUCCESS);
stat = manager.DeleteKvStore(appId, storeId64, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: DeleteKvStore002
* @tc.desc: Delete an opened SingleKvStore, and the callback function should return SUCCESS.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteKvStore002, TestSize.Level1)
{
ZLOGI("DeleteKvStore002 begin.");
std::shared_ptr<SingleKvStore> kvStore;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore, nullptr);
// first close it if opened, and then delete it.
Status stat = manager.DeleteKvStore(appId, storeId64, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: DeleteKvStore003
* @tc.desc: Delete a non-existing KvStore, and the callback function should return DB_ERROR.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteKvStore003, TestSize.Level1)
{
ZLOGI("DeleteKvStore003 begin.");
Status stat = manager.DeleteKvStore(appId, storeId64, create.baseDir);
EXPECT_EQ(stat, Status::STORE_NOT_FOUND);
}
/**
* @tc.name: DeleteKvStore004
* @tc.desc: Delete a KvStore with an empty storeId, and the callback function should return INVALID_ARGUMENT.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteKvStore004, TestSize.Level1)
{
ZLOGI("DeleteKvStore004 begin.");
Status stat = manager.DeleteKvStore(appId, storeIdEmpty);
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
}
/**
* @tc.name: DeleteKvStore005
* @tc.desc: Delete a KvStore with 65 bytes long storeId (which exceed storeId length limit). Should
* return INVALID_ARGUMENT.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteKvStore005, TestSize.Level1)
{
ZLOGI("DeleteKvStore005 begin.");
Status stat = manager.DeleteKvStore(appId, storeId65);
EXPECT_EQ(stat, Status::INVALID_ARGUMENT);
}
/**
* @tc.name: DeleteAllKvStore001
* @tc.desc: Delete all KvStores after closing all of them, and the callback function should return SUCCESS.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteAllKvStore001, TestSize.Level1)
{
ZLOGI("DeleteAllKvStore001 begin.");
std::shared_ptr<SingleKvStore> kvStore1;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore1);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore1, nullptr);
std::shared_ptr<SingleKvStore> kvStore2;
status = manager.GetSingleKvStore(create, appId, storeIdTest, kvStore2);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore2, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseKvStore(appId, storeIdTest);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.DeleteAllKvStore(appId, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: DeleteAllKvStore002
* @tc.desc: Delete all kvstore fail when any kvstore in the appId is not closed
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteAllKvStore002, TestSize.Level1)
{
ZLOGI("DeleteAllKvStore002 begin.");
std::shared_ptr<SingleKvStore> kvStore1;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore1);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore1, nullptr);
std::shared_ptr<SingleKvStore> kvStore2;
status = manager.GetSingleKvStore(create, appId, storeIdTest, kvStore2);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore2, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.DeleteAllKvStore(appId, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: DeleteAllKvStore003
* @tc.desc: Delete all KvStores even if no KvStore exists in the appId.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000BVTDM
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteAllKvStore003, TestSize.Level1)
{
ZLOGI("DeleteAllKvStore003 begin.");
Status stat = manager.DeleteAllKvStore(appId, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: DeleteAllKvStore004
* @tc.desc: when delete the last active kvstore, the system will remove the app manager scene
* @tc.type: FUNC
* @tc.require: bugs
* @tc.author: Sven Wang
*/
HWTEST_F(DistributedKvDataManagerTest, DeleteAllKvStore004, TestSize.Level1)
{
ZLOGI("DeleteAllKvStore004 begin.");
std::shared_ptr<SingleKvStore> kvStore1;
Status status = manager.GetSingleKvStore(create, appId, storeId64, kvStore1);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore1, nullptr);
std::shared_ptr<SingleKvStore> kvStore2;
status = manager.GetSingleKvStore(create, appId, storeIdTest, kvStore2);
ASSERT_EQ(status, Status::SUCCESS);
ASSERT_NE(kvStore2, nullptr);
Status stat = manager.CloseKvStore(appId, storeId64);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.CloseKvStore(appId, storeIdTest);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.DeleteKvStore(appId, storeIdTest, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
stat = manager.DeleteAllKvStore(appId, create.baseDir);
EXPECT_EQ(stat, Status::SUCCESS);
}
/**
* @tc.name: RegisterKvStoreServiceDeathRecipient001
* @tc.desc: Register a callback called when the service dies.
* @tc.type: FUNC
* @tc.require: SR000CQDU0 AR000CQDU1
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, RegisterKvStoreServiceDeathRecipient001, TestSize.Level1)
{
ZLOGI("RegisterKvStoreServiceDeathRecipient001 begin.");
std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipient = std::make_shared<MyDeathRecipient>();
manager.RegisterKvStoreServiceDeathRecipient(kvStoreDeathRecipient);
kvStoreDeathRecipient->OnRemoteDied();
}
/**
* @tc.name: UnRegisterKvStoreServiceDeathRecipient001
* @tc.desc: Unregister the callback called when the service dies.
* @tc.type: FUNC
* @tc.require: AR000CQDUS AR000CQDU1
* @tc.author: liqiao
*/
HWTEST_F(DistributedKvDataManagerTest, UnRegisterKvStoreServiceDeathRecipient001, TestSize.Level1)
{
ZLOGI("UnRegisterKvStoreServiceDeathRecipient001 begin.");
std::shared_ptr<KvStoreDeathRecipient> kvStoreDeathRecipientPtr = std::make_shared<MyDeathRecipient>();
manager.UnRegisterKvStoreServiceDeathRecipient(kvStoreDeathRecipientPtr);
}

View File

@ -1,607 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "SingleKvStoreClientQueryTest"
#include <unistd.h>
#include <cstddef>
#include <cstdint>
#include <vector>
#include "distributed_kv_data_manager.h"
#include "types.h"
#include "log_print.h"
#include "gtest/gtest.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
class SingleKvStoreClientQueryTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
static std::shared_ptr<SingleKvStore> singleKvStorePtr;
static Status statusGetKvStore;
};
const std::string VALID_SCHEMA_STRICT_DEFINE = "{\"SCHEMA_VERSION\":\"1.0\","
"\"SCHEMA_MODE\":\"STRICT\","
"\"SCHEMA_SKIPSIZE\":0,"
"\"SCHEMA_DEFINE\":{"
"\"name\":\"INTEGER, NOT NULL\""
"},"
"\"SCHEMA_INDEXES\":[\"$.name\"]}";
std::shared_ptr<SingleKvStore> SingleKvStoreClientQueryTest::singleKvStorePtr = nullptr;
Status SingleKvStoreClientQueryTest::statusGetKvStore = Status::ERROR;
void SingleKvStoreClientQueryTest::SetUpTestCase(void)
{}
void SingleKvStoreClientQueryTest::TearDownTestCase(void)
{}
void SingleKvStoreClientQueryTest::SetUp(void)
{}
void SingleKvStoreClientQueryTest::TearDown(void)
{}
/**
* @tc.name: TestQueryC001
* @tc.desc: Query reset.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC001, TestSize.Level1)
{
ZLOGD("TestQueryC001 start");
DataQuery query;
EXPECT_TRUE(query.ToString().length() == 0);
std::string str = "test value";
query.EqualTo("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
EXPECT_TRUE(query.ToString().length() == 0);
ZLOGD("TestQueryC001 end");
}
/**
* @tc.name: TestQueryC002
* @tc.desc: Query equalTo.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC002, TestSize.Level1)
{
ZLOGD("TestQueryC002 start");
DataQuery query;
query.EqualTo("$.test_field_name", 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.EqualTo("$.test_field_name", (int64_t) 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.EqualTo("$.test_field_name", 1.23);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.EqualTo("$.test_field_name", false);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::string str = "";
query.EqualTo("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC002 end");
}
/**
* @tc.name: TestQueryC003
* @tc.desc: Query notEqualTo.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC003, TestSize.Level1)
{
ZLOGD("TestQueryC003 start");
DataQuery query;
query.NotEqualTo("$.test_field_name", 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.NotEqualTo("$.test_field_name", (int64_t) 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.NotEqualTo("$.test_field_name", 1.23);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.NotEqualTo("$.test_field_name", false);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::string str = "test value";
query.NotEqualTo("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC003 end");
}
/**
* @tc.name: TestQueryC004
* @tc.desc: Query greaterThan.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC004, TestSize.Level1)
{
ZLOGD("TestQueryC004 start");
DataQuery query;
query.GreaterThan("$.test_field_name", 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.GreaterThan("$.test_field_name", (int64_t) 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.GreaterThan("$.test_field_name", 1.23);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::string str = "test value";
query.GreaterThan("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC004 end");
}
/**
* @tc.name: TestQueryC005
* @tc.desc: Query lessThan.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC005, TestSize.Level1)
{
ZLOGD("TestQueryC005 start");
DataQuery query;
query.LessThan("$.test_field_name", 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.LessThan("$.test_field_name", (int64_t) 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.LessThan("$.test_field_name", 1.23);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::string str = "test value";
query.LessThan("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC005 end");
}
/**
* @tc.name: TestQueryC006
* @tc.desc: Query greaterThanOrEqualTo.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC006, TestSize.Level1)
{
ZLOGD("TestQueryC006 start");
DataQuery query;
query.GreaterThanOrEqualTo("$.test_field_name", 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.GreaterThanOrEqualTo("$.test_field_name", (int64_t) 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.GreaterThanOrEqualTo("$.test_field_name", 1.23);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::string str = "test value";
query.GreaterThanOrEqualTo("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC006 end");
}
/**
* @tc.name: TestQueryC007
* @tc.desc: Query lessThanOrEqualTo.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC007, TestSize.Level1)
{
ZLOGD("TestQueryC007 start");
DataQuery query;
query.LessThanOrEqualTo("$.test_field_name", 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.LessThanOrEqualTo("$.test_field_name", (int64_t) 100);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
query.LessThanOrEqualTo("$.test_field_name", 1.23);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::string str = "test value";
query.LessThanOrEqualTo("$.test_field_name", str);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC007 end");
}
/**
* @tc.name: TestQueryC008
* @tc.desc: Query isNull.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC008, TestSize.Level1)
{
ZLOGD("TestQueryC008 start");
DataQuery query;
query.IsNull("$.test_field_name");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC008 end");
}
/**
* @tc.name: TestQueryC009
* @tc.desc: Query in.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC009, TestSize.Level1)
{
ZLOGD("TestQueryC009 start");
DataQuery query;
std::vector<int> vectInt{ 10, 20, 30 };
query.In("$.test_field_name", vectInt);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::vector<int64_t> vectLong{ (int64_t) 100, (int64_t) 200, (int64_t) 300 };
query.In("$.test_field_name", vectLong);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::vector<double> vectDouble{1.23, 2.23, 3.23};
query.In("$.test_field_name", vectDouble);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::vector<std::string> vectString{ "value 1", "value 2", "value 3" };
query.In("$.test_field_name", vectString);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC009 end");
}
/**
* @tc.name: TestQueryC010
* @tc.desc: Query in.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC010, TestSize.Level1)
{
ZLOGD("TestQueryC010 start");
DataQuery query;
std::vector<int> vectInt{ 10, 20, 30 };
query.NotIn("$.test_field_name", vectInt);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::vector<int64_t> vectLong{ (int64_t) 100, (int64_t) 200, (int64_t) 300 };
query.NotIn("$.test_field_name", vectLong);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::vector<double> vectDouble{ 1.23, 2.23, 3.23 };
query.NotIn("$.test_field_name", vectDouble);
EXPECT_TRUE(query.ToString().length() > 0);
query.Reset();
std::vector<std::string> vectString{ "value 1", "value 2", "value 3" };
query.NotIn("$.test_field_name", vectString);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC010 end");
}
/**
* @tc.name: TestQueryC011
* @tc.desc: Query like.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC011, TestSize.Level1)
{
ZLOGD("TestQueryC011 start");
DataQuery query;
query.Like("$.test_field_name", "test value");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC011 end");
}
/**
* @tc.name: TestQueryC012
* @tc.desc: Query unlike.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC012, TestSize.Level1)
{
ZLOGD("TestQueryC012 start");
DataQuery query;
query.Unlike("$.test_field_name", "test value");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC012 end");
}
/**
* @tc.name: TestQueryC013
* @tc.desc: Query and.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC013, TestSize.Level1)
{
ZLOGD("TestQueryC013 start");
DataQuery query;
query.Like("$.test_field_name1", "test value1");
query.And();
query.Like("$.test_field_name2", "test value2");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC013 end");
}
/**
* @tc.name: TestQueryC014
* @tc.desc: Query or.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC014, TestSize.Level1)
{
ZLOGD("TestQueryC014 start");
DataQuery query;
query.Like("$.test_field_name1", "test value1");
query.Or();
query.Like("$.test_field_name2", "test value2");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC014 end");
}
/**
* @tc.name: TestQueryC015
* @tc.desc: Query orderBy.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC015, TestSize.Level1)
{
ZLOGD("TestQueryC015 start");
DataQuery query;
query.OrderByAsc("$.test_field_name1");
query.Reset();
query.OrderByDesc("$.test_field_name1");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC015 end");
}
/**
* @tc.name: TestQueryC016
* @tc.desc: Query orderBy.
* @tc.type: FUNC
* @tc.require: AR000DPSF5
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC016, TestSize.Level1)
{
ZLOGD("TestQueryC016 start");
DataQuery query;
query.Limit(10, 100);
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC016 end");
}
/**
* @tc.name: TestSingleKvStoreQueryC001
* @tc.desc: query single KvStore.
* @tc.type: FUNC
* @tc.require: SR000DPCO9
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestSingleKvStoreQueryC001, TestSize.Level1)
{
ZLOGD("TestSingleKvStoreQueryC001 start");
DistributedKvDataManager manager;
Options options = { .createIfMissing = true, .encrypt = true, .autoSync = true,
.kvStoreType = KvStoreType::SINGLE_VERSION, .schema = VALID_SCHEMA_STRICT_DEFINE };
AppId appId = { "SingleKvStoreClientQueryTestAppId1" };
StoreId storeId = { "SingleKvStoreClientQueryTestStoreId1" };
statusGetKvStore = manager.GetSingleKvStore(options, appId, storeId, singleKvStorePtr);
EXPECT_NE(singleKvStorePtr, nullptr) << "kvStorePtr is null.";
singleKvStorePtr->Put("test_key_1", "{\"name\":1}");
singleKvStorePtr->Put("test_key_2", "{\"name\":2}");
singleKvStorePtr->Put("test_key_3", "{\"name\":3}");
DataQuery query;
query.NotEqualTo("$.name", 3);
std::vector<Entry> results;
Status status1 = singleKvStorePtr->GetEntries(query, results);
ASSERT_EQ(status1, Status::SUCCESS);
EXPECT_TRUE(results.size() == 2);
results.clear();
Status status2 = singleKvStorePtr->GetEntries(query, results);
ASSERT_EQ(status2, Status::SUCCESS);
EXPECT_TRUE(results.size() == 2);
std::shared_ptr<KvStoreResultSet> resultSet;
Status status3 = singleKvStorePtr->GetResultSet(query, resultSet);
ASSERT_EQ(status3, Status::SUCCESS);
EXPECT_TRUE(resultSet->GetCount() == 2);
auto closeResultSetStatus = singleKvStorePtr->CloseResultSet(resultSet);
ASSERT_EQ(closeResultSetStatus, Status::SUCCESS);
Status status4 = singleKvStorePtr->GetResultSet(query, resultSet);
ASSERT_EQ(status4, Status::SUCCESS);
EXPECT_TRUE(resultSet->GetCount() == 2);
closeResultSetStatus = singleKvStorePtr->CloseResultSet(resultSet);
ASSERT_EQ(closeResultSetStatus, Status::SUCCESS);
int resultSize1;
Status status5 = singleKvStorePtr->GetCount(query, resultSize1);
ASSERT_EQ(status5, Status::SUCCESS);
EXPECT_TRUE(resultSize1 == 2);
int resultSize2;
Status status6 = singleKvStorePtr->GetCount(query, resultSize2);
ASSERT_EQ(status6, Status::SUCCESS);
EXPECT_TRUE(resultSize2 == 2);
singleKvStorePtr->Delete("test_key_1");
singleKvStorePtr->Delete("test_key_2");
singleKvStorePtr->Delete("test_key_3");
Status status = manager.CloseAllKvStore(appId);
EXPECT_EQ(status, Status::SUCCESS);
status = manager.DeleteAllKvStore(appId);
EXPECT_EQ(status, Status::SUCCESS);
ZLOGD("TestSingleKvStoreQueryC001 end");
}
/**
* @tc.name: TestSingleKvStoreQueryC002
* @tc.desc: query single KvStore.
* @tc.type: FUNC
* @tc.require: SR000DPCO9
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestSingleKvStoreQueryC002, TestSize.Level1)
{
ZLOGD("TestSingleKvStoreQueryC002 start");
DistributedKvDataManager manager;
Options options = { .createIfMissing = true, .encrypt = true, .autoSync = true,
.kvStoreType = KvStoreType::SINGLE_VERSION };
options.schema = VALID_SCHEMA_STRICT_DEFINE;
AppId appId = { "SingleKvStoreClientQueryTestAppId2" };
StoreId storeId = { "SingleKvStoreClientQueryTestStoreId2" };
statusGetKvStore = manager.GetSingleKvStore(options, appId, storeId, singleKvStorePtr);
EXPECT_NE(singleKvStorePtr, nullptr) << "kvStorePtr is null.";
singleKvStorePtr->Put("test_key_1", "{\"name\":1}");
singleKvStorePtr->Put("test_key_2", "{\"name\":2}");
singleKvStorePtr->Put("test_key_3", "{\"name\":3}");
DataQuery query;
query.NotEqualTo("$.name", 3);
query.And();
query.EqualTo("$.name", 1);
std::vector<Entry> results1;
Status status1 = singleKvStorePtr->GetEntries(query, results1);
ASSERT_EQ(status1, Status::SUCCESS);
EXPECT_TRUE(results1.size() == 1);
std::vector<Entry> results2;
Status status2 = singleKvStorePtr->GetEntries(query, results2);
ASSERT_EQ(status2, Status::SUCCESS);
EXPECT_TRUE(results2.size() == 1);
std::shared_ptr<KvStoreResultSet> resultSet;
Status status3 = singleKvStorePtr->GetResultSet(query, resultSet);
ASSERT_EQ(status3, Status::SUCCESS);
EXPECT_TRUE(resultSet->GetCount() == 1);
auto closeResultSetStatus = singleKvStorePtr->CloseResultSet(resultSet);
ASSERT_EQ(closeResultSetStatus, Status::SUCCESS);
Status status4 = singleKvStorePtr->GetResultSet(query, resultSet);
ASSERT_EQ(status4, Status::SUCCESS);
EXPECT_TRUE(resultSet->GetCount() == 1);
closeResultSetStatus = singleKvStorePtr->CloseResultSet(resultSet);
ASSERT_EQ(closeResultSetStatus, Status::SUCCESS);
int resultSize1;
Status status5 = singleKvStorePtr->GetCount(query, resultSize1);
ZLOGD("this is it %ul", status5);
ASSERT_EQ(status5, Status::SUCCESS);
EXPECT_TRUE(resultSize1 == 1);
int resultSize2;
Status status6 = singleKvStorePtr->GetCount(query, resultSize2);
ASSERT_EQ(status6, Status::SUCCESS);
EXPECT_TRUE(resultSize2 == 1);
singleKvStorePtr->Delete("test_key_1");
singleKvStorePtr->Delete("test_key_2");
singleKvStorePtr->Delete("test_key_3");
Status status = manager.CloseAllKvStore(appId);
EXPECT_EQ(status, Status::SUCCESS);
status = manager.DeleteAllKvStore(appId);
EXPECT_EQ(status, Status::SUCCESS);
ZLOGD("TestSingleKvStoreQueryC002 end");
}
/**
* @tc.name: TestQueryC017
* @tc.desc: Query group prefix isNotNull.
* @tc.type: FUNC
* @tc.require: AR000EPAMV
* @tc.author: YangLeda
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC017, TestSize.Level1)
{
ZLOGD("TestQueryC017 start");
DataQuery query;
query.KeyPrefix("prefix");
query.BeginGroup();
query.IsNotNull("$.name");
query.EndGroup();
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC017 end");
}
/**
* @tc.name: TestQueryC018
* @tc.desc: Query SetSuggestIndex.
* @tc.type: FUNC
* @tc.require: AR000F3PBJ
* @tc.author: liuwenhui
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC018, TestSize.Level1)
{
ZLOGD("TestQueryC018 start");
DataQuery query;
query.SetSuggestIndex("test_field_name");
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC018 end");
}
/**
* @tc.name: TestQueryC019
* @tc.desc: Query InKeys.
* @tc.type: FUNC
* @tc.require: AR000GOHO7
* @tc.author: taoyuxin
*/
HWTEST_F(SingleKvStoreClientQueryTest, TestQueryC019, TestSize.Level1)
{
ZLOGD("TestQueryC019 start");
DataQuery query;
query.InKeys({"test_field_name"});
EXPECT_TRUE(query.ToString().length() > 0);
ZLOGD("TestQueryC019 end");
}

View File

@ -1,148 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 <gtest/gtest.h>
#include <cstdint>
#include <vector>
#include "iremote_object.h"
#include "itypes_util.h"
#include "types.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
using namespace OHOS;
class TypesUtilTest : public testing::Test {
public:
class TestRemoteObject : public IRemoteObject {
public:
int32_t GetObjectRefCount() override
{
return 0;
}
int SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override
{
return 0;
}
bool AddDeathRecipient(const sptr<DeathRecipient> &recipient) override
{
return false;
}
bool RemoveDeathRecipient(const sptr<DeathRecipient> &recipient) override
{
return false;
}
int Dump(int fd, const vector<std::u16string> &args) override
{
return 0;
}
};
static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {};
void SetUp() {};
void TearDown() {};
};
HWTEST_F(TypesUtilTest, DeviceInfo, TestSize.Level0)
{
MessageParcel parcel;
DeviceInfo clientDev;
clientDev.deviceId = "123";
clientDev.deviceName = "rk3568";
clientDev.deviceType = "phone";
ASSERT_TRUE(ITypesUtil::Marshal(parcel, clientDev));
DeviceInfo serverDev;
ASSERT_TRUE(ITypesUtil::Unmarshal(parcel, serverDev));
ASSERT_EQ(clientDev.deviceId, serverDev.deviceId);
ASSERT_EQ(clientDev.deviceName, serverDev.deviceName);
ASSERT_EQ(clientDev.deviceType, serverDev.deviceType);
}
HWTEST_F(TypesUtilTest, Entry, TestSize.Level0)
{
MessageParcel parcel;
Entry entryIn;
entryIn.key = "student_name_mali";
entryIn.value = "age:20";
ASSERT_TRUE(ITypesUtil::Marshal(parcel, entryIn));
Entry entryOut;
ASSERT_TRUE(ITypesUtil::Unmarshal(parcel, entryOut));
EXPECT_EQ(entryOut.key.ToString(), std::string("student_name_mali"));
EXPECT_EQ(entryOut.value.ToString(), std::string("age:20"));
}
HWTEST_F(TypesUtilTest, ChangeNotification, TestSize.Level1)
{
Entry insert, update, del;
insert.key = "insert";
update.key = "update";
del.key = "delete";
insert.value = "insert_value";
update.value = "update_value";
del.value = "delete_value";
std::vector<Entry> inserts, updates, deleteds;
inserts.push_back(insert);
updates.push_back(update);
deleteds.push_back(del);
ChangeNotification changeIn(std::move(inserts), std::move(updates), std::move(deleteds), std::string(), false);
MessageParcel parcel;
ASSERT_TRUE(ITypesUtil::Marshal(parcel, changeIn));
ChangeNotification changeOut({}, {}, {}, "", false);
ASSERT_TRUE(ITypesUtil::Unmarshal(parcel, changeOut));
ASSERT_EQ(changeOut.GetInsertEntries().size(), 1UL);
EXPECT_EQ(changeOut.GetInsertEntries().front().key.ToString(), std::string("insert"));
EXPECT_EQ(changeOut.GetInsertEntries().front().value.ToString(), std::string("insert_value"));
ASSERT_EQ(changeOut.GetUpdateEntries().size(), 1UL);
EXPECT_EQ(changeOut.GetUpdateEntries().front().key.ToString(), std::string("update"));
EXPECT_EQ(changeOut.GetUpdateEntries().front().value.ToString(), std::string("update_value"));
ASSERT_EQ(changeOut.GetDeleteEntries().size(), 1UL);
EXPECT_EQ(changeOut.GetDeleteEntries().front().key.ToString(), std::string("delete"));
EXPECT_EQ(changeOut.GetDeleteEntries().front().value.ToString(), std::string("delete_value"));
EXPECT_EQ(changeOut.IsClear(), false);
}
HWTEST_F(TypesUtilTest, Multiple, TestSize.Level1)
{
uint32_t input1 = 10;
int32_t input2 = -10;
std::string input3 = "i test";
Blob input4 = "input 4";
Entry input5;
input5.key = "my test";
input5.value = "test value";
DeviceInfo input6 = {.deviceId = "mock deviceId", .deviceName = "mock phone", .deviceType = "0"};
sptr<IRemoteObject> input7 = new TestRemoteObject();
MessageParcel parcel;
ASSERT_TRUE(ITypesUtil::Marshal(parcel, input1, input2, input3, input4, input5, input6, input7));
uint32_t output1 = 0;
int32_t output2 = 0;
std::string output3 = "";
Blob output4;
Entry output5;
DeviceInfo output6;
sptr<IRemoteObject> output7;
ASSERT_TRUE(ITypesUtil::Unmarshal(parcel, output1, output2, output3, output4, output5, output6, output7));
ASSERT_EQ(output1, input1);
ASSERT_EQ(output2, input2);
ASSERT_EQ(output3, input3);
ASSERT_EQ(output4, input4);
ASSERT_EQ(output5.key, input5.key);
ASSERT_EQ(output5.value, input5.value);
ASSERT_EQ(output6.deviceId, input6.deviceId);
ASSERT_EQ(output6.deviceName, input6.deviceName);
ASSERT_EQ(output6.deviceType, input6.deviceType);
ASSERT_EQ(output7, input7);
}

View File

@ -1,47 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 SDB_AUTO_SYNC_TIMER_H
#define SDB_AUTO_SYNC_TIMER_H
#include <set>
#include "concurrent_map.h"
#include "kv_scheduler.h"
#include "kvdb_service.h"
namespace OHOS::DistributedKv {
class AutoSyncTimer {
public:
static constexpr uint32_t FORCE_SYNC_INTERVAL = 200;
static constexpr uint32_t AUTO_SYNC_INTERVAL = 50;
static AutoSyncTimer &GetInstance();
void DoAutoSync(const std::string &appId, const std::set<StoreId> &storeIds);
private:
static constexpr size_t TIME_TASK_NUM = 5;
static constexpr size_t SYNC_STORE_NUM = 10;
AutoSyncTimer() = default;
~AutoSyncTimer() = default;
std::map<std::string, std::set<StoreId>> GetStoreIds();
std::function<void()> ProcessTask();
void StartTimer();
void StopTimer();
void AddSyncStores(const std::string &appId, std::set<StoreId> storeIds);
bool HasSyncStores();
ConcurrentMap<std::string, std::set<StoreId>> stores_;
SchedulerTask delaySyncTask_;
SchedulerTask forceSyncTask_;
std::mutex mutex_;
KvScheduler scheduler_{ TIME_TASK_NUM };
};
} // namespace OHOS::DistributedKv
#endif // SDB_AUTO_SYNC_TIMER_H

View File

@ -1,83 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_BACKUP_MANAGER_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_BACKUP_MANAGER_H
#include <string>
#include <map>
#include <vector>
#include "store_errno.h"
#include "kv_store_nb_delegate.h"
#include "kv_store_task.h"
#include "kv_store_thread_pool.h"
#include "security_manager.h"
#include "store_util.h"
namespace OHOS::DistributedKv {
class BackupManager {
public:
using DBStore = DistributedDB::KvStoreNbDelegate;
struct ResidueInfo {
size_t tmpBackupSize;
size_t tmpKeySize;
bool hasRawBackup;
bool hasTmpBackup;
bool hasRawKey;
bool hasTmpKey;
};
enum ClearType {
DO_NOTHING = 0,
ROLLBACK_DATA,
ROLLBACK_KEY,
ROLLBACK,
CLEAN_TMP,
};
static BackupManager &GetInstance();
void Init(const std::string &baseDir);
void Prepare(const std::string &path, const std::string &storeId);
Status Backup(const std::string &name, const std::string &baseDir,
const std::string &storeId, std::shared_ptr<DBStore> dbStore);
Status Restore(const std::string &name, const std::string &baseDir,
const std::string &appId, const std::string &storeId, std::shared_ptr<DBStore> dbStore);
Status DeleteBackup(std::map<std::string, Status> &deleteList,
const std::string &baseDir, const std::string &storeId);
private:
BackupManager();
~BackupManager();
void KeepData(const std::string &name, bool isCreated);
void RollBackData(const std::string &name, bool isCreated);
void CleanTmpData(const std::string &name);
StoreUtil::FileInfo GetBackupFileInfo(const std::string &name,
const std::string &baseDir, const std::string &storeId);
SecurityManager::DBPassword GetRestorePassword(const std::string &name, const std::string &baseDir,
const std::string &appId, const std::string &storeId);
bool HaveResidueFile(const std::vector<StoreUtil::FileInfo> &files);
bool HaveResidueKey(const std::vector<StoreUtil::FileInfo> &files, std::string storeId);
std::string GetBackupName(const std::string &fileName);
void SetResidueInfo(ResidueInfo &residueInfo, const std::vector<StoreUtil::FileInfo> &files,
const std::string &name, const std::string &postFix);
std::map<std::string, ResidueInfo> BuildResidueInfo(const std::vector<StoreUtil::FileInfo> &files,
const std::vector<StoreUtil::FileInfo> &keys, const std::string &storeId);
ClearType GetClearType(const ResidueInfo &residueInfo);
void ClearResidueFile(std::map<std::string, ResidueInfo> residueInfo,
const std::string &baseDir, const std::string &storeId);
bool IsEndWith(const std::string &fullString, const std::string &end);
bool IsBeginWith(const std::string &fullString, const std::string &begin);
static constexpr int MAX_BACKUP_NUM = 5;
static constexpr int POOL_SIZE = 1;
std::shared_ptr<DistributedKv::KvStoreThreadPool> pool_;
};
} // namespace OHOS::DistributedKv
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_BACKUP_MANAGER_H

View File

@ -1,42 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_KEY_CONVERTOR_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_KEY_CONVERTOR_H
#include <vector>
#include "data_query.h"
#include "query.h"
#include "types.h"
#include "types_export.h"
namespace OHOS::DistributedKv {
class Convertor {
public:
using DBKey = DistributedDB::Key;
using DBQuery = DistributedDB::Query;
virtual std::vector<uint8_t> ToLocalDBKey(const Key &key) const;
virtual std::vector<uint8_t> ToWholeDBKey(const Key &key) const;
virtual Key ToKey(DBKey &&key, std::string &deviceId) const;
virtual std::vector<uint8_t> GetPrefix(const Key &prefix) const;
virtual std::vector<uint8_t> GetPrefix(const DataQuery &query) const;
DBQuery GetDBQuery(const DataQuery &query) const;
protected:
virtual std::string GetRealKey(const std::string &key, const DataQuery &query) const;
std::vector<uint8_t> TrimKey(const Key &prefix) const;
private:
static constexpr size_t MAX_KEY_LENGTH = 1024;
};
} // namespace OHOS::DistributedKv
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_KEY_CONVERTOR_H

View File

@ -1,51 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_DEV_MANAGER_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_DEV_MANAGER_H
#include <string>
#include "types.h"
#include "lru_bucket.h"
#include "device_manager.h"
namespace OHOS::DistributedKv {
class DevManager {
public:
static constexpr size_t MAX_ID_LEN = 64;
struct DetailInfo {
std::string uuid;
std::string udid;
std::string networkId;
std::string deviceName;
std::string deviceType;
};
static DevManager &GetInstance();
std::string ToUUID(const std::string &networkId) const;
std::string ToNetworkId(const std::string &uuid) const;
const DetailInfo &GetLocalDevice();
std::vector<DetailInfo> GetRemoteDevices() const;
void Online(const std::string &networkId);
void Offline(const std::string &networkId);
void OnChanged(const std::string &networkId);
void RegisterDevCallback();
private:
DevManager();
~DevManager() = default;
int32_t Init();
const DetailInfo invalidDetail_ {};
mutable std::mutex mutex_ {};
DetailInfo localInfo_ {};
mutable LRUBucket<std::string, DetailInfo> deviceInfos_ {64};
};
} // namespace OHOS::DistributedKv
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_DEV_MANAGER_H

View File

@ -1,37 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_DEVICE_STORE_IMPL_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_DEVICE_STORE_IMPL_H
#include <vector>
#include "convertor.h"
namespace OHOS::DistributedKv {
class DeviceConvertor : public Convertor {
public:
std::vector<uint8_t> ToLocalDBKey(const Key &key) const override;
std::vector<uint8_t> ToWholeDBKey(const Key &key) const override;
Key ToKey(DBKey &&key, std::string &deviceId) const override;
std::vector<uint8_t> GetPrefix(const Key &prefix) const override;
std::vector<uint8_t> GetPrefix(const DataQuery &query) const override;
protected:
std::string GetRealKey(const std::string &key, const DataQuery &query) const override;
private:
static constexpr size_t MAX_DEV_KEY_LEN = 896;
std::vector<uint8_t> ConvertNetwork(const Key &in, bool withLen = false) const;
std::vector<uint8_t> ToLocal(const Key &in, bool withLen) const;
};
} // namespace OHOS::DistributedKv
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_DEVICE_STORE_IMPL_H

View File

@ -1,87 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SERVICE_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SERVICE_H
#include <limits>
#include <memory>
#include "ikvstore_observer.h"
#include "ikvstore_sync_callback.h"
#include "iremote_broker.h"
#include "kvstore_death_recipient.h"
#include "single_kvstore.h"
#include "types.h"
namespace OHOS::DistributedKv {
class KVDBService : public IRemoteBroker {
public:
using SingleKVStore = SingleKvStore;
struct SyncInfo {
uint64_t seqId = std::numeric_limits<uint64_t>::max();
int32_t mode = PUSH_PULL;
uint32_t delay = 0;
std::vector<std::string> devices;
std::string query;
};
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.KVDBService");
API_EXPORT KVDBService() = default;
API_EXPORT virtual ~KVDBService() = default;
virtual Status GetStoreIds(const AppId &appId, std::vector<StoreId> &storeIds) = 0;
virtual Status BeforeCreate(const AppId &appId, const StoreId &storeId, const Options &options) = 0;
virtual Status AfterCreate(
const AppId &appId, const StoreId &storeId, const Options &options, const std::vector<uint8_t> &password) = 0;
virtual Status Delete(const AppId &appId, const StoreId &storeId) = 0;
virtual Status Sync(const AppId &appId, const StoreId &storeId, const SyncInfo &syncInfo) = 0;
virtual Status RegisterSyncCallback(const AppId &appId, sptr<IKvStoreSyncCallback> callback) = 0;
virtual Status UnregisterSyncCallback(const AppId &appId) = 0;
virtual Status SetSyncParam(const AppId &appId, const StoreId &storeId, const KvSyncParam &syncParam) = 0;
virtual Status GetSyncParam(const AppId &appId, const StoreId &storeId, KvSyncParam &syncParam) = 0;
virtual Status EnableCapability(const AppId &appId, const StoreId &storeId) = 0;
virtual Status DisableCapability(const AppId &appId, const StoreId &storeId) = 0;
virtual Status SetCapability(const AppId &appId, const StoreId &storeId, const std::vector<std::string> &local,
const std::vector<std::string> &remote) = 0;
virtual Status AddSubscribeInfo(const AppId &appId, const StoreId &storeId, const SyncInfo &syncInfo) = 0;
virtual Status RmvSubscribeInfo(const AppId &appId, const StoreId &storeId, const SyncInfo &syncInfo) = 0;
virtual Status Subscribe(const AppId &appId, const StoreId &storeId, sptr<IKvStoreObserver> observer) = 0;
virtual Status Unsubscribe(const AppId &appId, const StoreId &storeId, sptr<IKvStoreObserver> observer) = 0;
virtual Status GetBackupPassword(
const AppId &appId, const StoreId &storeId, std::vector<uint8_t> &password) = 0;
protected:
enum TransId : int32_t {
TRANS_HEAD,
TRANS_GET_STORE_IDS = TRANS_HEAD,
TRANS_BEFORE_CREATE,
TRANS_AFTER_CREATE,
TRANS_DELETE,
TRANS_SYNC,
TRANS_REGISTER_CALLBACK,
TRANS_UNREGISTER_CALLBACK,
TRANS_SET_SYNC_PARAM,
TRANS_GET_SYNC_PARAM,
TRANS_ENABLE_CAP,
TRANS_DISABLE_CAP,
TRANS_SET_CAP,
TRANS_ADD_SUB,
TRANS_RMV_SUB,
TRANS_SUB,
TRANS_UNSUB,
TRANS_GET_PASSWORD,
TRANS_BUTT,
};
};
} // namespace OHOS::DistributedKv
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SERVICE_H

View File

@ -1,65 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SERVICE_CLIENT_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SERVICE_CLIENT_H
#include <functional>
#include "concurrent_map.h"
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "kvdb_service.h"
#include "kvstore_sync_callback_client.h"
namespace OHOS::DistributedKv {
class KVDBServiceClient : public IRemoteProxy<KVDBService> {
public:
static std::shared_ptr<KVDBServiceClient> GetInstance();
Status GetStoreIds(const AppId &appId, std::vector<StoreId> &storeIds) override;
Status BeforeCreate(const AppId &appId, const StoreId &storeId, const Options &options) override;
Status AfterCreate(const AppId &appId, const StoreId &storeId, const Options &options,
const std::vector<uint8_t> &password) override;
Status Delete(const AppId &appId, const StoreId &storeId) override;
Status Sync(const AppId &appId, const StoreId &storeId, const SyncInfo &syncInfo) override;
Status RegisterSyncCallback(const AppId &appId, sptr<IKvStoreSyncCallback> callback) override;
Status UnregisterSyncCallback(const AppId &appIdd) override;
Status SetSyncParam(const AppId &appId, const StoreId &storeId, const KvSyncParam &syncParam) override;
Status GetSyncParam(const AppId &appId, const StoreId &storeId, KvSyncParam &syncParam) override;
Status EnableCapability(const AppId &appId, const StoreId &storeId) override;
Status DisableCapability(const AppId &appId, const StoreId &storeId) override;
Status SetCapability(const AppId &appId, const StoreId &storeId, const std::vector<std::string> &local,
const std::vector<std::string> &remote) override;
Status AddSubscribeInfo(const AppId &appId, const StoreId &storeId, const SyncInfo &syncInfo) override;
Status RmvSubscribeInfo(const AppId &appId, const StoreId &storeId, const SyncInfo &syncInfo) override;
Status Subscribe(const AppId &appId, const StoreId &storeId, sptr<IKvStoreObserver> observer) override;
Status Unsubscribe(const AppId &appId, const StoreId &storeId, sptr<IKvStoreObserver> observer) override;
Status GetBackupPassword(const AppId &appId, const StoreId &storeId, std::vector<uint8_t> &password) override;
sptr<KvStoreSyncCallbackClient> GetSyncAgent(const AppId &appId);
private:
explicit KVDBServiceClient(const sptr<IRemoteObject> &object);
virtual ~KVDBServiceClient() = default;
class ServiceDeath : public KvStoreDeathRecipient {
public:
ServiceDeath() = default;
virtual ~ServiceDeath() = default;
void OnRemoteDied() override;
};
static std::mutex mutex_;
static std::shared_ptr<KVDBServiceClient> instance_;
static std::atomic_bool isWatched_;
sptr<IRemoteObject> remote_;
std::mutex agentMtx_;
sptr<KvStoreSyncCallbackClient> syncAgent_;
};
} // namespace OHOS::DistributedKv
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SERVICE_CLIENT_H

View File

@ -1,56 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_OBSERVER_BRIDGE_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_OBSERVER_BRIDGE_H
#include "convertor.h"
#include "kv_store_nb_delegate.h"
#include "kv_store_observer.h"
#include "kvstore_observer.h"
#include "kvstore_observer_client.h"
namespace OHOS::DistributedKv {
class IKvStoreObserver;
class ObserverBridge : public DistributedDB::KvStoreObserver {
public:
using Observer = DistributedKv::KvStoreObserver;
using DBEntry = DistributedDB::Entry;
using DBKey = DistributedDB::Key;
using DBChangedData = DistributedDB::KvStoreChangedData;
ObserverBridge(AppId appId, StoreId storeId, std::shared_ptr<Observer> observer, const Convertor &cvt);
~ObserverBridge();
Status RegisterRemoteObserver();
Status UnregisterRemoteObserver();
void OnChange(const DBChangedData &data) override;
private:
class ObserverClient : public KvStoreObserverClient {
public:
ObserverClient(std::shared_ptr<Observer> observer, const Convertor &cvt);
void OnChange(const ChangeNotification &data) override;
private:
const Convertor &convert_;
};
template<class T>
static std::vector<Entry> ConvertDB(const T &dbEntries, std::string &deviceId, const Convertor &convert);
AppId appId_;
StoreId storeId_;
std::shared_ptr<DistributedKv::KvStoreObserver> observer_;
sptr<IKvStoreObserver> remote_;
const Convertor &convert_;
};
} // namespace OHOS::DistributedKv
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_OBSERVER_BRIDGE_H

View File

@ -1,42 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SECURITY_MANAGER_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SECURITY_MANAGER_H
#include "types.h"
#include "types_export.h"
namespace OHOS::DistributedKv {
class SecurityManager {
public:
using DBPassword = DistributedDB::CipherPassword;
static SecurityManager &GetInstance();
DBPassword GetDBPassword(const std::string &name, const std::string &path, bool needCreate = false);
bool SaveDBPassword(const std::string &name, const std::string &path, const DBPassword &key);
void DelDBPassword(const std::string &name, const std::string &path);
private:
static constexpr const char *ROOT_KEY_ALIAS = "distributed_db_root_key";
static constexpr const char *STRATEGY_META_PREFIX = "StrategyMetaData";
static constexpr const char *CAPABILITY_ENABLED = "capabilityEnabled";
static constexpr const char *CAPABILITY_RANGE = "capabilityRange";
static constexpr const char *HKS_BLOB_TYPE_NONCE = "Z5s0Bo571KoqwIi6";
static constexpr const char *HKS_BLOB_TYPE_AAD = "distributeddata";
static constexpr int KEY_SIZE = 32;
std::vector<uint8_t> Random(int32_t len);
std::vector<uint8_t> LoadKeyFromFile(const std::string &name, const std::string &path);
bool SaveKeyToFile(const std::string &name, const std::string &path, const std::vector<uint8_t> &key);
};
} // namespace OHOS::DistributedKv
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SECURITY_MANAGER_H

View File

@ -1,104 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SINGLE_STORE_IMPL_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SINGLE_STORE_IMPL_H
#include <functional>
#include <shared_mutex>
#include "concurrent_map.h"
#include "convertor.h"
#include "kv_store_nb_delegate.h"
#include "kvdb_service.h"
#include "observer_bridge.h"
#include "single_kvstore.h"
#include "sync_observer.h"
namespace OHOS::DistributedKv {
class SingleStoreImpl : public SingleKvStore {
public:
using Observer = KvStoreObserver;
using SyncCallback = KvStoreSyncCallback;
using ResultSet = KvStoreResultSet;
using DBStore = DistributedDB::KvStoreNbDelegate;
using DBEntry = DistributedDB::Entry;
using DBKey = DistributedDB::Key;
using DBValue = DistributedDB::Value;
using DBQuery = DistributedDB::Query;
using SyncInfo = KVDBService::SyncInfo;
using Convert = std::function<Key(const DBKey &key, std::string &deviceId)>;
SingleStoreImpl(std::shared_ptr<DBStore> dbStore, const AppId &appId, const Options &options, const Convertor &cvt);
~SingleStoreImpl() = default;
StoreId GetStoreId() const override;
Status Put(const Key &key, const Value &value) override;
Status PutBatch(const std::vector<Entry> &entries) override;
Status Delete(const Key &key) override;
Status DeleteBatch(const std::vector<Key> &keys) override;
Status StartTransaction() override;
Status Commit() override;
Status Rollback() override;
Status SubscribeKvStore(SubscribeType type, std::shared_ptr<Observer> observer) override;
Status UnSubscribeKvStore(SubscribeType type, std::shared_ptr<Observer> observer) override;
Status Get(const Key &key, Value &value) override;
Status GetEntries(const Key &prefix, std::vector<Entry> &entries) const override;
Status GetEntries(const DataQuery &query, std::vector<Entry> &entries) const override;
Status GetResultSet(const Key &prefix, std::shared_ptr<ResultSet> &resultSet) const override;
Status GetResultSet(const DataQuery &query, std::shared_ptr<ResultSet> &resultSet) const override;
Status CloseResultSet(std::shared_ptr<ResultSet> &resultSet) override;
Status GetCount(const DataQuery &query, int &count) const override;
Status GetSecurityLevel(SecurityLevel &secLevel) const override;
Status RemoveDeviceData(const std::string &device) override;
int32_t Close(bool isForce = false);
int32_t AddRef();
Status Backup(const std::string &file, const std::string &baseDir) override;
Status Restore(const std::string &file, const std::string &baseDir) override;
Status DeleteBackup(const std::vector<std::string> &files, const std::string &baseDir,
std::map<std::string, DistributedKv::Status> &status) override;
// IPC interface
Status Sync(const std::vector<std::string> &devices, SyncMode mode, uint32_t delay) override;
Status Sync(const std::vector<std::string> &devices, SyncMode mode, const DataQuery &query,
std::shared_ptr<SyncCallback> syncCallback) override;
Status RegisterSyncCallback(std::shared_ptr<SyncCallback> callback) override;
Status UnRegisterSyncCallback() override;
Status SetSyncParam(const KvSyncParam &syncParam) override;
Status GetSyncParam(KvSyncParam &syncParam) override;
Status SetCapabilityEnabled(bool enabled) const override;
Status SetCapabilityRange(const std::vector<std::string> &local,
const std::vector<std::string> &remote) const override;
Status SubscribeWithQuery(const std::vector<std::string> &devices, const DataQuery &query) override;
Status UnsubscribeWithQuery(const std::vector<std::string> &devices, const DataQuery &query) override;
protected:
std::shared_ptr<ObserverBridge> PutIn(uint32_t &realType, std::shared_ptr<Observer> observer);
std::shared_ptr<ObserverBridge> TakeOut(uint32_t &realType, std::shared_ptr<Observer> observer);
private:
static constexpr size_t MAX_VALUE_LENGTH = 4 * 1024 * 1024;
static constexpr size_t MAX_OBSERVER_SIZE = 8;
Status GetResultSet(const DBQuery &query, std::shared_ptr<ResultSet> &resultSet) const;
Status GetEntries(const DBQuery &query, std::vector<Entry> &entries) const;
std::function<void(ObserverBridge *)> BridgeReleaser();
Status DoSync(const SyncInfo &syncInfo, std::shared_ptr<SyncCallback> observer);
void DoAutoSync();
const Convertor &convertor_;
std::string appId_;
std::string storeId_;
bool autoSync_ = false;
int32_t ref_ = 1;
mutable std::shared_mutex rwMutex_;
std::shared_ptr<DBStore> dbStore_ = nullptr;
std::shared_ptr<SyncObserver> syncObserver_ = nullptr;
ConcurrentMap<uintptr_t, std::pair<uint32_t, std::shared_ptr<ObserverBridge>>> observers_;
};
} // namespace OHOS::DistributedKv
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SINGLE_STORE_IMPL_H

View File

@ -1,46 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_STORE_FACTORY_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_STORE_FACTORY_H
#include <memory>
#include "concurrent_map.h"
#include "convertor.h"
#include "kv_store_delegate_manager.h"
#include "single_store_impl.h"
namespace OHOS::DistributedKv {
class StoreFactory {
public:
static StoreFactory &GetInstance();
std::shared_ptr<SingleKvStore> GetOrOpenStore(const AppId &appId, const StoreId &storeId, const Options &options,
Status &status, bool &isCreate);
Status Delete(const AppId &appId, const StoreId &storeId, const std::string &path);
Status Close(const AppId &appId, const StoreId &storeId, bool isForce = false);
private:
using DBManager = DistributedDB::KvStoreDelegateManager;
using DBOption = DistributedDB::KvStoreNbDelegate::Option;
using DBStore = DistributedDB::KvStoreNbDelegate;
using DBPassword = DistributedDB::CipherPassword;
StoreFactory();
std::shared_ptr<DBManager> GetDBManager(const std::string &path, const AppId &appId);
DBOption GetDBOption(const Options &options, const DBPassword &password) const;
ConcurrentMap<std::string, std::shared_ptr<DBManager>> dbManagers_;
ConcurrentMap<std::string, std::map<std::string, std::shared_ptr<SingleStoreImpl>>> stores_;
Convertor *convertors_[INVALID_TYPE];
};
} // namespace OHOS::DistributedKv
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_STORE_FACTORY_H

View File

@ -1,32 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_STORE_MANAGER_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_STORE_MANAGER_H
#include "single_kvstore.h"
namespace OHOS::DistributedKv {
class StoreManager {
public:
static StoreManager &GetInstance();
std::shared_ptr<SingleKvStore> GetKVStore(const AppId &appId, const StoreId &storeId, const Options &options,
Status &status);
Status CloseKVStore(const AppId &appId, const StoreId &storeId);
Status CloseKVStore(const AppId &appId, std::shared_ptr<SingleKvStore> &kvStore);
Status CloseAllKVStore(const AppId &appId);
Status GetStoreIds(const AppId &appId, std::vector<StoreId> &storeIds);
Status Delete(const AppId &appId, const StoreId &storeId, const std::string &path);
};
}
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_STORE_MANAGER_H

View File

@ -1,53 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_STORE_RESULT_SET_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_STORE_RESULT_SET_H
#include <memory>
#include <shared_mutex>
#include "convertor.h"
#include "kv_store_nb_delegate.h"
#include "kv_store_result_set.h"
#include "kvstore_result_set.h"
namespace OHOS::DistributedKv {
class StoreResultSet : public KvStoreResultSet {
public:
using DBResultSet = DistributedDB::KvStoreResultSet;
using DBStore = DistributedDB::KvStoreNbDelegate;
using DBEntry = DistributedDB::Entry;
StoreResultSet(DBResultSet *impl, std::shared_ptr<DBStore> dbStore, const Convertor &convert);
~StoreResultSet();
int GetCount() const override;
int GetPosition() const override;
bool MoveToFirst() override;
bool MoveToLast() override;
bool MoveToNext() override;
bool MoveToPrevious() override;
bool Move(int offset) override;
bool MoveToPosition(int position) override;
bool IsFirst() const override;
bool IsLast() const override;
bool IsBeforeFirst() const override;
bool IsAfterLast() const override;
Status GetEntry(Entry &entry) const override;
Status Close() override;
private:
mutable std::shared_mutex mutex_;
DBResultSet *impl_;
std::shared_ptr<DBStore> dbStore_;
const Convertor &convert_;
};
} // namespace OHOS::DistributedKv
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_STORE_RESULT_SET_H

View File

@ -1,49 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_STORE_UTIL_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_STORE_UTIL_H
#include "kv_store_delegate_manager.h"
#include "store_errno.h"
#include "store_types.h"
#include "types.h"
namespace OHOS::DistributedKv {
class StoreUtil final {
public:
using DBSecurity = DistributedDB::SecurityOption;
using DBStatus = DistributedDB::DBStatus;
using DBMode = DistributedDB::SyncMode;
struct FileInfo {
std::string name;
size_t size;
time_t modifyTime;
};
static DBSecurity GetDBSecurity(int32_t secLevel);
static int32_t GetSecLevel(DBSecurity dbSec);
static DBMode GetDBMode(SyncMode syncMode);
static uint32_t GetObserverMode(SubscribeType subType);
static std::string Anonymous(const std::string &name);
static uint32_t Anonymous(const void *ptr);
static Status ConvertStatus(DBStatus status);
static bool InitPath(const std::string &path);
static bool CreateFile(const std::string &name);
static std::vector<std::string> GetSubPath(const std::string &path);
static std::vector<FileInfo> GetFiles(const std::string &path);
static bool Rename(const std::string &oldName, const std::string &newName);
static bool IsFileExist(const std::string &name);
static bool Remove(const std::string &path);
};
} // namespace OHOS::DistributedKv
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_STORE_UTIL_H

View File

@ -1,33 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SYSTEM_API_H
#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SYSTEM_API_H
#include "iprocess_system_api_adapter.h"
namespace OHOS::DistributedKv {
class SystemApi : public DistributedDB::IProcessSystemApiAdapter {
public:
using AccessEventHanle = DistributedDB::OnAccessControlledEvent;
using DBStatus = DistributedDB::DBStatus;
using DBOption = DistributedDB::SecurityOption;
SystemApi();
~SystemApi();
DBStatus RegOnAccessControlledEvent(const AccessEventHanle &callback) override;
bool IsAccessControlled() const override;
DBStatus SetSecurityOption(const std::string &filePath, const DBOption &option) override;
DBStatus GetSecurityOption(const std::string &filePath, DBOption &option) const override;
bool CheckDeviceSecurityAbility(const std::string &devId, const DBOption &option) const override;
};
}
#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_KVDB_SYSTEM_API_H

View File

@ -1,114 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "AutoSyncTimer"
#include "auto_sync_timer.h"
#include "kvdb_service_client.h"
#include "log_print.h"
namespace OHOS::DistributedKv {
AutoSyncTimer &AutoSyncTimer::GetInstance()
{
static AutoSyncTimer instance;
return instance;
}
void AutoSyncTimer::StartTimer()
{
std::lock_guard<decltype(mutex_)> lockGuard(mutex_);
if (forceSyncTask_ == SchedulerTask()) {
auto expiredTime = std::chrono::system_clock::now() + std::chrono::milliseconds(FORCE_SYNC_INTERVAL);
forceSyncTask_ = scheduler_.At(expiredTime, ProcessTask());
}
if (delaySyncTask_ == SchedulerTask()) {
auto expiredTime = std::chrono::system_clock::now() + std::chrono::milliseconds(AUTO_SYNC_INTERVAL);
delaySyncTask_ = scheduler_.At(expiredTime, ProcessTask());
} else {
delaySyncTask_ = scheduler_.Reset(delaySyncTask_, delaySyncTask_->first,
std::chrono::milliseconds(AUTO_SYNC_INTERVAL));
}
}
void AutoSyncTimer::DoAutoSync(const std::string &appId, const std::set<StoreId> &storeIds)
{
AddSyncStores(appId, storeIds);
StartTimer();
}
void AutoSyncTimer::AddSyncStores(const std::string &appId, std::set<StoreId> storeIds)
{
stores_.Compute(appId, [&storeIds](const auto &key, std::set<StoreId> &value) {
value.merge(std::move(storeIds));
return !value.empty();
});
}
bool AutoSyncTimer::HasSyncStores()
{
return !stores_.Empty();
}
std::map<std::string, std::set<StoreId>> AutoSyncTimer::GetStoreIds()
{
std::map<std::string, std::set<StoreId>> stores;
int count = SYNC_STORE_NUM;
stores_.EraseIf([&stores, &count](const std::string &key, std::set<StoreId> &value) {
int size = value.size();
if (size <= count) {
stores.insert({ key, std::move(value) });
count = count - size;
return true;
}
auto &innerStore = stores[key];
for (auto it = value.begin(); it != value.end() && count > 0;) {
innerStore.insert(*it);
it = value.erase(it);
count--;
}
return value.empty();
});
return stores;
}
std::function<void()> AutoSyncTimer::ProcessTask()
{
return [this]() {
StopTimer();
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return;
}
auto storeIds = GetStoreIds();
for (const auto &id : storeIds) {
ZLOGD("DoSync appId:%{public}s store size:%{public}zu", id.first.c_str(), id.second.size());
for (const auto &storeId : id.second) {
service->Sync({ id.first }, storeId, {});
}
}
if (HasSyncStores()) {
StartTimer();
}
};
}
void AutoSyncTimer::StopTimer()
{
std::lock_guard<decltype(mutex_)> lockGuard(mutex_);
scheduler_.Clean();
forceSyncTask_ = {};
delaySyncTask_ = {};
}
}

View File

@ -1,439 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "BackupManager"
#include "backup_manager.h"
#include "kvdb_service_client.h"
#include "log_print.h"
namespace OHOS::DistributedKv {
namespace {
constexpr const char *BACKUP_POSTFIX = ".bak";
constexpr const int BACKUP_POSTFIX_SIZE = 4;
constexpr const char *BACKUP_TMP_POSTFIX = ".bk";
constexpr const int BACKUP_TMP_POSTFIX_SIZE = 3;
constexpr const char *BACKUP_KEY_POSTFIX = ".key";
constexpr const char *BACKUP_KEY_PREFIX = "Prefix_backup_";
constexpr const char *AUTO_BACKUP_NAME = "autoBackup";
constexpr const char *BACKUP_TOP_PATH = "/kvdb/backup";
constexpr const char *KEY_PATH = "/key";
}
BackupManager &BackupManager::GetInstance()
{
static BackupManager instance;
return instance;
}
BackupManager::BackupManager()
{
pool_ = KvStoreThreadPool::GetPool(POOL_SIZE, true);
}
BackupManager::~BackupManager()
{
if (pool_ != nullptr) {
pool_->Stop();
pool_ = nullptr;
}
}
void BackupManager::Init(const std::string &baseDir)
{
if (pool_ == nullptr) {
ZLOGE("Backup Init, pool is null");
return;
}
KvStoreTask task([this, baseDir]() {
auto topPath = baseDir + BACKUP_TOP_PATH;
auto keyPath = baseDir + KEY_PATH;
auto storeIds = StoreUtil::GetSubPath(topPath);
auto keyFiles = StoreUtil::GetFiles(keyPath);
for (auto &storeId : storeIds) {
if (storeId == "." || storeId == "..") {
continue;
}
auto backupPath = topPath + "/" + storeId;
auto backupFiles = StoreUtil::GetFiles(backupPath);
if (HaveResidueFile(backupFiles) || HaveResidueKey(keyFiles, storeId)) {
auto ResidueInfo = BuildResidueInfo(backupFiles, keyFiles, storeId);
ClearResidueFile(ResidueInfo, baseDir, storeId);
}
}
});
pool_->AddTask(std::move(task));
}
void BackupManager::Prepare(const std::string &path, const std::string &storeId)
{
std::string topPath = path + BACKUP_TOP_PATH;
std::string storePath = topPath + "/" + storeId;
std::string autoBackupName = storePath + "/" + AUTO_BACKUP_NAME + BACKUP_POSTFIX;
(void)StoreUtil::InitPath(topPath);
(void)StoreUtil::InitPath(storePath);
(void)StoreUtil::CreateFile(autoBackupName);
}
void BackupManager::KeepData(const std::string &name, bool isCreated)
{
auto tmpName = name + BACKUP_TMP_POSTFIX;
if (isCreated) {
StoreUtil::CreateFile(tmpName);
} else {
StoreUtil::Rename(name, tmpName);
}
}
void BackupManager::RollBackData(const std::string &name, bool isCreated)
{
auto tmpName = name + BACKUP_TMP_POSTFIX;
if (isCreated) {
StoreUtil::Remove(name);
StoreUtil::Remove(tmpName);
} else {
StoreUtil::Remove(name);
StoreUtil::Rename(tmpName, name);
}
}
void BackupManager::CleanTmpData(const std::string &name)
{
auto tmpName = name + BACKUP_TMP_POSTFIX;
StoreUtil::Remove(tmpName);
}
Status BackupManager::Backup(const std::string &name, const std::string &baseDir, const std::string &storeId,
std::shared_ptr<DBStore> dbStore)
{
if (dbStore == nullptr) {
return ALREADY_CLOSED;
}
if (name.size() == 0 || baseDir.size() == 0 || storeId.size() == 0 || name == AUTO_BACKUP_NAME) {
return INVALID_ARGUMENT;
}
std::string topPath = baseDir + BACKUP_TOP_PATH;
std::string storePath = topPath + "/" + storeId;
std::string backupFullName = storePath + "/"+ name + BACKUP_POSTFIX;
std::string keyName = BACKUP_KEY_PREFIX + storeId + "_" + name;
std::string keyFullName = baseDir + KEY_PATH + "/" + keyName + BACKUP_KEY_POSTFIX;
bool isCreate = !StoreUtil::IsFileExist(backupFullName);
if ((StoreUtil::GetFiles(storePath).size() >= MAX_BACKUP_NUM) && isCreate) {
return ERROR;
}
(void)StoreUtil::InitPath(topPath);
(void)StoreUtil::InitPath(storePath);
KeepData(backupFullName, isCreate);
auto password = SecurityManager::GetInstance().GetDBPassword(storeId, baseDir);
if (password.GetSize() != 0) {
KeepData(keyFullName, isCreate);
}
auto dbStatus = dbStore->Export(backupFullName, password);
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status == SUCCESS) {
if (password.GetSize() != 0) {
SecurityManager::GetInstance().SaveDBPassword(keyName, baseDir, password);
CleanTmpData(keyFullName);
}
CleanTmpData(backupFullName);
} else {
RollBackData(backupFullName, isCreate);
if (password.GetSize() != 0) {
RollBackData(keyFullName, isCreate);
}
}
return status;
}
StoreUtil::FileInfo BackupManager::GetBackupFileInfo(
const std::string &name, const std::string &baseDir, const std::string &storeId)
{
StoreUtil::FileInfo backupFile;
std::string path = baseDir + BACKUP_TOP_PATH + "/" + storeId;
std::string backupName = name + BACKUP_POSTFIX;
auto files = StoreUtil::GetFiles(path);
time_t modifyTime = 0;
for (auto &file : files) {
if (file.name == backupName) {
backupFile = file;
break;
}
if ((file.modifyTime > modifyTime) && (file.size != 0)) {
modifyTime = file.modifyTime;
backupFile = file;
}
}
return backupFile;
}
Status BackupManager::Restore(const std::string &name, const std::string &baseDir, const std::string &appId,
const std::string &storeId, std::shared_ptr<DBStore> dbStore)
{
if (dbStore == nullptr) {
return ALREADY_CLOSED;
}
if (storeId.size() == 0 || baseDir.size() == 0) {
return INVALID_ARGUMENT;
}
auto backupFile = GetBackupFileInfo(name, baseDir, storeId);
if (backupFile.name.size() == 0) {
return INVALID_ARGUMENT;
}
auto fullName = baseDir + BACKUP_TOP_PATH + "/" + storeId + "/" + backupFile.name;
auto password = GetRestorePassword(backupFile.name, baseDir, appId, storeId);
auto dbStatus = dbStore->Import(fullName, password);
auto status = StoreUtil::ConvertStatus(dbStatus);
return status;
}
SecurityManager::DBPassword BackupManager::GetRestorePassword(const std::string &name, const std::string &baseDir,
const std::string &appId, const std::string &storeId)
{
auto backupName = name.substr(0, name.length() - BACKUP_POSTFIX_SIZE);
auto keyName = BACKUP_KEY_PREFIX + storeId + "_" + backupName;
SecurityManager::DBPassword password;
if (backupName == AUTO_BACKUP_NAME) {
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return SecurityManager::DBPassword();
}
std::vector<uint8_t> pwd;
service->GetBackupPassword({ appId }, { storeId }, pwd);
password.SetValue(pwd.data(), pwd.size());
pwd.assign(pwd.size(), 0);
} else {
password = SecurityManager::GetInstance().GetDBPassword(keyName, baseDir);
}
return password;
}
Status BackupManager::DeleteBackup(std::map<std::string, Status> &deleteList, const std::string &baseDir,
const std::string &storeId)
{
if (deleteList.empty() || baseDir.size() == 0 || storeId.size() == 0) {
return INVALID_ARGUMENT;
}
std::string path = baseDir + BACKUP_TOP_PATH + "/" + storeId;
auto fileInfos = StoreUtil::GetFiles(path);
for (auto &info : fileInfos) {
auto it = deleteList.find(info.name.substr(0, info.name.length() - BACKUP_POSTFIX_SIZE));
if (it == deleteList.end()) {
continue;
}
auto backupName = info.name.substr(0, info.name.length() - BACKUP_POSTFIX_SIZE);
if (backupName == AUTO_BACKUP_NAME) {
it->second = INVALID_ARGUMENT;
continue;
}
std::string keyName = BACKUP_KEY_PREFIX + storeId + "_" + backupName;
SecurityManager::GetInstance().DelDBPassword(keyName, baseDir);
it->second = (StoreUtil::Remove(path + "/" + info.name)) ? SUCCESS : ERROR;
}
return SUCCESS;
}
bool BackupManager::HaveResidueFile(const std::vector<StoreUtil::FileInfo> &files)
{
for (auto &file : files) {
if (IsEndWith(file.name, BACKUP_TMP_POSTFIX)) {
return true;
}
}
return false;
}
bool BackupManager::HaveResidueKey(const std::vector<StoreUtil::FileInfo> &files, std::string storeId)
{
for (auto &file : files) {
auto prefix = BACKUP_KEY_PREFIX + storeId;
if (IsBeginWith(file.name, prefix) && IsEndWith(file.name, BACKUP_TMP_POSTFIX)) {
return true;
}
}
return false;
}
std::string BackupManager::GetBackupName(const std::string &fileName)
{
int postFixLen = IsEndWith(fileName, BACKUP_TMP_POSTFIX) ?
BACKUP_POSTFIX_SIZE + BACKUP_TMP_POSTFIX_SIZE : BACKUP_POSTFIX_SIZE;
return fileName.substr(0, fileName.length() - postFixLen);
}
void BackupManager::SetResidueInfo(BackupManager::ResidueInfo &residueInfo,
const std::vector<StoreUtil::FileInfo> &files, const std::string &name, const std::string &postFix)
{
for (auto &file : files) {
if (IsBeginWith(file.name, name)) {
if (IsEndWith(file.name, postFix + BACKUP_TMP_POSTFIX) && (postFix == BACKUP_POSTFIX)) {
residueInfo.hasTmpBackup = true;
residueInfo.tmpBackupSize = file.size;
}
if (IsEndWith(file.name, postFix) && (postFix == BACKUP_POSTFIX)) {
residueInfo.hasRawBackup = true;
}
if (IsEndWith(file.name, postFix + BACKUP_TMP_POSTFIX) && (postFix == BACKUP_KEY_POSTFIX)) {
residueInfo.hasTmpKey = true;
residueInfo.tmpKeySize = file.size;
}
if (IsEndWith(file.name, postFix) && (postFix == BACKUP_KEY_POSTFIX)) {
residueInfo.hasRawKey = true;
}
}
}
}
std::map<std::string, BackupManager::ResidueInfo> BackupManager::BuildResidueInfo(
const std::vector<StoreUtil::FileInfo> &files,
const std::vector<StoreUtil::FileInfo> &keys, const std::string &storeId)
{
std::map<std::string, ResidueInfo> residueInfoList;
for (auto &file : files) {
auto backupName = GetBackupName(file.name);
if (backupName == AUTO_BACKUP_NAME) {
continue;
}
auto it = residueInfoList.find(backupName);
if (it == residueInfoList.end()) {
ResidueInfo residueInfo = { 0, 0, false, false, false, false };
SetResidueInfo(residueInfo, files, backupName, BACKUP_POSTFIX);
SetResidueInfo(residueInfo, keys, BACKUP_KEY_PREFIX + storeId + "_" + backupName, BACKUP_KEY_POSTFIX);
residueInfoList.emplace(backupName, residueInfo);
}
}
return residueInfoList;
}
/**
* in function NeedRollBack, use the number of tmp and raw file to charge who to do when start,
* learning by watching blow table,
* we can konw when the num of tmp file greater than or equal raw, interrupt happend druing backup
*
* backup step (encrypt) file status option file num
* 1, backup old data - storeId.key rollback data raw = 1
* storeId.bak.bk - tmp = 1
*
* 2, backup old key - - rollback raw = 0
* storeId.bak.bk, storeId.key.bk tmp = 2
*
* 3, do backup storeId.bak - rollback raw = 1
* storeId.bak.bk, storeId.key.bk tmp = 2
*
* 4, store key storeId.bak storeId.key rollback raw = 2
* storeId.bak.bk, storeId.key.bk tmp = 2
*
* 5, delet tmp key storeId.bak storeId.key clean data raw = 2
* storeId.bak.bk - tmp = 1
*
* 6, delet tmp data storeId.bak storeId.key do nothing raw = 2
* - - tmp = 0
*
* if step3 has failed, do as 7 ~ 8
*
* 7, rollback data storeId.bak - rollback key raw = 1
* - storeId.key.bk tmp = 1
*
* 8, rollback data storeId.bak storeId.key do nothing raw = 2
* - - tmp = 0
*
* backup step (unencrypt) file status option file num
* 1, backup old data - rollback data raw = 0
* storeId.bak.bk - tmp = 1
*
* 2, do backup storeId.bak - rollback data raw = 1
* storeId.bak.bk, - tmp = 1
*
* 6, delet tmp data storeId.bak - do nothing raw = 1
* - - tmp = 0
*
* */
BackupManager::ClearType BackupManager::GetClearType(const BackupManager::ResidueInfo &residueInfo)
{
int rawFile = 0;
int tmpFile = 0;
if (residueInfo.hasRawBackup) {
rawFile++;
}
if (residueInfo.hasRawKey) {
rawFile++;
}
if (residueInfo.hasTmpBackup) {
tmpFile++;
}
if (residueInfo.hasTmpKey) {
tmpFile++;
}
if (tmpFile == 0) {
return DO_NOTHING;
}
if ((tmpFile >= rawFile) && (tmpFile == 1) && residueInfo.hasTmpBackup) {
return ROLLBACK_DATA;
}
if ((tmpFile >= rawFile) && (tmpFile == 1) && residueInfo.hasTmpKey) {
return ROLLBACK_KEY;
}
return (tmpFile >= rawFile) ? ROLLBACK : CLEAN_TMP;
}
void BackupManager::ClearResidueFile(std::map<std::string, ResidueInfo> residueInfo,
const std::string &baseDir, const std::string &storeId)
{
for (auto &info : residueInfo) {
auto backupFullName = baseDir + BACKUP_TOP_PATH + "/" + storeId + "/" + info.first + BACKUP_POSTFIX;
auto keyFullName =
baseDir + KEY_PATH + "/" + BACKUP_KEY_PREFIX + storeId + "_" + info.first + BACKUP_KEY_POSTFIX;
switch (GetClearType(info.second)) {
case ROLLBACK_DATA:
RollBackData(backupFullName, (info.second.tmpBackupSize == 0));
break;
case ROLLBACK_KEY:
RollBackData(keyFullName, (info.second.tmpKeySize == 0));
break;
case ROLLBACK:
RollBackData(backupFullName, (info.second.tmpBackupSize == 0));
RollBackData(keyFullName, (info.second.tmpKeySize == 0));
break;
case CLEAN_TMP:
CleanTmpData(backupFullName);
CleanTmpData(keyFullName);
break;
case DO_NOTHING:
default:
break;
}
}
}
bool BackupManager::IsEndWith(const std::string &fullString, const std::string &end)
{
if (fullString.length() >= end.length()) {
return (fullString.compare(fullString.length() - end.length(), end.length(), end) == 0);
} else {
return false;
}
}
bool BackupManager::IsBeginWith(const std::string &fullString, const std::string &begin)
{
if (fullString.length() >= begin.length()) {
return (fullString.compare(0, begin.length(), begin) == 0);
} else {
return false;
}
}
} // namespace OHOS::DistributedKv

View File

@ -1,79 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 "convertor.h"
namespace OHOS::DistributedKv {
std::vector<uint8_t> Convertor::ToLocalDBKey(const Key &key) const
{
return Convertor::GetPrefix(key);
}
std::vector<uint8_t> Convertor::ToWholeDBKey(const Key &key) const
{
return Convertor::GetPrefix(key);
}
Key Convertor::ToKey(DBKey &&key, std::string &deviceId) const
{
return std::move(key);
}
std::vector<uint8_t> Convertor::GetPrefix(const Key &prefix) const
{
std::vector<uint8_t> dbKey = TrimKey(prefix);
if (dbKey.size() > MAX_KEY_LENGTH) {
dbKey.clear();
}
return dbKey;
}
std::vector<uint8_t> Convertor::GetPrefix(const DataQuery &query) const
{
return Convertor::GetPrefix(Key(query.prefix_));
}
Convertor::DBQuery Convertor::GetDBQuery(const DataQuery &query) const
{
DBQuery dbQuery = *(query.query_);
if (query.hasPrefix_) {
dbQuery.PrefixKey(GetPrefix(query));
}
if (query.hasKeys_) {
std::set<DBKey> keys;
for (auto &key : query.keys_) {
keys.insert(ToWholeDBKey(GetRealKey(key, query)));
}
dbQuery.InKeys(keys);
}
return dbQuery;
}
std::string Convertor::GetRealKey(const std::string &key, const DataQuery &query) const
{
(void)query;
return key;
}
std::vector<uint8_t> Convertor::TrimKey(const Key &prefix) const
{
auto begin = std::find_if(prefix.Data().begin(), prefix.Data().end(), [](int ch) { return !std::isspace(ch); });
auto rBegin = std::find_if(prefix.Data().rbegin(), prefix.Data().rend(), [](int ch) { return !std::isspace(ch); });
auto end = static_cast<decltype(begin)>(rBegin.base());
if (end <= begin) {
return {};
}
return {begin, end};
}
}

View File

@ -1,224 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "DevManager"
#include "dev_manager.h"
#include <thread>
#include "log_print.h"
#include "device_manager_callback.h"
#include "dm_device_info.h"
#include "store_util.h"
namespace OHOS::DistributedKv {
using namespace OHOS::DistributedHardware;
constexpr int32_t DM_OK = 0;
constexpr int32_t DM_ERROR = -1;
constexpr size_t DevManager::MAX_ID_LEN;
constexpr const char *PKG_NAME = "ohos.distributeddata";
class KvDeviceStateCallback : public DeviceStateCallback {
public:
void OnDeviceOnline(const DmDeviceInfo &deviceInfo) override;
void OnDeviceOffline(const DmDeviceInfo &deviceInfo) override;
void OnDeviceChanged(const DmDeviceInfo &deviceInfo) override;
void OnDeviceReady(const DmDeviceInfo &deviceInfo) override;
};
void KvDeviceStateCallback::OnDeviceOnline(const DmDeviceInfo &deviceInfo)
{
DevManager::GetInstance().Online(deviceInfo.networkId);
}
void KvDeviceStateCallback::OnDeviceOffline(const DmDeviceInfo &deviceInfo)
{
DevManager::GetInstance().Offline(deviceInfo.networkId);
}
void KvDeviceStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo)
{
DevManager::GetInstance().OnChanged(deviceInfo.networkId);
}
void KvDeviceStateCallback::OnDeviceReady(const DmDeviceInfo &deviceInfo)
{
}
class DmDeathCallback : public DmInitCallback {
public:
void OnRemoteDied() override;
};
void DmDeathCallback::OnRemoteDied()
{
ZLOGI("dm device manager died, init it again");
DevManager::GetInstance().RegisterDevCallback();
}
DevManager::DevManager()
{
RegisterDevCallback();
}
int32_t DevManager::Init()
{
auto &deviceManager = DeviceManager::GetInstance();
auto deviceInitCallback = std::make_shared<DmDeathCallback>();
auto deviceCallback = std::make_shared<KvDeviceStateCallback>();
int32_t errNo = deviceManager.InitDeviceManager(PKG_NAME, deviceInitCallback);
if (errNo != DM_OK) {
return errNo;
}
errNo = deviceManager.RegisterDevStateCallback(PKG_NAME, "", deviceCallback);
return errNo;
}
void DevManager::RegisterDevCallback()
{
int32_t errNo = Init();
if (errNo == DM_OK) {
return;
}
ZLOGE("register device failed, try again");
std::thread th = std::thread([this]() {
constexpr int RETRY_TIMES = 300;
int i = 0;
int32_t errNo = DM_ERROR;
while (i++ < RETRY_TIMES) {
errNo = Init();
if (errNo == DM_OK) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
ZLOGI("reg device exit now: %{public}d times, errNo: %{public}d", i, errNo);
});
th.detach();
}
DevManager &DevManager::GetInstance()
{
static DevManager instance;
return instance;
}
std::string DevManager::ToUUID(const std::string &networkId) const
{
DetailInfo deviceInfo;
if (deviceInfos_.Get(networkId, deviceInfo)) {
return deviceInfo.uuid;
}
std::string uuid;
std::string udid;
auto &deviceManager = DeviceManager::GetInstance();
deviceManager.GetUuidByNetworkId(PKG_NAME, networkId, uuid);
deviceManager.GetUdidByNetworkId(PKG_NAME, networkId, udid);
if (uuid.empty() || udid.empty() || networkId.empty()) {
return "";
}
deviceInfo = { uuid, std::move(udid), networkId, "", "" };
deviceInfos_.Set(networkId, deviceInfo);
deviceInfos_.Set(uuid, deviceInfo);
return uuid;
}
std::string DevManager::ToNetworkId(const std::string &uuid) const
{
DetailInfo deviceInfo;
if (deviceInfos_.Get(uuid, deviceInfo)) {
return deviceInfo.networkId;
}
auto infos = GetRemoteDevices();
for (auto &info : infos) {
if (info.uuid == uuid) {
deviceInfos_.Set(info.uuid, info);
deviceInfos_.Set(info.networkId, info);
return info.networkId;
}
}
std::lock_guard<decltype(mutex_)> lockGuard(mutex_);
return (localInfo_.uuid == uuid) ? localInfo_.networkId : "";
}
const DevManager::DetailInfo &DevManager::GetLocalDevice()
{
std::lock_guard<decltype(mutex_)> lockGuard(mutex_);
if (!localInfo_.uuid.empty()) {
return localInfo_;
}
DmDeviceInfo info;
auto &deviceManager = DeviceManager::GetInstance();
int32_t ret = deviceManager.GetLocalDeviceInfo(PKG_NAME, info);
if (ret != DM_OK) {
ZLOGE("GetLocalNodeDeviceInfo error");
return invalidDetail_;
}
std::string networkId = std::string(info.networkId);
std::string uuid;
deviceManager.GetUuidByNetworkId(PKG_NAME, networkId, uuid);
std::string udid;
deviceManager.GetUdidByNetworkId(PKG_NAME, networkId, udid);
if (uuid.empty() || udid.empty() || networkId.empty()) {
return invalidDetail_;
}
ZLOGI("[LocalDevice] id:%{public}s, name:%{public}s, type:%{public}d",
StoreUtil::Anonymous(uuid).c_str(), info.deviceName, info.deviceTypeId);
localInfo_ = { std::move(uuid), std::move(udid), std::move(networkId),
std::string(info.deviceName), std::string(info.deviceName) };
return localInfo_;
}
std::vector<DevManager::DetailInfo> DevManager::GetRemoteDevices() const
{
std::vector<DetailInfo> devices;
std::vector<DmDeviceInfo> dmDeviceInfos {};
auto &deviceManager = DeviceManager::GetInstance();
int32_t ret = deviceManager.GetTrustedDeviceList(PKG_NAME, "", dmDeviceInfos);
if (ret != DM_OK) {
ZLOGE("GetTrustedDeviceList error");
return devices;
}
for (const auto &dmDeviceInfo : dmDeviceInfos) {
std::string networkId = dmDeviceInfo.networkId;
std::string uuid;
std::string udid;
deviceManager.GetUuidByNetworkId(PKG_NAME, networkId, uuid);
deviceManager.GetUdidByNetworkId(PKG_NAME, networkId, udid);
DetailInfo deviceInfo = { std::move(uuid), std::move(udid), std::move(networkId),
std::string(dmDeviceInfo.deviceName), std::to_string(dmDeviceInfo.deviceTypeId) };
devices.push_back(std::move(deviceInfo));
}
return devices;
}
void DevManager::Online(const std::string &networkId)
{
// do nothing
}
void DevManager::Offline(const std::string &networkId)
{
DetailInfo deviceInfo;
if (deviceInfos_.Get(networkId, deviceInfo)) {
deviceInfos_.Delete(networkId);
deviceInfos_.Delete(deviceInfo.uuid);
}
}
void DevManager::OnChanged(const std::string &networkId)
{
// do nothing
}
} // namespace OHOS::DistributedKv

View File

@ -1,168 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "DeviceConvertor"
#include "device_convertor.h"
#include <endian.h>
#include <iomanip>
#include <regex>
#include "dev_manager.h"
#include "log_print.h"
namespace OHOS::DistributedKv {
std::vector<uint8_t> DeviceConvertor::ToLocalDBKey(const Key &key) const
{
return ToLocal(key, true);
}
std::vector<uint8_t> DeviceConvertor::ToLocal(const Key &in, bool withLen) const
{
auto uuid = DevManager::GetInstance().GetLocalDevice().uuid;
if (uuid.empty()) {
return {};
}
std::vector<uint8_t> original = TrimKey(in);
if ((original.empty() && withLen) || original.size() > MAX_DEV_KEY_LEN) {
return {};
}
// |local uuid|original key|uuid len|
// |---- -----|------------|---4----|
std::vector<uint8_t> dbKey;
dbKey.insert(dbKey.end(), uuid.begin(), uuid.end());
dbKey.insert(dbKey.end(), original.begin(), original.end());
if (withLen) {
uint32_t length = uuid.length();
length = htole32(length);
uint8_t *buf = reinterpret_cast<uint8_t *>(&length);
dbKey.insert(dbKey.end(), buf, buf + sizeof(length));
}
return dbKey;
}
std::vector<uint8_t> DeviceConvertor::ToWholeDBKey(const Key &key) const
{
// | device uuid | original key | uuid len |
// |-------------|--------------|-----4----|
return ConvertNetwork(key, true);
}
Key DeviceConvertor::ToKey(DBKey &&key, std::string &deviceId) const
{
// | uuid |original key|uuid len|
// |---- -----|------------|---4----|
if (key.size() < sizeof(uint32_t)) {
return std::move(key);
}
uint32_t length = *(reinterpret_cast<uint32_t *>(&(*(key.end() - sizeof(uint32_t)))));
if (length > key.size() - sizeof(uint32_t)) {
return std::move(key);
}
if (deviceId.empty()) {
deviceId = DevManager::GetInstance().ToNetworkId({ key.begin(), key.begin() + length });
}
length = le32toh(length);
key.erase(key.begin(), key.begin() + length);
key.erase(key.end() - sizeof(uint32_t), key.end());
return std::move(key);
}
std::vector<uint8_t> DeviceConvertor::GetPrefix(const Key &prefix) const
{
// | length | networkId | original key |
// |----4-----|-----------|--------------|
return ConvertNetwork(prefix);
}
std::vector<uint8_t> DeviceConvertor::GetPrefix(const DataQuery &query) const
{
// | length | networkId | original key |
// |----4-----|-----------|--------------|
return ConvertNetwork(GetRealKey(query.prefix_, query));
}
std::string DeviceConvertor::GetRealKey(const std::string &key, const DataQuery &query) const
{
if (query.deviceId_.empty()) {
return key;
}
// | length | networkId | original key |
// |----4-----|-----------|--------------|
std::ostringstream oss;
oss << std::setfill('0') << std::setw(sizeof(uint32_t)) << query.deviceId_.length();
oss << query.deviceId_ << key;
std::string realKey = oss.str();
return realKey;
}
std::vector<uint8_t> DeviceConvertor::ConvertNetwork(const Key &in, bool withLen) const
{
// input
// | network ID len | networkID | original key |
// |--------4-------|-----------|--------------|
size_t begin = 0;
if (in.Size() < sizeof(uint32_t)) {
return ToLocal(in, withLen);
}
std::string deviceLen(in.Data().begin() + begin, in.Data().begin() + begin + sizeof(uint32_t));
std::regex patten("^[0-9]*$");
if (!std::regex_match(deviceLen, patten)) {
// | original key |
// |--------------|
return ToLocal(in, withLen);
}
size_t devLen = static_cast<size_t>(atol(deviceLen.c_str()));
if (devLen > in.Data().size() + sizeof(uint32_t)) {
// | original key |
// |--------------|
return ToLocal(in, withLen);
}
begin += sizeof(uint32_t);
std::string networkId(in.Data().begin() + begin, in.Data().begin() + begin + devLen);
std::string uuid = DevManager::GetInstance().ToUUID(networkId);
if (uuid.empty()) {
// | original key |
// |--------------|
return devLen != DevManager::MAX_ID_LEN ? ToLocal(in, withLen) : std::vector<uint8_t>();
}
begin += devLen;
// output
// | device uuid | original key | uuid len |
// |-------------|--------------|----4-----|
// | Mandatory | Mandatory | Optional |
std::vector<uint8_t> original{ in.Data().begin() + begin, in.Data().end() };
original = TrimKey(std::move(original));
if ((original.empty() && withLen) || original.size() > MAX_DEV_KEY_LEN) {
return {};
}
std::vector<uint8_t> out;
out.insert(out.end(), uuid.begin(), uuid.end());
out.insert(out.end(), original.begin(), original.end());
if (withLen) {
uint32_t length = uuid.length();
length = htole32(length);
uint8_t *buf = reinterpret_cast<uint8_t *>(&length);
out.insert(out.end(), buf, buf + sizeof(length));
}
return out;
}
} // namespace OHOS::DistributedKv

View File

@ -1,304 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "KVDBServiceClient"
#include "kvdb_service_client.h"
#include <cinttypes>
#include "itypes_util.h"
#include "kvstore_observer_client.h"
#include "kvstore_service_death_notifier.h"
#include "log_print.h"
#include "security_manager.h"
#include "single_store_impl.h"
#include "store_factory.h"
#include "store_util.h"
namespace OHOS::DistributedKv {
#define IPC_SEND(code, reply, ...) \
({ \
int32_t __status = SUCCESS; \
do { \
MessageParcel request; \
if (!request.WriteInterfaceToken(GetDescriptor())) { \
__status = IPC_PARCEL_ERROR; \
break; \
} \
if (!ITypesUtil::Marshal(request, ##__VA_ARGS__)) { \
__status = IPC_PARCEL_ERROR; \
break; \
} \
MessageOption option; \
auto result = remote_->SendRequest((code), request, reply, option); \
if (result != 0) { \
__status = IPC_ERROR; \
break; \
} \
\
ITypesUtil::Unmarshal(reply, __status); \
} while (0); \
__status; \
})
std::mutex KVDBServiceClient::mutex_;
std::shared_ptr<KVDBServiceClient> KVDBServiceClient::instance_;
std::atomic_bool KVDBServiceClient::isWatched_(false);
std::shared_ptr<KVDBServiceClient> KVDBServiceClient::GetInstance()
{
if (!isWatched_.exchange(true)) {
KvStoreServiceDeathNotifier::AddServiceDeathWatcher(std::make_shared<ServiceDeath>());
}
std::lock_guard<decltype(mutex_)> lockGuard(mutex_);
if (instance_ != nullptr) {
return instance_;
}
sptr<IKvStoreDataService> ability = KvStoreServiceDeathNotifier::GetDistributedKvDataService();
if (ability == nullptr) {
return nullptr;
}
sptr<IRemoteObject> service = ability->GetKVdbService();
if (service == nullptr) {
return nullptr;
}
sptr<KVDBServiceClient> client = new (std::nothrow) KVDBServiceClient(service);
if (client == nullptr) {
return nullptr;
}
instance_.reset(client.GetRefPtr(), [client](auto *) mutable { client = nullptr; });
return instance_;
}
void KVDBServiceClient::ServiceDeath::OnRemoteDied()
{
std::lock_guard<decltype(mutex_)> lockGuard(mutex_);
instance_ = nullptr;
}
KVDBServiceClient::KVDBServiceClient(const sptr<IRemoteObject> &handle) : IRemoteProxy(handle)
{
remote_ = Remote();
}
Status KVDBServiceClient::GetStoreIds(const AppId &appId, std::vector<StoreId> &storeIds)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_GET_STORE_IDS, reply, appId, StoreId(), storeIds);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s", status, appId.appId.c_str());
}
ITypesUtil::Unmarshal(reply, storeIds);
return static_cast<Status>(status);
}
Status KVDBServiceClient::BeforeCreate(const AppId &appId, const StoreId &storeId, const Options &options)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_BEFORE_CREATE, reply, appId, storeId, options);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x appId:%{public}s, storeId:%{public}s", status, appId.appId.c_str(),
storeId.storeId.c_str());
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::AfterCreate(
const AppId &appId, const StoreId &storeId, const Options &options, const std::vector<uint8_t> &password)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_AFTER_CREATE, reply, appId, storeId, options, password);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x appId:%{public}s, storeId:%{public}s, encrypt:%{public}d", status,
appId.appId.c_str(), storeId.storeId.c_str(), options.encrypt);
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::Delete(const AppId &appId, const StoreId &storeId)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_DELETE, reply, appId, storeId);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x appId:%{public}s, storeId:%{public}s", status, appId.appId.c_str(),
storeId.storeId.c_str());
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::Sync(const AppId &appId, const StoreId &storeId, const SyncInfo &syncInfo)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_SYNC, reply, appId, storeId, syncInfo.seqId, syncInfo.mode, syncInfo.devices,
syncInfo.delay, syncInfo.query);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s, storeId:%{public}s, sequenceId:%{public}" PRIu64, status,
appId.appId.c_str(), storeId.storeId.c_str(), syncInfo.seqId);
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::RegisterSyncCallback(const AppId &appId, sptr<IKvStoreSyncCallback> callback)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_REGISTER_CALLBACK, reply, appId, StoreId(), callback->AsObject().GetRefPtr());
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s, callback:0x%{public}x", status, appId.appId.c_str(),
StoreUtil::Anonymous(callback.GetRefPtr()));
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::UnregisterSyncCallback(const AppId &appId)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_UNREGISTER_CALLBACK, reply, appId, StoreId());
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s", status, appId.appId.c_str());
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::SetSyncParam(const AppId &appId, const StoreId &storeId, const KvSyncParam &syncParam)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_SET_SYNC_PARAM, reply, appId, storeId, syncParam.allowedDelayMs);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s, storeId:%{public}s", status, appId.appId.c_str(),
storeId.storeId.c_str());
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::GetSyncParam(const AppId &appId, const StoreId &storeId, KvSyncParam &syncParam)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_GET_SYNC_PARAM, reply, appId, storeId);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s, storeId:%{public}s", status, appId.appId.c_str(),
storeId.storeId.c_str());
return SUCCESS;
}
ITypesUtil::Unmarshal(reply, syncParam.allowedDelayMs);
return static_cast<Status>(status);
}
Status KVDBServiceClient::EnableCapability(const AppId &appId, const StoreId &storeId)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_ENABLE_CAP, reply, appId, storeId);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s, storeId:%{public}s", status, appId.appId.c_str(),
storeId.storeId.c_str());
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::DisableCapability(const AppId &appId, const StoreId &storeId)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_DISABLE_CAP, reply, appId, storeId);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s, storeId:%{public}s", status, appId.appId.c_str(),
storeId.storeId.c_str());
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::SetCapability(const AppId &appId, const StoreId &storeId,
const std::vector<std::string> &local, const std::vector<std::string> &remote)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_SET_CAP, reply, appId, storeId, local, remote);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s, storeId:%{public}s", status, appId.appId.c_str(),
storeId.storeId.c_str());
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::AddSubscribeInfo(const AppId &appId, const StoreId &storeId, const SyncInfo &syncInfo)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_ADD_SUB, reply, appId, storeId, syncInfo.seqId, syncInfo.devices, syncInfo.query);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s, storeId:%{public}s, query:%{public}s", status,
appId.appId.c_str(), storeId.storeId.c_str(), StoreUtil::Anonymous(syncInfo.query).c_str());
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::RmvSubscribeInfo(const AppId &appId, const StoreId &storeId, const SyncInfo &syncInfo)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_RMV_SUB, reply, appId, storeId, syncInfo.seqId, syncInfo.devices, syncInfo.query);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s, storeId:%{public}s, query:%{public}s", status,
appId.appId.c_str(), storeId.storeId.c_str(), StoreUtil::Anonymous(syncInfo.query).c_str());
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::Subscribe(const AppId &appId, const StoreId &storeId, sptr<IKvStoreObserver> observer)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_SUB, reply, appId, storeId, observer->AsObject().GetRefPtr());
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s, storeId:%{public}s, observer:0x%{public}x", status,
appId.appId.c_str(), storeId.storeId.c_str(), StoreUtil::Anonymous(observer.GetRefPtr()));
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::Unsubscribe(const AppId &appId, const StoreId &storeId, sptr<IKvStoreObserver> observer)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_UNSUB, reply, appId, storeId, observer->AsObject().GetRefPtr());
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x, appId:%{public}s, storeId:%{public}s, observer:0x%{public}x", status,
appId.appId.c_str(), storeId.storeId.c_str(), StoreUtil::Anonymous(observer.GetRefPtr()));
}
return static_cast<Status>(status);
}
Status KVDBServiceClient::GetBackupPassword(
const AppId &appId, const StoreId &storeId, std::vector<uint8_t> &password)
{
MessageParcel reply;
int32_t status = IPC_SEND(TRANS_GET_PASSWORD, reply, appId, storeId);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x appId:%{public}s, storeId:%{public}s", status,
appId.appId.c_str(), storeId.storeId.c_str());
}
ITypesUtil::Unmarshal(reply, password);
return static_cast<Status>(status);
}
sptr<KvStoreSyncCallbackClient> KVDBServiceClient::GetSyncAgent(const AppId &appId)
{
std::lock_guard<decltype(agentMtx_)> lockGuard(agentMtx_);
if (syncAgent_ != nullptr) {
return syncAgent_;
}
sptr<KvStoreSyncCallbackClient> syncAgent = new (std::nothrow) KvStoreSyncCallbackClient();
auto status = RegisterSyncCallback(appId, syncAgent);
if (status == SUCCESS) {
syncAgent_ = std::move(syncAgent);
}
return syncAgent_;
}
} // namespace OHOS::DistributedKv

View File

@ -1,109 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 "observer_bridge.h"
#include "kvdb_service_client.h"
#include "kvstore_observer_client.h"
namespace OHOS::DistributedKv {
ObserverBridge::ObserverBridge(AppId appId, StoreId store, std::shared_ptr<Observer> observer, const Convertor &cvt)
: appId_(std::move(appId)), storeId_(std::move(store)), observer_(std::move(observer)), convert_(cvt)
{
}
ObserverBridge::~ObserverBridge()
{
if (remote_ == nullptr) {
return;
}
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return;
}
service->Unsubscribe(appId_, storeId_, remote_);
}
Status ObserverBridge::RegisterRemoteObserver()
{
if (remote_ != nullptr) {
return SUCCESS;
}
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return SERVER_UNAVAILABLE;
}
remote_ = new (std::nothrow) ObserverClient(observer_, convert_);
auto status = service->Subscribe(appId_, storeId_, remote_);
if (status != SUCCESS) {
remote_ = nullptr;
}
return status;
}
Status ObserverBridge::UnregisterRemoteObserver()
{
if (remote_ == nullptr) {
return SUCCESS;
}
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return SERVER_UNAVAILABLE;
}
auto status = service->Unsubscribe(appId_, storeId_, remote_);
remote_ = nullptr;
return status;
}
void ObserverBridge::OnChange(const DBChangedData &data)
{
std::string deviceId;
auto inserted = ConvertDB(data.GetEntriesInserted(), deviceId, convert_);
auto updated = ConvertDB(data.GetEntriesUpdated(), deviceId, convert_);
auto deleted = ConvertDB(data.GetEntriesDeleted(), deviceId, convert_);
ChangeNotification notice(std::move(inserted), std::move(updated), std::move(deleted), deviceId, false);
observer_->OnChange(notice);
}
ObserverBridge::ObserverClient::ObserverClient(std::shared_ptr<Observer> observer, const Convertor &cvt)
: KvStoreObserverClient(observer), convert_(cvt)
{
}
void ObserverBridge::ObserverClient::OnChange(const ChangeNotification &data)
{
std::string deviceId;
auto inserted = ObserverBridge::ConvertDB(data.GetInsertEntries(), deviceId, convert_);
auto updated = ObserverBridge::ConvertDB(data.GetUpdateEntries(), deviceId, convert_);
auto deleted = ObserverBridge::ConvertDB(data.GetDeleteEntries(), deviceId, convert_);
ChangeNotification notice(std::move(inserted), std::move(updated), std::move(deleted), deviceId, false);
KvStoreObserverClient::OnChange(notice);
}
template<class T>
std::vector<Entry> ObserverBridge::ConvertDB(const T &dbEntries, std::string &deviceId, const Convertor &convert)
{
std::vector<Entry> entries(dbEntries.size());
auto it = entries.begin();
for (const auto &dbEntry : dbEntries) {
Entry &entry = *it;
entry.key = convert.ToKey(DBKey(dbEntry.key), deviceId);
entry.value = dbEntry.value;
++it;
}
return entries;
}
} // namespace OHOS::DistributedKv

View File

@ -1,119 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 "security_manager.h"
#include <limits>
#include <random>
#include "file_ex.h"
#include "securec.h"
#include "store_util.h"
namespace OHOS::DistributedKv {
SecurityManager &SecurityManager::GetInstance()
{
static SecurityManager instance;
return instance;
}
SecurityManager::DBPassword SecurityManager::GetDBPassword(const std::string &name,
const std::string &path, bool needCreate)
{
auto secKey = LoadKeyFromFile(name, path);
if (secKey.empty()) {
if (!needCreate) {
return DBPassword();
} else {
secKey = Random(KEY_SIZE);
SaveKeyToFile(name, path, secKey);
}
}
DBPassword password;
password.SetValue(secKey.data(), secKey.size());
secKey.assign(secKey.size(), 0);
return password;
}
bool SecurityManager::SaveDBPassword
(const std::string &name, const std::string &path, const SecurityManager::DBPassword &key)
{
std::vector<uint8_t> pwd(key.GetData(), key.GetData() + key.GetSize());
SaveKeyToFile(name, path, pwd);
pwd.assign(pwd.size(), 0);
return true;
}
void SecurityManager::DelDBPassword(const std::string &name, const std::string &path)
{
auto keyPath = path + "/key/" + name + ".key";
StoreUtil::Remove(keyPath);
}
std::vector<uint8_t> SecurityManager::Random(int32_t len)
{
std::random_device randomDevice;
std::uniform_int_distribution<int> distribution(0, std::numeric_limits<uint8_t>::max());
std::vector<uint8_t> key(len);
for (int32_t i = 0; i < len; i++) {
key[i] = static_cast<uint8_t>(distribution(randomDevice));
}
return key;
}
std::vector<uint8_t> SecurityManager::LoadKeyFromFile(const std::string &name, const std::string &path)
{
auto keyPath = path + "/key/" + name + ".key";
if (!FileExists(keyPath)) {
return {};
}
std::vector<char> content;
auto loaded = LoadBufferFromFile(keyPath, content);
if (!loaded) {
return {};
}
if (content.size() < (sizeof(time_t) / sizeof(uint8_t)) + KEY_SIZE + 1) {
return {};
}
size_t offset = 0;
if (content[offset] != char((sizeof(time_t) / sizeof(uint8_t)) + KEY_SIZE)) {
return {};
}
offset++;
std::vector<uint8_t> date;
date.assign(content.begin() + offset, content.begin() + (sizeof(time_t) / sizeof(uint8_t)) + offset);
offset += (sizeof(time_t) / sizeof(uint8_t));
std::vector<uint8_t> key{content.begin() + offset, content.begin() + KEY_SIZE + offset};
content.assign(content.size(), 0);
return key;
}
bool SecurityManager::SaveKeyToFile(const std::string &name, const std::string &path, const std::vector<uint8_t> &key)
{
auto keyPath = path + "/key";
StoreUtil::InitPath(keyPath);
std::vector<char> content;
auto time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::system_clock::now());
std::vector<uint8_t> date(reinterpret_cast<uint8_t *>(&time), reinterpret_cast<uint8_t *>(&time) + sizeof(time));
content.push_back(char((sizeof(time_t) / sizeof(uint8_t)) + KEY_SIZE));
content.insert(content.end(), date.begin(), date.end());
content.insert(content.end(), key.begin(), key.end());
auto keyFullPath = keyPath+ "/" + name + ".key";
auto ret = SaveBufferToFile(keyFullPath, content);
content.assign(content.size(), 0);
return ret;
}
} // namespace OHOS::DistributedKv

View File

@ -1,761 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "SingleStoreImpl"
#include "single_store_impl.h"
#include "auto_sync_timer.h"
#include "backup_manager.h"
#include "dds_trace.h"
#include "dev_manager.h"
#include "kvdb_service_client.h"
#include "kvstore_utils.h"
#include "log_print.h"
#include "store_result_set.h"
#include "store_util.h"
namespace OHOS::DistributedKv {
using namespace OHOS::DistributedDataDfx;
SingleStoreImpl::SingleStoreImpl(std::shared_ptr<DBStore> dbStore, const AppId &appId, const Options &options,
const Convertor &cvt) : convertor_(cvt), dbStore_(std::move(dbStore))
{
appId_ = appId.appId;
storeId_ = dbStore_->GetStoreId();
autoSync_ = options.autoSync;
syncObserver_ = std::make_shared<SyncObserver>();
if (options.backup) {
BackupManager::GetInstance().Prepare(options.baseDir, storeId_);
}
}
StoreId SingleStoreImpl::GetStoreId() const
{
return { storeId_ };
}
Status SingleStoreImpl::Put(const Key &key, const Value &value)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
DBKey dbKey = convertor_.ToLocalDBKey(key);
if (dbKey.empty() || value.Size() > MAX_VALUE_LENGTH) {
ZLOGE("invalid key:%{public}s size:[k:%{public}zu v:%{public}zu]",
StoreUtil::Anonymous(key.ToString()).c_str(), key.Size(), value.Size());
return INVALID_ARGUMENT;
}
auto dbStatus = dbStore_->Put(dbKey, value);
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x key:%{public}s, value size:%{public}zu", status,
StoreUtil::Anonymous(key.ToString()).c_str(), value.Size());
}
DoAutoSync();
return status;
}
Status SingleStoreImpl::PutBatch(const std::vector<Entry> &entries)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
std::vector<DBEntry> dbEntries;
for (const auto &entry : entries) {
DBEntry dbEntry;
dbEntry.key = convertor_.ToLocalDBKey(entry.key);
if (dbEntry.key.empty() || entry.value.Size() > MAX_VALUE_LENGTH) {
ZLOGE("invalid key:%{public}s size:[k:%{public}zu v:%{public}zu]",
StoreUtil::Anonymous(entry.key.ToString()).c_str(), entry.key.Size(), entry.value.Size());
return INVALID_ARGUMENT;
}
dbEntry.value = entry.value;
dbEntries.push_back(std::move(dbEntry));
}
auto dbStatus = dbStore_->PutBatch(dbEntries);
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x entries size:%{public}zu", status, entries.size());
}
DoAutoSync();
return status;
}
Status SingleStoreImpl::Delete(const Key &key)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
DBKey dbKey = convertor_.ToLocalDBKey(key);
if (dbKey.empty()) {
ZLOGE("invalid key:%{public}s size:%{public}zu", StoreUtil::Anonymous(key.ToString()).c_str(), key.Size());
return INVALID_ARGUMENT;
}
auto dbStatus = dbStore_->Delete(dbKey);
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x key:%{public}s", status, StoreUtil::Anonymous(key.ToString()).c_str());
}
DoAutoSync();
return status;
}
Status SingleStoreImpl::DeleteBatch(const std::vector<Key> &keys)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
std::vector<DBKey> dbKeys;
for (const auto &key : keys) {
DBKey dbKey = convertor_.ToLocalDBKey(key);
if (dbKey.empty()) {
ZLOGE("invalid key:%{public}s size:%{public}zu", StoreUtil::Anonymous(key.ToString()).c_str(), key.Size());
return INVALID_ARGUMENT;
}
dbKeys.push_back(std::move(dbKey));
}
auto dbStatus = dbStore_->DeleteBatch(dbKeys);
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x keys size:%{public}zu", status, keys.size());
}
DoAutoSync();
return status;
}
Status SingleStoreImpl::StartTransaction()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
auto dbStatus = dbStore_->StartTransaction();
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x storeId:%{public}s", status, storeId_.c_str());
}
return status;
}
Status SingleStoreImpl::Commit()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
auto dbStatus = dbStore_->Commit();
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x storeId:%{public}s", status, dbStore_->GetStoreId().c_str());
}
return status;
}
Status SingleStoreImpl::Rollback()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
auto dbStatus = dbStore_->Rollback();
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x storeId:%{public}s", status, storeId_.c_str());
}
return status;
}
Status SingleStoreImpl::SubscribeKvStore(SubscribeType type, std::shared_ptr<Observer> observer)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
if (observer == nullptr) {
ZLOGE("invalid observer is null");
return INVALID_ARGUMENT;
}
uint32_t realType = type;
std::shared_ptr<ObserverBridge> bridge = PutIn(realType, observer);
if (bridge == nullptr) {
return (realType == type) ? OVER_MAX_SUBSCRIBE_LIMITS : STORE_ALREADY_SUBSCRIBE;
}
Status status = SUCCESS;
if ((realType & SUBSCRIBE_TYPE_LOCAL) == SUBSCRIBE_TYPE_LOCAL) {
auto dbStatus = dbStore_->RegisterObserver({}, DistributedDB::OBSERVER_CHANGES_NATIVE, bridge.get());
status = StoreUtil::ConvertStatus(dbStatus);
}
if (((realType & SUBSCRIBE_TYPE_REMOTE) == SUBSCRIBE_TYPE_REMOTE) && status == SUCCESS) {
realType &= ~SUBSCRIBE_TYPE_LOCAL;
status = bridge->RegisterRemoteObserver();
}
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x type:%{public}d->%{public}d observer:0x%{public}x", status, type, realType,
StoreUtil::Anonymous(bridge.get()));
TakeOut(realType, observer);
}
return status;
}
Status SingleStoreImpl::UnSubscribeKvStore(SubscribeType type, std::shared_ptr<Observer> observer)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
if (observer == nullptr) {
ZLOGE("invalid observer is null");
return INVALID_ARGUMENT;
}
uint32_t realType = type;
std::shared_ptr<ObserverBridge> bridge = TakeOut(realType, observer);
if (bridge == nullptr) {
return STORE_NOT_SUBSCRIBE;
}
Status status = SUCCESS;
if ((realType & SUBSCRIBE_TYPE_LOCAL) == SUBSCRIBE_TYPE_LOCAL) {
auto dbStatus = dbStore_->UnRegisterObserver(bridge.get());
status = StoreUtil::ConvertStatus(dbStatus);
}
if (((realType & SUBSCRIBE_TYPE_REMOTE) == SUBSCRIBE_TYPE_REMOTE) && status == SUCCESS) {
realType &= ~SUBSCRIBE_TYPE_LOCAL;
status = bridge->UnregisterRemoteObserver();
}
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x type:%{public}d->%{public}d observer:0x%{public}x", status, type, realType,
StoreUtil::Anonymous(bridge.get()));
}
return status;
}
Status SingleStoreImpl::Get(const Key &key, Value &value)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
DBKey dbKey = convertor_.ToWholeDBKey(key);
if (dbKey.empty()) {
ZLOGE("invalid key:%{public}s size:%{public}zu", StoreUtil::Anonymous(key.ToString()).c_str(), key.Size());
return INVALID_ARGUMENT;
}
DBValue dbValue;
auto dbStatus = dbStore_->Get(dbKey, dbValue);
value = std::move(dbValue);
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x key:%{public}s", status, StoreUtil::Anonymous(key.ToString()).c_str());
}
return status;
}
Status SingleStoreImpl::GetEntries(const Key &prefix, std::vector<Entry> &entries) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
DBKey dbPrefix = convertor_.GetPrefix(prefix);
if (dbPrefix.empty() && !prefix.Empty()) {
ZLOGE("invalid prefix:%{public}s size:%{public}zu", StoreUtil::Anonymous(prefix.ToString()).c_str(),
prefix.Size());
return INVALID_ARGUMENT;
}
DBQuery dbQuery = DBQuery::Select();
dbQuery.PrefixKey(dbPrefix);
auto status = GetEntries(dbQuery, entries);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x prefix:%{public}s", status, StoreUtil::Anonymous(prefix.ToString()).c_str());
}
return status;
}
Status SingleStoreImpl::GetEntries(const DataQuery &query, std::vector<Entry> &entries) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
DBQuery dbQuery = convertor_.GetDBQuery(query);
auto status = GetEntries(dbQuery, entries);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x query:%{public}s", status, StoreUtil::Anonymous(query.ToString()).c_str());
}
return status;
}
Status SingleStoreImpl::GetResultSet(const Key &prefix, std::shared_ptr<ResultSet> &resultSet) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
DBKey dbPrefix = convertor_.GetPrefix(prefix);
if (dbPrefix.empty() && !prefix.Empty()) {
ZLOGE("invalid prefix:%{public}s size:%{public}zu", StoreUtil::Anonymous(prefix.ToString()).c_str(),
prefix.Size());
return INVALID_ARGUMENT;
}
DBQuery dbQuery = DistributedDB::Query::Select();
dbQuery.PrefixKey(dbPrefix);
auto status = GetResultSet(dbQuery, resultSet);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x prefix:%{public}s", status, StoreUtil::Anonymous(prefix.ToString()).c_str());
}
return status;
}
Status SingleStoreImpl::GetResultSet(const DataQuery &query, std::shared_ptr<ResultSet> &resultSet) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
DBQuery dbQuery = convertor_.GetDBQuery(query);
auto status = GetResultSet(dbQuery, resultSet);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x query:%{public}s", status, StoreUtil::Anonymous(query.ToString()).c_str());
}
return status;
}
Status SingleStoreImpl::CloseResultSet(std::shared_ptr<ResultSet> &resultSet)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
if (resultSet == nullptr) {
ZLOGE("input is nullptr");
return INVALID_ARGUMENT;
}
auto status = resultSet->Close();
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x storeId:%{public}s", status, storeId_.c_str());
}
resultSet = nullptr;
return status;
}
Status SingleStoreImpl::GetCount(const DataQuery &query, int &result) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
DBQuery dbQuery = convertor_.GetDBQuery(query);
auto dbStatus = dbStore_->GetCount(dbQuery, result);
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x query:%{public}s", status, StoreUtil::Anonymous(query.ToString()).c_str());
}
return status;
}
Status SingleStoreImpl::GetSecurityLevel(SecurityLevel &secLevel) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
DistributedDB::SecurityOption option;
auto dbStatus = dbStore_->GetSecurityOption(option);
secLevel = static_cast<SecurityLevel>(StoreUtil::GetSecLevel(option));
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x security:[%{public}d]", status, option.securityLabel);
}
return status;
}
Status SingleStoreImpl::RemoveDeviceData(const std::string &device)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
auto dbStatus = dbStore_->RemoveDeviceData(DevManager::GetInstance().ToUUID(device));
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x device:%{public}s", status, StoreUtil::Anonymous(device).c_str());
}
return status;
}
Status SingleStoreImpl::Sync(const std::vector<std::string> &devices, SyncMode mode, uint32_t delay)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
KVDBService::SyncInfo syncInfo;
syncInfo.seqId = KvStoreUtils::GenerateSequenceId();
syncInfo.mode = mode;
syncInfo.delay = delay;
syncInfo.devices = devices;
return DoSync(syncInfo, syncObserver_);
}
Status SingleStoreImpl::Sync(const std::vector<std::string> &devices, SyncMode mode, const DataQuery &query,
std::shared_ptr<SyncCallback> syncCallback)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
KVDBService::SyncInfo syncInfo;
syncInfo.seqId = KvStoreUtils::GenerateSequenceId();
syncInfo.mode = mode;
syncInfo.devices = devices;
syncInfo.query = query.ToString();
return DoSync(syncInfo, syncCallback);
}
Status SingleStoreImpl::RegisterSyncCallback(std::shared_ptr<SyncCallback> callback)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::API_PERFORMANCE_TRACE_ON);
if (callback == nullptr) {
ZLOGW("INVALID_ARGUMENT.");
return INVALID_ARGUMENT;
}
syncObserver_->Add(callback);
return SUCCESS;
}
Status SingleStoreImpl::UnRegisterSyncCallback()
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__),
TraceSwitch::BYTRACE_ON | TraceSwitch::API_PERFORMANCE_TRACE_ON);
syncObserver_->Clean();
return SUCCESS;
}
Status SingleStoreImpl::SetSyncParam(const KvSyncParam &syncParam)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return SERVER_UNAVAILABLE;
}
return service->SetSyncParam({ appId_ }, { storeId_ }, syncParam);
}
Status SingleStoreImpl::GetSyncParam(KvSyncParam &syncParam)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return SERVER_UNAVAILABLE;
}
return service->GetSyncParam({ appId_ }, { storeId_ }, syncParam);
}
Status SingleStoreImpl::SetCapabilityEnabled(bool enabled) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return SERVER_UNAVAILABLE;
}
if (enabled) {
return service->EnableCapability({ appId_ }, { storeId_ });
}
return service->DisableCapability({ appId_ }, { storeId_ });
}
Status SingleStoreImpl::SetCapabilityRange(const std::vector<std::string> &localLabels,
const std::vector<std::string> &remoteLabels) const
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return SERVER_UNAVAILABLE;
}
return service->SetCapability({ appId_ }, { storeId_ }, localLabels, remoteLabels);
}
Status SingleStoreImpl::SubscribeWithQuery(const std::vector<std::string> &devices, const DataQuery &query)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return SERVER_UNAVAILABLE;
}
SyncInfo syncInfo;
syncInfo.seqId = KvStoreUtils::GenerateSequenceId();
syncInfo.devices = devices;
syncInfo.query = query.ToString();
auto syncAgent = service->GetSyncAgent({ appId_ });
if (syncAgent == nullptr) {
ZLOGE("failed! invalid agent app:%{public}s, store:%{public}s!", appId_.c_str(), storeId_.c_str());
return ILLEGAL_STATE;
}
syncAgent->AddSyncCallback(syncObserver_, syncInfo.seqId);
return service->AddSubscribeInfo({ appId_ }, { storeId_ }, syncInfo);
}
Status SingleStoreImpl::UnsubscribeWithQuery(const std::vector<std::string> &devices, const DataQuery &query)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__), true);
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return SERVER_UNAVAILABLE;
}
SyncInfo syncInfo;
syncInfo.seqId = KvStoreUtils::GenerateSequenceId();
syncInfo.devices = devices;
syncInfo.query = query.ToString();
auto syncAgent = service->GetSyncAgent({ appId_ });
if (syncAgent == nullptr) {
ZLOGE("failed! invalid agent app:%{public}s, store:%{public}s!", appId_.c_str(), storeId_.c_str());
return ILLEGAL_STATE;
}
syncAgent->AddSyncCallback(syncObserver_, syncInfo.seqId);
return service->RmvSubscribeInfo({ appId_ }, { storeId_ }, syncInfo);
}
int32_t SingleStoreImpl::AddRef()
{
ref_++;
return ref_;
}
int32_t SingleStoreImpl::Close(bool isForce)
{
if (isForce) {
ref_ = 1;
}
ref_--;
if (ref_ != 0) {
return ref_;
}
observers_.Clear();
syncObserver_->Clean();
std::unique_lock<decltype(rwMutex_)> lock(rwMutex_);
dbStore_ = nullptr;
return ref_;
}
Status SingleStoreImpl::Backup(const std::string &file, const std::string &baseDir)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
auto status = BackupManager::GetInstance().Backup(file, baseDir, storeId_, dbStore_);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x storeId:%{public}s, backup name:%{public}s ",
status, storeId_.c_str(), file.c_str());
}
return status;
}
Status SingleStoreImpl::Restore(const std::string &file, const std::string &baseDir)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
auto status = BackupManager::GetInstance().Restore(file, baseDir, appId_, storeId_, dbStore_);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x storeId:%{public}s, backup name:%{public}s ",
status, storeId_.c_str(), file.c_str());
}
return status;
}
Status SingleStoreImpl::DeleteBackup(const std::vector<std::string> &files, const std::string &baseDir,
std::map<std::string, DistributedKv::Status> &results)
{
DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__));
for (auto &file : files) {
results.emplace(file, DEVICE_NOT_FOUND);
}
auto status = BackupManager::GetInstance().DeleteBackup(results, baseDir, storeId_);
if (status != SUCCESS) {
ZLOGE("status:0x%{public}x storeId:%{public}s", status, storeId_.c_str());
}
return status;
}
std::function<void(ObserverBridge *)> SingleStoreImpl::BridgeReleaser()
{
return [this](ObserverBridge *obj) {
if (obj == nullptr) {
return;
}
Status status = ALREADY_CLOSED;
{
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ != nullptr) {
auto dbStatus = dbStore_->UnRegisterObserver(obj);
status = StoreUtil::ConvertStatus(dbStatus);
}
}
Status remote = obj->UnregisterRemoteObserver();
if (status != SUCCESS || remote != SUCCESS) {
ZLOGE("status:0x%{public}x remote:0x%{public}x observer:0x%{public}x", status, remote,
StoreUtil::Anonymous(obj));
}
delete obj;
};
}
std::shared_ptr<ObserverBridge> SingleStoreImpl::PutIn(uint32_t &realType, std::shared_ptr<Observer> observer)
{
std::shared_ptr<ObserverBridge> bridge = nullptr;
observers_.Compute(uintptr_t(observer.get()),
[this, &realType, observer, &bridge](const auto &, std::pair<uint32_t, std::shared_ptr<ObserverBridge>> &pair) {
if ((pair.first & realType) == realType) {
realType = (realType & (~pair.first));
return (pair.first != 0);
}
if (observers_.Size() > MAX_OBSERVER_SIZE) {
return false;
}
if (pair.first == 0) {
auto release = BridgeReleaser();
StoreId storeId{ storeId_ };
AppId appId{ appId_ };
pair.second = { new ObserverBridge(appId, storeId, observer, convertor_), release };
}
bridge = pair.second;
realType = (realType & (~pair.first));
pair.first = pair.first | realType;
return (pair.first != 0);
});
return bridge;
}
std::shared_ptr<ObserverBridge> SingleStoreImpl::TakeOut(uint32_t &realType, std::shared_ptr<Observer> observer)
{
std::shared_ptr<ObserverBridge> bridge = nullptr;
observers_.ComputeIfPresent(uintptr_t(observer.get()),
[&realType, observer, &bridge](const auto &, std::pair<uint32_t, std::shared_ptr<ObserverBridge>> &pair) {
if ((pair.first & realType) == 0) {
return (pair.first != 0);
}
realType = (realType & pair.first);
pair.first = (pair.first & (~realType));
bridge = pair.second;
return (pair.first != 0);
});
return bridge;
}
Status SingleStoreImpl::GetResultSet(const DBQuery &query, std::shared_ptr<ResultSet> &resultSet) const
{
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
DistributedDB::KvStoreResultSet *dbResultSet = nullptr;
auto status = dbStore_->GetEntries(query, dbResultSet);
if (dbResultSet == nullptr) {
return StoreUtil::ConvertStatus(status);
}
resultSet = std::make_shared<StoreResultSet>(dbResultSet, dbStore_, convertor_);
return SUCCESS;
}
Status SingleStoreImpl::GetEntries(const DBQuery &query, std::vector<Entry> &entries) const
{
std::shared_lock<decltype(rwMutex_)> lock(rwMutex_);
if (dbStore_ == nullptr) {
ZLOGE("db:%{public}s already closed!", storeId_.c_str());
return ALREADY_CLOSED;
}
std::vector<DBEntry> dbEntries;
std::string deviceId;
auto dbStatus = dbStore_->GetEntries(query, dbEntries);
entries.resize(dbEntries.size());
auto it = entries.begin();
for (auto &dbEntry : dbEntries) {
auto &entry = *it;
entry.key = convertor_.ToKey(std::move(dbEntry.key), deviceId);
entry.value = std::move(dbEntry.value);
++it;
}
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status == NOT_FOUND) {
status = SUCCESS;
}
return status;
}
Status SingleStoreImpl::DoSync(const SyncInfo &syncInfo, std::shared_ptr<SyncCallback> observer)
{
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return SERVER_UNAVAILABLE;
}
auto syncAgent = service->GetSyncAgent({ appId_ });
if (syncAgent == nullptr) {
ZLOGE("failed! invalid agent app:%{public}s store:%{public}s!", appId_.c_str(), storeId_.c_str());
return ILLEGAL_STATE;
}
syncAgent->AddSyncCallback(observer, syncInfo.seqId);
return service->Sync({ appId_ }, { storeId_ }, syncInfo);
}
void SingleStoreImpl::DoAutoSync()
{
if (!autoSync_) {
return;
}
ZLOGD("app:%{public}s store:%{public}s!", appId_.c_str(), storeId_.c_str());
AutoSyncTimer::GetInstance().DoAutoSync(appId_, { { storeId_ } });
}
} // namespace OHOS::DistributedKv

View File

@ -1,159 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "StoreFactory"
#include "store_factory.h"
#include "backup_manager.h"
#include "device_convertor.h"
#include "log_print.h"
#include "security_manager.h"
#include "single_store_impl.h"
#include "store_util.h"
#include "system_api.h"
namespace OHOS::DistributedKv {
using namespace DistributedDB;
StoreFactory &StoreFactory::GetInstance()
{
static StoreFactory instance;
return instance;
}
StoreFactory::StoreFactory()
{
convertors_[DEVICE_COLLABORATION] = new DeviceConvertor();
convertors_[SINGLE_VERSION] = new Convertor();
convertors_[MULTI_VERSION] = new Convertor();
if (DBManager::IsProcessSystemApiAdapterValid()) {
return;
}
(void)DBManager::SetProcessSystemAPIAdapter(std::make_shared<SystemApi>());
}
std::shared_ptr<SingleKvStore> StoreFactory::GetOrOpenStore(const AppId &appId, const StoreId &storeId,
const Options &options, Status &status, bool &isCreate)
{
std::shared_ptr<SingleStoreImpl> kvStore;
isCreate = false;
stores_.Compute(appId, [&](auto &, auto &stores) {
if (stores.find(storeId) != stores.end()) {
kvStore = stores[storeId];
kvStore->AddRef();
status = SUCCESS;
return !stores.empty();
}
auto dbManager = GetDBManager(options.baseDir, appId);
auto password = SecurityManager::GetInstance().GetDBPassword(storeId.storeId, options.baseDir, options.encrypt);
DBStatus dbStatus = DBStatus::DB_ERROR;
dbManager->GetKvStore(storeId, GetDBOption(options, password),
[this, &dbManager, &kvStore, &appId, &dbStatus, &options](auto status, auto *store) {
dbStatus = status;
if (store == nullptr) {
return;
}
auto release = [dbManager](auto *store) { dbManager->CloseKvStore(store); };
auto dbStore = std::shared_ptr<DBStore>(store, release);
const Convertor &convertor = *(convertors_[options.kvStoreType]);
kvStore = std::make_shared<SingleStoreImpl>(dbStore, appId, options, convertor);
});
status = StoreUtil::ConvertStatus(dbStatus);
if (kvStore == nullptr) {
ZLOGE("failed! status:%{public}d appId:%{public}s storeId:%{public}s path:%{public}s", dbStatus,
appId.appId.c_str(), storeId.storeId.c_str(), options.baseDir.c_str());
return !stores.empty();
}
isCreate = true;
stores[storeId] = kvStore;
return !stores.empty();
});
return kvStore;
}
Status StoreFactory::Delete(const AppId &appId, const StoreId &storeId, const std::string &path)
{
Close(appId, storeId, true);
auto dbManager = GetDBManager(path, appId);
auto status = dbManager->DeleteKvStore(storeId);
SecurityManager::GetInstance().DelDBPassword(storeId.storeId, path);
return StoreUtil::ConvertStatus(status);
}
Status StoreFactory::Close(const AppId &appId, const StoreId &storeId, bool isForce)
{
Status status = STORE_NOT_OPEN;
stores_.ComputeIfPresent(appId, [&storeId, &status, isForce](auto &, auto &values) {
for (auto it = values.begin(); it != values.end();) {
if (!storeId.storeId.empty() && (it->first != storeId.storeId)) {
++it;
continue;
}
status = SUCCESS;
auto ref = it->second->Close(isForce);
if (ref <= 0) {
it = values.erase(it);
} else {
++it;
}
}
return !values.empty();
});
return status;
}
std::shared_ptr<StoreFactory::DBManager> StoreFactory::GetDBManager(const std::string &path, const AppId &appId)
{
std::shared_ptr<DBManager> dbManager;
dbManagers_.Compute(path, [&dbManager, &appId](const auto &path, std::shared_ptr<DBManager> &manager) {
if (manager != nullptr) {
dbManager = manager;
return true;
}
std::string fullPath = path + "/kvdb";
auto result = StoreUtil::InitPath(fullPath);
dbManager = std::make_shared<DBManager>(appId.appId, "default");
dbManager->SetKvStoreConfig({ fullPath });
manager = dbManager;
BackupManager::GetInstance().Init(path);
return result;
});
return dbManager;
}
StoreFactory::DBOption StoreFactory::GetDBOption(const Options &options, const DBPassword &password) const
{
DBOption dbOption;
dbOption.syncDualTupleMode = true; // tuple of (appid+storeid)
dbOption.createIfNecessary = options.createIfMissing;
dbOption.isNeedRmCorruptedDb = options.rebuild;
dbOption.isMemoryDb = (!options.persistent);
dbOption.isEncryptedDb = options.encrypt;
if (options.encrypt) {
dbOption.cipher = DistributedDB::CipherType::AES_256_GCM;
dbOption.passwd = password;
}
if (options.kvStoreType == KvStoreType::SINGLE_VERSION) {
dbOption.conflictResolvePolicy = DistributedDB::LAST_WIN;
} else if (options.kvStoreType == KvStoreType::DEVICE_COLLABORATION) {
dbOption.conflictResolvePolicy = DistributedDB::DEVICE_COLLABORATION;
}
dbOption.schema = options.schema;
dbOption.createDirByStoreIdOnly = true;
dbOption.secOption = StoreUtil::GetDBSecurity(options.securityLevel);
return dbOption;
}
} // namespace OHOS::DistributedKv

View File

@ -1,124 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "StoreManager"
#include "store_manager.h"
#include "kvdb_service_client.h"
#include "log_print.h"
#include "security_manager.h"
#include "store_factory.h"
namespace OHOS::DistributedKv {
StoreManager &StoreManager::GetInstance()
{
static StoreManager instance;
return instance;
}
std::shared_ptr<SingleKvStore> StoreManager::GetKVStore(const AppId &appId, const StoreId &storeId,
const Options &options, Status &status)
{
ZLOGD("appId:%{public}s, storeId:%{public}s type:%{public}d area:%{public}d dir:%{public}s", appId.appId.c_str(),
storeId.storeId.c_str(), options.kvStoreType, options.area, options.baseDir.c_str());
status = ILLEGAL_STATE;
if (!appId.IsValid() || !storeId.IsValid() || !options.IsValidType()) {
status = INVALID_ARGUMENT;
return nullptr;
}
auto service = KVDBServiceClient::GetInstance();
if (service != nullptr) {
status = service->BeforeCreate(appId, storeId, options);
}
if (status == STORE_META_CHANGED) {
ZLOGE("appId:%{public}s, storeId:%{public}s type:%{public}d encrypt:%{public}d", appId.appId.c_str(),
storeId.storeId.c_str(), options.kvStoreType, options.encrypt);
return nullptr;
}
bool isCreate = false;
auto kvStore = StoreFactory::GetInstance().GetOrOpenStore(appId, storeId, options, status, isCreate);
if (isCreate && options.persistent) {
auto password = SecurityManager::GetInstance().GetDBPassword(storeId.storeId, options.baseDir, options.encrypt);
std::vector<uint8_t> pwd(password.GetData(), password.GetData() + password.GetSize());
if (service != nullptr) {
// delay notify
service->AfterCreate(appId, storeId, options, pwd);
}
pwd.assign(pwd.size(), 0);
}
return kvStore;
}
Status StoreManager::CloseKVStore(const AppId &appId, const StoreId &storeId)
{
ZLOGD("appId:%{public}s, storeId:%{public}s", appId.appId.c_str(), storeId.storeId.c_str());
if (!appId.IsValid() || !storeId.IsValid()) {
return INVALID_ARGUMENT;
}
return StoreFactory::GetInstance().Close(appId, storeId);
}
Status StoreManager::CloseKVStore(const AppId &appId, std::shared_ptr<SingleKvStore> &kvStore)
{
if (!appId.IsValid() || kvStore == nullptr) {
return INVALID_ARGUMENT;
}
StoreId storeId{ kvStore->GetStoreId() };
kvStore = nullptr;
return StoreFactory::GetInstance().Close(appId, storeId);
}
Status StoreManager::CloseAllKVStore(const AppId &appId)
{
ZLOGD("appId:%{public}s", appId.appId.c_str());
if (!appId.IsValid()) {
return INVALID_ARGUMENT;
}
return StoreFactory::GetInstance().Close(appId, { "" }, true);
}
Status StoreManager::GetStoreIds(const AppId &appId, std::vector<StoreId> &storeIds)
{
ZLOGD("appId:%{public}s", appId.appId.c_str());
if (!appId.IsValid()) {
return INVALID_ARGUMENT;
}
auto service = KVDBServiceClient::GetInstance();
if (service == nullptr) {
return SERVER_UNAVAILABLE;
}
return service->GetStoreIds(appId, storeIds);
}
Status StoreManager::Delete(const AppId &appId, const StoreId &storeId, const std::string &path)
{
ZLOGD("appId:%{public}s, storeId:%{public}s dir:%{public}s", appId.appId.c_str(), storeId.storeId.c_str(),
path.c_str());
if (!appId.IsValid() || !storeId.IsValid()) {
return INVALID_ARGUMENT;
}
auto service = KVDBServiceClient::GetInstance();
if (service != nullptr) {
service->Delete(appId, storeId);
}
return StoreFactory::GetInstance().Delete(appId, storeId, path);
}
} // namespace OHOS::DistributedKv

View File

@ -1,199 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "StoreResultSet"
#include "store_result_set.h"
#include "log_print.h"
#include "store_util.h"
namespace OHOS::DistributedKv {
StoreResultSet::StoreResultSet(DBResultSet *impl, std::shared_ptr<DBStore> dbStore, const Convertor &convert)
: impl_(impl), dbStore_(std::move(dbStore)), convert_(convert)
{
}
StoreResultSet::~StoreResultSet()
{
if (impl_ != nullptr && dbStore_ != nullptr) {
dbStore_->CloseResultSet(impl_);
impl_ = nullptr;
}
}
int StoreResultSet::GetCount() const
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return INVALID_COUNT;
}
return impl_->GetCount();
}
int StoreResultSet::GetPosition() const
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return INVALID_POSITION;
}
return impl_->GetPosition();
}
bool StoreResultSet::MoveToFirst()
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return false;
}
return impl_->MoveToFirst();
}
bool StoreResultSet::MoveToLast()
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return false;
}
return impl_->MoveToLast();
}
bool StoreResultSet::MoveToNext()
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return false;
}
return impl_->MoveToNext();
}
bool StoreResultSet::MoveToPrevious()
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return false;
}
return impl_->MoveToPrevious();
}
bool StoreResultSet::Move(int offset)
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return false;
}
return impl_->Move(offset);
}
bool StoreResultSet::MoveToPosition(int position)
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return false;
}
return impl_->MoveToPosition(position);
}
bool StoreResultSet::IsFirst() const
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return false;
}
return impl_->IsFirst();
}
bool StoreResultSet::IsLast() const
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return false;
}
return impl_->IsLast();
}
bool StoreResultSet::IsBeforeFirst() const
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return false;
}
return impl_->IsBeforeFirst();
}
bool StoreResultSet::IsAfterLast() const
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return false;
}
return impl_->IsAfterLast();
}
Status StoreResultSet::GetEntry(Entry &entry) const
{
std::shared_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr) {
ZLOGW("already closed");
return ALREADY_CLOSED;
}
DBEntry dbEntry;
auto dbStatus = impl_->GetEntry(dbEntry);
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status != SUCCESS) {
ZLOGE("failed! status:%{public}d, position:%{public}d", status, impl_->GetPosition());
return status;
}
std::string deviceId;
entry.key = convert_.ToKey(std::move(dbEntry.key), deviceId);
entry.value = std::move(dbEntry.value);
return SUCCESS;
}
Status StoreResultSet::Close()
{
std::unique_lock<decltype(mutex_)> lock(mutex_);
if (impl_ == nullptr || dbStore_ == nullptr) {
return SUCCESS;
}
auto dbStatus = dbStore_->CloseResultSet(impl_);
auto status = StoreUtil::ConvertStatus(dbStatus);
if (status == SUCCESS) {
impl_ = nullptr;
dbStore_ = nullptr;
}
return status;
}
} // namespace OHOS::DistributedKv

View File

@ -1,258 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "StoreUtil"
#include "store_util.h"
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include "log_print.h"
#include "types.h"
namespace OHOS::DistributedKv {
constexpr mode_t DEFAULT_UMASK = 0002;
constexpr int32_t HEAD_SIZE = 3;
constexpr int32_t END_SIZE = 3;
constexpr int32_t MIN_SIZE = HEAD_SIZE + END_SIZE + 3;
constexpr const char *REPLACE_CHAIN = "***";
constexpr const char *DEFAULT_ANONYMOUS = "******";
StoreUtil::DBSecurity StoreUtil::GetDBSecurity(int32_t secLevel)
{
if (secLevel < SecurityLevel::NO_LABEL || secLevel > SecurityLevel::S4) {
return { DistributedDB::NOT_SET, DistributedDB::ECE };
}
if (secLevel == SecurityLevel::S3) {
return { DistributedDB::S3, DistributedDB::SECE };
}
if (secLevel == SecurityLevel::S4) {
return { DistributedDB::S4, DistributedDB::ECE };
}
return { secLevel, DistributedDB::ECE };
}
int32_t StoreUtil::GetSecLevel(StoreUtil::DBSecurity dbSec)
{
switch (dbSec.securityLabel) {
case DistributedDB::NOT_SET: // fallthrough
case DistributedDB::S0: // fallthrough
case DistributedDB::S1: // fallthrough
case DistributedDB::S2: // fallthrough
return dbSec.securityLabel;
case DistributedDB::S3:
return dbSec.securityFlag ? S3 : S3_EX;
case DistributedDB::S4:
return S4;
default:
break;
}
return NO_LABEL;
}
StoreUtil::DBMode StoreUtil::GetDBMode(SyncMode syncMode)
{
DBMode dbMode;
if (syncMode == SyncMode::PUSH) {
dbMode = DBMode::SYNC_MODE_PUSH_ONLY;
} else if (syncMode == SyncMode::PULL) {
dbMode = DBMode::SYNC_MODE_PULL_ONLY;
} else {
dbMode = DBMode::SYNC_MODE_PUSH_PULL;
}
return dbMode;
}
uint32_t StoreUtil::GetObserverMode(SubscribeType subType)
{
uint32_t mode;
if (subType == SubscribeType::SUBSCRIBE_TYPE_LOCAL) {
mode = DistributedDB::OBSERVER_CHANGES_NATIVE;
} else if (subType == SubscribeType::SUBSCRIBE_TYPE_REMOTE) {
mode = DistributedDB::OBSERVER_CHANGES_FOREIGN;
} else {
mode = DistributedDB::OBSERVER_CHANGES_FOREIGN | DistributedDB::OBSERVER_CHANGES_NATIVE;
}
return mode;
}
std::string StoreUtil::Anonymous(const std::string &name)
{
if (name.length() <= HEAD_SIZE) {
return DEFAULT_ANONYMOUS;
}
if (name.length() < MIN_SIZE) {
return (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN);
}
return (name.substr(0, HEAD_SIZE) + REPLACE_CHAIN + name.substr(name.length() - END_SIZE, END_SIZE));
}
uint32_t StoreUtil::Anonymous(const void *ptr)
{
uint32_t hash = (uintptr_t(ptr) & 0xFFFFFFFF);
hash = (hash & 0xFFFF) ^ ((hash >> 16) & 0xFFFF);
return hash;
}
Status StoreUtil::ConvertStatus(DBStatus status)
{
switch (status) {
case DBStatus::BUSY: // fallthrough
case DBStatus::DB_ERROR:
return Status::DB_ERROR;
case DBStatus::OK:
return Status::SUCCESS;
case DBStatus::INVALID_ARGS:
return Status::INVALID_ARGUMENT;
case DBStatus::NOT_FOUND:
return Status::NOT_FOUND;
case DBStatus::INVALID_VALUE_FIELDS:
return Status::INVALID_VALUE_FIELDS;
case DBStatus::INVALID_FIELD_TYPE:
return Status::INVALID_FIELD_TYPE;
case DBStatus::CONSTRAIN_VIOLATION:
return Status::CONSTRAIN_VIOLATION;
case DBStatus::INVALID_FORMAT:
return Status::INVALID_FORMAT;
case DBStatus::INVALID_QUERY_FORMAT:
return Status::INVALID_QUERY_FORMAT;
case DBStatus::INVALID_QUERY_FIELD:
return Status::INVALID_QUERY_FIELD;
case DBStatus::NOT_SUPPORT:
return Status::NOT_SUPPORT;
case DBStatus::TIME_OUT:
return Status::TIME_OUT;
case DBStatus::OVER_MAX_LIMITS:
return Status::OVER_MAX_SUBSCRIBE_LIMITS;
case DBStatus::INVALID_PASSWD_OR_CORRUPTED_DB:
return Status::CRYPT_ERROR;
case DBStatus::SCHEMA_MISMATCH:
return Status::SCHEMA_MISMATCH;
case DBStatus::INVALID_SCHEMA:
return Status::INVALID_SCHEMA;
case DBStatus::EKEYREVOKED_ERROR: // fallthrough
case DBStatus::SECURITY_OPTION_CHECK_ERROR:
return Status::SECURITY_LEVEL_ERROR;
default:
ZLOGE("unknown db error:0x%{public}x", status);
break;
}
return Status::ERROR;
}
bool StoreUtil::InitPath(const std::string &path)
{
if (access(path.c_str(), F_OK) == 0) {
return true;
}
umask(DEFAULT_UMASK);
if (mkdir(path.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)) != 0 && errno != EEXIST) {
ZLOGE("mkdir error:%{public}d, path:%{public}s", errno, path.c_str());
return false;
}
return true;
}
bool StoreUtil::CreateFile(const std::string &name)
{
umask(DEFAULT_UMASK);
int fp = open(name.c_str(), (O_WRONLY | O_CREAT), (S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP));
if (fp < 0) {
ZLOGE("fopen error:%{public}d, path:%{public}s", errno, name.c_str());
return false;
}
close(fp);
return true;
}
std::vector<std::string> StoreUtil::GetSubPath(const std::string &path)
{
std::vector<std::string> subPaths;
DIR *dirp = opendir(path.c_str());
if (dirp == nullptr) {
ZLOGE("opendir error:%{public}d, path:%{public}s", errno, path.c_str());
return subPaths;
}
struct dirent *dp;
while ((dp = readdir(dirp)) != nullptr) {
if (dp->d_type == DT_DIR) {
subPaths.push_back(dp->d_name);
}
}
(void)closedir(dirp);
return subPaths;
}
std::vector<StoreUtil::FileInfo> StoreUtil::GetFiles(const std::string &path)
{
std::vector<FileInfo> fileInfos;
DIR *dirp = opendir(path.c_str());
if (dirp == nullptr) {
ZLOGE("opendir error:%{public}d, path:%{public}s", errno, path.c_str());
return fileInfos;
}
struct dirent *dp;
while ((dp = readdir(dirp)) != nullptr) {
if (dp->d_type == DT_REG) {
struct stat fileStat;
auto fullName = path + "/" + dp->d_name;
stat(fullName.c_str(), &fileStat);
FileInfo fileInfo = { "", 0, 0 };
fileInfo.name = dp->d_name;
fileInfo.modifyTime = fileStat.st_mtim.tv_sec;
fileInfo.size = fileStat.st_size;
fileInfos.push_back(fileInfo);
}
}
closedir(dirp);
return fileInfos;
}
bool StoreUtil::Rename(const std::string &oldName, const std::string &newName)
{
if (oldName.empty() || newName.empty()) {
return false;
}
if (!Remove(newName)) {
return false;
}
if (rename(oldName.c_str(), newName.c_str()) != 0) {
ZLOGE("rename error:%{public}d, file:%{public}s->%{public}s", errno, oldName.c_str(), newName.c_str());
return false;
}
return true;
}
bool StoreUtil::IsFileExist(const std::string &name)
{
if (name.empty()) {
return false;
}
if (access(name.c_str(), F_OK) != 0) {
return false;
}
return true;
}
bool StoreUtil::Remove(const std::string &path)
{
if (access(path.c_str(), F_OK) != 0) {
return true;
}
if (remove(path.c_str()) != 0) {
ZLOGE("remove error:%{public}d, path:%{public}s", errno, path.c_str());
return false;
}
return true;
}
} // namespace OHOS::DistributedKv

View File

@ -1,106 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "SystemApi"
#include "system_api.h"
#include <regex>
#include <sys/stat.h>
#include <unistd.h>
#include "log_print.h"
#include "security_label.h"
#include "store_util.h"
namespace OHOS::DistributedKv {
using Label = DistributedDB::SecurityLabel;
using Flag = DistributedDB::SecurityFlag;
using SecurityLabel = DistributedFS::ModuleSecurityLabel::SecurityLabel;
SystemApi::SystemApi()
{
}
SystemApi::~SystemApi()
{
}
SystemApi::DBStatus SystemApi::RegOnAccessControlledEvent(const AccessEventHanle &callback)
{
return DBStatus::NOT_SUPPORT;
}
bool SystemApi::IsAccessControlled() const
{
return false;
}
SystemApi::DBStatus SystemApi::SetSecurityOption(const std::string &filePath, const DBOption &option)
{
if (filePath.empty() || option.securityLabel < Label::NOT_SET || option.securityLabel > Label::S4) {
return DBStatus::INVALID_ARGS;
}
struct stat curStat;
stat(filePath.c_str(), &curStat);
if (S_ISDIR(curStat.st_mode)) {
return DBStatus::NOT_SUPPORT;
}
if (access(filePath.c_str(), F_OK) != 0) {
return DBStatus::INVALID_ARGS;
}
if (option.securityLabel == Label::NOT_SET) {
return DBStatus::OK;
}
auto secLevel = std::string("s") + std::to_string(option.securityLabel - 1);
bool result = SecurityLabel::SetSecurityLabel(filePath, secLevel);
if (!result) {
ZLOGE("set label failed! level:%{public}s, file:%{public}s", secLevel.c_str(),
StoreUtil::Anonymous(filePath).c_str());
return DBStatus::DB_ERROR;
}
return DBStatus::OK;
}
SystemApi::DBStatus SystemApi::GetSecurityOption(const std::string &filePath, DBOption &option) const
{
if (filePath.empty()) {
return DBStatus::INVALID_ARGS;
}
struct stat curStat;
stat(filePath.c_str(), &curStat);
if (S_ISDIR(curStat.st_mode)) {
return DBStatus::NOT_SUPPORT;
}
if (access(filePath.c_str(), F_OK) != 0) {
option = {Label::NOT_SET, Flag::ECE};
return DBStatus::OK;
}
std::string value = SecurityLabel::GetSecurityLabel(filePath);
if (!std::regex_match(value, std::regex("s([01234])"))) {
option = {Label::NOT_SET, Flag::ECE};
return DBStatus::OK;
}
option = { (value[1] - '0') + 1, value[1] == '3' ? Flag::SECE : Flag::ECE};
return DBStatus::OK;
}
bool SystemApi::CheckDeviceSecurityAbility(const std::string &devId, const DBOption &option) const
{
return false;
}
} // namespace OHOS::DistributedKv

View File

@ -1,82 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 <gtest/gtest.h>
#include "auto_sync_timer.h"
#include "store_manager.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
class AutoSyncTimerTest : public testing::Test {
public:
class TestSyncCallback : public KvStoreSyncCallback {
public:
void SyncCompleted(const std::map<std::string, Status> &results) override
{
ASSERT_TRUE(true);
}
};
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
protected:
static std::shared_ptr<SingleKvStore> kvStore_;
};
std::shared_ptr<SingleKvStore> AutoSyncTimerTest::kvStore_;
void AutoSyncTimerTest::SetUpTestCase(void)
{
mkdir("/data/service/el1/public/database/ut_test", (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH));
Options options;
options.kvStoreType = SINGLE_VERSION;
options.securityLevel = S1;
options.area = EL1;
options.baseDir = "/data/service/el1/public/database/ut_test";
AppId appId = { "ut_test" };
StoreId storeId = { "ut_test_store" };
Status status = StoreManager::GetInstance().Delete(appId, storeId, options.baseDir);
kvStore_ = StoreManager::GetInstance().GetKVStore(appId, storeId, options, status);
ASSERT_EQ(status, SUCCESS);
}
void AutoSyncTimerTest::TearDownTestCase(void)
{
(void)remove("/data/service/el1/public/database/ut_test/key");
(void)remove("/data/service/el1/public/database/ut_test/kvdb");
(void)remove("/data/service/el1/public/database/ut_test");
}
void AutoSyncTimerTest::SetUp(void)
{
}
void AutoSyncTimerTest::TearDown(void)
{
}
/**
* @tc.name: GetStoreId
* @tc.desc: get the store id of the kv store
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(AutoSyncTimerTest, GetStoreId, TestSize.Level0)
{
AutoSyncTimer::GetInstance().DoAutoSync("ut_test", {{"ut_test_store"}});
sleep(3);
ASSERT_TRUE(true);
}

View File

@ -1,95 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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.
*/
#define LOG_TAG "DevManagerTest"
#include <gtest/gtest.h>
#include "dev_manager.h"
#include "types.h"
#include "log_print.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
class DevManagerTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void DevManagerTest::SetUpTestCase(void)
{}
void DevManagerTest::TearDownTestCase(void)
{}
void DevManagerTest::SetUp(void)
{}
void DevManagerTest::TearDown(void)
{}
/**
* @tc.name: GetLocalDevice001
* @tc.desc: Get local device's infomation
* @tc.type: FUNC
* @tc.require:
* @tc.author: taoyuxin
*/
HWTEST_F(DevManagerTest, GetLocalDevice001, TestSize.Level1)
{
ZLOGI("GetLocalDevice001 begin.");
DevManager &devManager = OHOS::DistributedKv::DevManager::GetInstance();
DevManager::DetailInfo devInfo = devManager.GetLocalDevice();
EXPECT_NE(devInfo.networkId, "");
EXPECT_NE(devInfo.uuid, "");
EXPECT_NE(devInfo.udid, "");
}
/**
* @tc.name: ToUUID001
* @tc.desc: Get uuid from networkId
* @tc.type: FUNC
* @tc.require:
* @tc.author: taoyuxin
*/
HWTEST_F(DevManagerTest, ToUUID001, TestSize.Level1)
{
ZLOGI("ToUUID001 begin.");
DevManager &devManager = OHOS::DistributedKv::DevManager::GetInstance();
DevManager::DetailInfo devInfo = devManager.GetLocalDevice();
EXPECT_NE(devInfo.networkId, "");
std::string uuid = devManager.ToUUID(devInfo.networkId);
EXPECT_NE(uuid, "");
EXPECT_EQ(uuid, devInfo.uuid);
}
/**
* @tc.name: GetRemoteDevices001
* @tc.desc: Get remote devices
* @tc.type: FUNC
* @tc.require:
* @tc.author: taoyuxin
*/
HWTEST_F(DevManagerTest, GetRemoteDevices001, TestSize.Level1)
{
ZLOGI("GetRemoteDevices001 begin.");
DevManager &devManager = OHOS::DistributedKv::DevManager::GetInstance();
vector<DevManager::DetailInfo> devInfo = devManager.GetRemoteDevices();
EXPECT_EQ(devInfo.size(), 0);
}

View File

@ -1,681 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 <gtest/gtest.h>
#include <condition_variable>
#include <vector>
#include "dev_manager.h"
#include "store_manager.h"
#include "types.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
class SingleStoreImplTest : public testing::Test {
public:
class TestObserver : public KvStoreObserver {
public:
bool IsChanged()
{
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this]() { return isChanged_; });
bool current = isChanged_;
isChanged_ = false;
cv_.notify_one();
return current;
}
void OnChange(const ChangeNotification &notification) override
{
insert_ = notification.GetInsertEntries();
update_ = notification.GetUpdateEntries();
delete_ = notification.GetDeleteEntries();
deviceId_ = notification.GetDeviceId();
{
std::lock_guard<std::mutex> lock(mutex_);
isChanged_ = true;
cv_.notify_one();
}
}
std::vector<Entry> insert_;
std::vector<Entry> update_;
std::vector<Entry> delete_;
std::string deviceId_;
private:
std::mutex mutex_;
std::condition_variable cv_;
bool isChanged_ = false;
};
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
protected:
std::shared_ptr<SingleKvStore> kvStore_;
};
void SingleStoreImplTest::SetUpTestCase(void)
{
}
void SingleStoreImplTest::TearDownTestCase(void)
{
}
void SingleStoreImplTest::SetUp(void)
{
Options options;
options.kvStoreType = SINGLE_VERSION;
options.securityLevel = S1;
AppId appId = { "LocalSingleKVStore" };
StoreId storeId = { "LocalSingleKVStore" };
std::string path = "";
Status status = StoreManager::GetInstance().Delete(appId, storeId, path);
kvStore_ = StoreManager::GetInstance().GetKVStore(appId, storeId, options, status);
ASSERT_EQ(status, SUCCESS);
}
void SingleStoreImplTest::TearDown(void)
{
AppId appId = { "LocalSingleKVStore" };
StoreId storeId = { "LocalSingleKVStore" };
std::string path = "";
Status status = StoreManager::GetInstance().Delete(appId, storeId, path);
ASSERT_EQ(status, SUCCESS);
}
/**
* @tc.name: GetStoreId
* @tc.desc: get the store id of the kv store
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, GetStoreId, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
auto storeId = kvStore_->GetStoreId();
ASSERT_EQ(storeId.storeId, "LocalSingleKVStore");
}
/**
* @tc.name: Put
* @tc.desc: put key-value data to the kv store
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, Put, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
auto status = kvStore_->Put({ "Put Test" }, { "Put Value" });
ASSERT_EQ(status, SUCCESS);
status = kvStore_->Put({ " Put Test" }, { "Put2 Value" });
ASSERT_EQ(status, SUCCESS);
Value value;
status = kvStore_->Get({ "Put Test" }, value);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(value.ToString(), "Put2 Value");
}
/**
* @tc.name: PutBatch
* @tc.desc: put some key-value data to the kv store
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, PutBatch, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
std::vector<Entry> entries;
for (int i = 0; i < 10; ++i) {
Entry entry;
entry.key = std::to_string(i).append("_k");
entry.value = std::to_string(i).append("_v");
entries.push_back(entry);
}
auto status = kvStore_->PutBatch(entries);
ASSERT_EQ(status, SUCCESS);
}
/**
* @tc.name: Delete
* @tc.desc: delete the value of the key
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, Delete, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
auto status = kvStore_->Put({ "Put Test" }, { "Put Value" });
ASSERT_EQ(status, SUCCESS);
Value value;
status = kvStore_->Get({ "Put Test" }, value);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(std::string("Put Value"), value.ToString());
status = kvStore_->Delete({ "Put Test" });
ASSERT_EQ(status, SUCCESS);
value = {};
status = kvStore_->Get({ "Put Test" }, value);
ASSERT_EQ(status, KEY_NOT_FOUND);
ASSERT_EQ(std::string(""), value.ToString());
}
/**
* @tc.name: DeleteBatch
* @tc.desc: delete the values of the keys
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, DeleteBatch, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
std::vector<Entry> entries;
for (int i = 0; i < 10; ++i) {
Entry entry;
entry.key = std::to_string(i).append("_k");
entry.value = std::to_string(i).append("_v");
entries.push_back(entry);
}
auto status = kvStore_->PutBatch(entries);
ASSERT_EQ(status, SUCCESS);
std::vector<Key> keys;
for (int i = 0; i < 10; ++i) {
Key key = std::to_string(i).append("_k");
keys.push_back(key);
}
status = kvStore_->DeleteBatch(keys);
ASSERT_EQ(status, SUCCESS);
for (int i = 0; i < 10; ++i) {
Value value;
status = kvStore_->Get(keys[i], value);
ASSERT_EQ(status, KEY_NOT_FOUND);
ASSERT_EQ(value.ToString(), std::string(""));
}
}
/**
* @tc.name: Transaction
* @tc.desc: do transaction
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, Transaction, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
auto status = kvStore_->StartTransaction();
ASSERT_EQ(status, SUCCESS);
status = kvStore_->Commit();
ASSERT_EQ(status, SUCCESS);
status = kvStore_->StartTransaction();
ASSERT_EQ(status, SUCCESS);
status = kvStore_->Rollback();
ASSERT_EQ(status, SUCCESS);
}
/**
* @tc.name: SubscribeKvStore
* @tc.desc: subscribe local
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, SubscribeKvStore, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
auto observer = std::make_shared<TestObserver>();
auto status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, observer);
ASSERT_EQ(status, SUCCESS);
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_REMOTE, observer);
ASSERT_EQ(status, SUCCESS);
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, observer);
ASSERT_EQ(status, STORE_ALREADY_SUBSCRIBE);
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_REMOTE, observer);
ASSERT_EQ(status, STORE_ALREADY_SUBSCRIBE);
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_ALL, observer);
ASSERT_EQ(status, STORE_ALREADY_SUBSCRIBE);
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_ALL, observer);
ASSERT_EQ(status, STORE_ALREADY_SUBSCRIBE);
status = kvStore_->Put({ "Put Test" }, { "Put Value" });
ASSERT_EQ(status, SUCCESS);
ASSERT_TRUE(observer->IsChanged());
ASSERT_EQ(observer->insert_.size(), 1);
ASSERT_EQ(observer->update_.size(), 0);
ASSERT_EQ(observer->delete_.size(), 0);
status = kvStore_->Put({ "Put Test" }, { "Put Value1" });
ASSERT_EQ(status, SUCCESS);
ASSERT_TRUE(observer->IsChanged());
ASSERT_EQ(observer->insert_.size(), 0);
ASSERT_EQ(observer->update_.size(), 1);
ASSERT_EQ(observer->delete_.size(), 0);
status = kvStore_->Delete({ "Put Test" });
ASSERT_EQ(status, SUCCESS);
ASSERT_TRUE(observer->IsChanged());
ASSERT_EQ(observer->insert_.size(), 0);
ASSERT_EQ(observer->update_.size(), 0);
ASSERT_EQ(observer->delete_.size(), 1);
}
/**
* @tc.name: SubscribeKvStore002
* @tc.desc: subscribe local
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Hollokin
*/
HWTEST_F(SingleStoreImplTest, SubscribeKvStore002, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
std::shared_ptr<TestObserver> subscribedObserver;
std::shared_ptr<TestObserver> unSubscribedObserver;
for (int i = 0; i < 15; ++i) {
auto observer = std::make_shared<TestObserver>();
auto status1 = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, observer);
auto status2 = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_REMOTE, observer);
if (i < 8) {
ASSERT_EQ(status1, SUCCESS);
ASSERT_EQ(status2, SUCCESS);
subscribedObserver = observer;
} else {
ASSERT_EQ(status1, OVER_MAX_SUBSCRIBE_LIMITS);
ASSERT_EQ(status2, OVER_MAX_SUBSCRIBE_LIMITS);
unSubscribedObserver = observer;
}
}
auto status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, subscribedObserver);
ASSERT_EQ(status, STORE_ALREADY_SUBSCRIBE);
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, {});
ASSERT_EQ(status, INVALID_ARGUMENT);
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_REMOTE, subscribedObserver);
ASSERT_EQ(status, STORE_ALREADY_SUBSCRIBE);
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_ALL, subscribedObserver);
ASSERT_EQ(status, STORE_ALREADY_SUBSCRIBE);
status = kvStore_->UnSubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, subscribedObserver);
ASSERT_EQ(status, SUCCESS);
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, subscribedObserver);
ASSERT_EQ(status, SUCCESS);
status = kvStore_->UnSubscribeKvStore(SUBSCRIBE_TYPE_ALL, subscribedObserver);
ASSERT_EQ(status, SUCCESS);
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, unSubscribedObserver);
ASSERT_EQ(status, SUCCESS);
subscribedObserver = unSubscribedObserver;
status = kvStore_->UnSubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, subscribedObserver);
ASSERT_EQ(status, SUCCESS);
auto observer = std::make_shared<TestObserver>();
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, observer);
ASSERT_EQ(status, SUCCESS);
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_ALL, observer);
ASSERT_EQ(status, SUCCESS);
observer = std::make_shared<TestObserver>();
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_ALL, observer);
ASSERT_EQ(status, OVER_MAX_SUBSCRIBE_LIMITS);
}
/**
* @tc.name: UnsubscribeKvStore
* @tc.desc: unsubscribe
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, UnsubscribeKvStore, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
auto observer = std::make_shared<TestObserver>();
auto status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_ALL, observer);
ASSERT_EQ(status, SUCCESS);
status = kvStore_->UnSubscribeKvStore(SUBSCRIBE_TYPE_REMOTE, observer);
ASSERT_EQ(status, SUCCESS);
status = kvStore_->UnSubscribeKvStore(SUBSCRIBE_TYPE_REMOTE, observer);
ASSERT_EQ(status, STORE_NOT_SUBSCRIBE);
status = kvStore_->UnSubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, observer);
ASSERT_EQ(status, SUCCESS);
status = kvStore_->UnSubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, observer);
ASSERT_EQ(status, STORE_NOT_SUBSCRIBE);
status = kvStore_->UnSubscribeKvStore(SUBSCRIBE_TYPE_ALL, observer);
ASSERT_EQ(status, STORE_NOT_SUBSCRIBE);
status = kvStore_->SubscribeKvStore(SUBSCRIBE_TYPE_LOCAL, observer);
ASSERT_EQ(status, SUCCESS);
status = kvStore_->UnSubscribeKvStore(SUBSCRIBE_TYPE_ALL, observer);
ASSERT_EQ(status, SUCCESS);
}
/**
* @tc.name: GetEntries
* @tc.desc: get entries by prefix
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, GetEntries_Prefix, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
std::vector<Entry> input;
for (int i = 0; i < 10; ++i) {
Entry entry;
entry.key = std::to_string(i).append("_k");
entry.value = std::to_string(i).append("_v");
input.push_back(entry);
}
auto status = kvStore_->PutBatch(input);
ASSERT_EQ(status, SUCCESS);
std::vector<Entry> output;
status = kvStore_->GetEntries({ "" }, output);
ASSERT_EQ(status, SUCCESS);
std::sort(output.begin(), output.end(),
[](const Entry &entry, const Entry &sentry) { return entry.key.Data() < sentry.key.Data(); });
for (int i = 0; i < 10; ++i) {
ASSERT_TRUE(input[i].key == output[i].key);
ASSERT_TRUE(input[i].value == output[i].value);
}
}
/**
* @tc.name: GetEntries
* @tc.desc: get entries by query
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, GetEntries_DataQuery, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
std::vector<Entry> input;
for (int i = 0; i < 10; ++i) {
Entry entry;
entry.key = std::to_string(i).append("_k");
entry.value = std::to_string(i).append("_v");
input.push_back(entry);
}
auto status = kvStore_->PutBatch(input);
ASSERT_EQ(status, SUCCESS);
DataQuery query;
query.InKeys({"0_k", "1_k"});
std::vector<Entry> output;
status = kvStore_->GetEntries(query, output);
ASSERT_EQ(status, SUCCESS);
std::sort(output.begin(), output.end(),
[](const Entry &entry, const Entry &sentry) { return entry.key.Data() < sentry.key.Data(); });
ASSERT_LE(output.size(), 2);
for (size_t i = 0; i < output.size(); ++i) {
ASSERT_TRUE(input[i].key == output[i].key);
ASSERT_TRUE(input[i].value == output[i].value);
}
}
/**
* @tc.name: GetResultSet
* @tc.desc: get result set by prefix
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, GetResultSet_Prefix, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
std::vector<Entry> input;
auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); };
std::map<Key, Value, decltype(cmp)> dictionary(cmp);
for (int i = 0; i < 10; ++i) {
Entry entry;
entry.key = std::to_string(i).append("_k");
entry.value = std::to_string(i).append("_v");
dictionary[entry.key] = entry.value;
input.push_back(entry);
}
auto status = kvStore_->PutBatch(input);
ASSERT_EQ(status, SUCCESS);
std::shared_ptr<KvStoreResultSet> output;
status = kvStore_->GetResultSet({ "" }, output);
ASSERT_EQ(status, SUCCESS);
ASSERT_NE(output, nullptr);
ASSERT_EQ(output->GetCount(), 10);
int count = 0;
while (output->MoveToNext()) {
count++;
Entry entry;
output->GetEntry(entry);
ASSERT_EQ(entry.value.Data(), dictionary[entry.key].Data());
}
ASSERT_EQ(count, output->GetCount());
}
/**
* @tc.name: GetResultSet
* @tc.desc: get result set by query
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, GetResultSet_Query, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
std::vector<Entry> input;
auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); };
std::map<Key, Value, decltype(cmp)> dictionary(cmp);
for (int i = 0; i < 10; ++i) {
Entry entry;
entry.key = std::to_string(i).append("_k");
entry.value = std::to_string(i).append("_v");
dictionary[entry.key] = entry.value;
input.push_back(entry);
}
auto status = kvStore_->PutBatch(input);
ASSERT_EQ(status, SUCCESS);
DataQuery query;
query.InKeys({"0_k", "1_k"});
std::shared_ptr<KvStoreResultSet> output;
status = kvStore_->GetResultSet(query, output);
ASSERT_EQ(status, SUCCESS);
ASSERT_NE(output, nullptr);
ASSERT_LE(output->GetCount(), 2);
int count = 0;
while (output->MoveToNext()) {
count++;
Entry entry;
output->GetEntry(entry);
ASSERT_EQ(entry.value.Data(), dictionary[entry.key].Data());
}
ASSERT_EQ(count, output->GetCount());
}
/**
* @tc.name: CloseResultSet
* @tc.desc: close the result set
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, CloseResultSet, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
std::vector<Entry> input;
auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); };
std::map<Key, Value, decltype(cmp)> dictionary(cmp);
for (int i = 0; i < 10; ++i) {
Entry entry;
entry.key = std::to_string(i).append("_k");
entry.value = std::to_string(i).append("_v");
dictionary[entry.key] = entry.value;
input.push_back(entry);
}
auto status = kvStore_->PutBatch(input);
ASSERT_EQ(status, SUCCESS);
DataQuery query;
query.InKeys({"0_k", "1_k"});
std::shared_ptr<KvStoreResultSet> output;
status = kvStore_->GetResultSet(query, output);
ASSERT_EQ(status, SUCCESS);
ASSERT_NE(output, nullptr);
ASSERT_LE(output->GetCount(), 2);
auto outputTmp = output;
status = kvStore_->CloseResultSet(output);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(output, nullptr);
ASSERT_EQ(outputTmp->GetCount(), KvStoreResultSet::INVALID_COUNT);
ASSERT_EQ(outputTmp->GetPosition(), KvStoreResultSet::INVALID_POSITION);
ASSERT_EQ(outputTmp->MoveToFirst(), false);
ASSERT_EQ(outputTmp->MoveToLast(), false);
ASSERT_EQ(outputTmp->MoveToNext(), false);
ASSERT_EQ(outputTmp->MoveToPrevious(), false);
ASSERT_EQ(outputTmp->Move(1), false);
ASSERT_EQ(outputTmp->MoveToPosition(1), false);
ASSERT_EQ(outputTmp->IsFirst(), false);
ASSERT_EQ(outputTmp->IsLast(), false);
ASSERT_EQ(outputTmp->IsBeforeFirst(), false);
ASSERT_EQ(outputTmp->IsAfterLast(), false);
Entry entry;
ASSERT_EQ(outputTmp->GetEntry(entry), ALREADY_CLOSED);
}
/**
* @tc.name: GetCount
* @tc.desc: close the result set
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, GetCount, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
std::vector<Entry> input;
auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); };
std::map<Key, Value, decltype(cmp)> dictionary(cmp);
for (int i = 0; i < 10; ++i) {
Entry entry;
entry.key = std::to_string(i).append("_k");
entry.value = std::to_string(i).append("_v");
dictionary[entry.key] = entry.value;
input.push_back(entry);
}
auto status = kvStore_->PutBatch(input);
ASSERT_EQ(status, SUCCESS);
DataQuery query;
query.InKeys({"0_k", "1_k"});
int count = 0;
status = kvStore_->GetCount(query, count);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(count, 2);
query.Reset();
status = kvStore_->GetCount(query, count);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(count, 10);
}
/**
* @tc.name: RemoveDeviceData
* @tc.desc: remove local device data
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, RemoveDeviceData, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
std::vector<Entry> input;
auto cmp = [](const Key &entry, const Key &sentry) { return entry.Data() < sentry.Data(); };
std::map<Key, Value, decltype(cmp)> dictionary(cmp);
for (int i = 0; i < 10; ++i) {
Entry entry;
entry.key = std::to_string(i).append("_k");
entry.value = std::to_string(i).append("_v");
dictionary[entry.key] = entry.value;
input.push_back(entry);
}
auto status = kvStore_->PutBatch(input);
ASSERT_EQ(status, SUCCESS);
int count = 0;
status = kvStore_->GetCount({}, count);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(count, 10);
status = kvStore_->RemoveDeviceData(DevManager::GetInstance().GetLocalDevice().uuid);
ASSERT_EQ(status, SUCCESS);
status = kvStore_->GetCount({}, count);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(count, 0);
}
/**
* @tc.name: RemoveDeviceData
* @tc.desc: remove local device data
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, GetSecurityLevel, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
SecurityLevel securityLevel = NO_LABEL;
auto status = kvStore_->GetSecurityLevel(securityLevel);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(securityLevel, S1);
}
/**
* @tc.name: RegisterSyncCallback
* @tc.desc: register the data sync callback
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, RegisterSyncCallback, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
class TestSyncCallback : public KvStoreSyncCallback {
public:
void SyncCompleted(const map<std::string, Status> &results) override
{
}
};
auto callback = std::make_shared<TestSyncCallback>();
auto status = kvStore_->RegisterSyncCallback(callback);
ASSERT_EQ(status, SUCCESS);
}
/**
* @tc.name: UnRegisterSyncCallback
* @tc.desc: unregister the data sync callback
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(SingleStoreImplTest, UnRegisterSyncCallback, TestSize.Level0)
{
ASSERT_NE(kvStore_, nullptr);
class TestSyncCallback : public KvStoreSyncCallback {
public:
void SyncCompleted(const map<std::string, Status> &results) override
{
}
};
auto callback = std::make_shared<TestSyncCallback>();
auto status = kvStore_->RegisterSyncCallback(callback);
ASSERT_EQ(status, SUCCESS);
status = kvStore_->UnRegisterSyncCallback();
ASSERT_EQ(status, SUCCESS);
}

View File

@ -1,188 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 <gtest/gtest.h>
#include "distributed_kv_data_manager.h"
using namespace testing::ext;
using namespace OHOS::DistributedKv;
class UpgradeTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
protected:
static const AppId appId_;
static const StoreId storeId_;
static constexpr const char *APP_DIR = "/data/service/el1/public/database/ut_test";
static constexpr const char *KEY_DIR = "/data/service/el1/public/database/ut_test/key";
static constexpr const char *DB_DIR = "/data/service/el1/public/database/ut_test/kvdb";
};
const AppId UpgradeTest::appId_ = { "ut_test" };
const StoreId UpgradeTest::storeId_ = { "ut_test_store" };
void UpgradeTest::SetUpTestCase(void)
{
mkdir(APP_DIR, (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH));
}
void UpgradeTest::TearDownTestCase(void)
{
(void)remove(KEY_DIR);
(void)remove(DB_DIR);
(void)remove(APP_DIR);
}
void UpgradeTest::SetUp(void)
{
DistributedKvDataManager manager;
manager.DeleteKvStore(appId_, storeId_);
manager.DeleteKvStore(appId_, storeId_, APP_DIR);
}
void UpgradeTest::TearDown(void)
{
DistributedKvDataManager manager;
manager.DeleteKvStore(appId_, storeId_);
manager.DeleteKvStore(appId_, storeId_, APP_DIR);
}
/**
* @tc.name: Upgrade
* @tc.desc: upgrade normal kv store
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(UpgradeTest, Upgrade, TestSize.Level0)
{
Options options;
options.kvStoreType = SINGLE_VERSION;
options.securityLevel = S1;
DistributedKvDataManager manager;
std::shared_ptr<SingleKvStore> kvStore;
auto status = manager.GetSingleKvStore(options, appId_, storeId_, kvStore);
ASSERT_EQ(status, SUCCESS);
status = kvStore->Put("upgrade test", "upgrade value");
ASSERT_EQ(status, SUCCESS);
status = manager.CloseKvStore(appId_, kvStore);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(kvStore, nullptr);
options.area = EL1;
options.baseDir = "/data/service/el1/public/database/ut_test";
status = manager.GetSingleKvStore(options, appId_, storeId_, kvStore);
ASSERT_EQ(status, SUCCESS);
Value value;
status = kvStore->Get("upgrade test", value);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(value.ToString(), std::string("upgrade value"));
}
/**
* @tc.name: UpgradeEncrypt
* @tc.desc: upgrade encrypt kv store
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(UpgradeTest, UpgradeEncrypt, TestSize.Level0)
{
Options options;
options.encrypt = true;
options.kvStoreType = SINGLE_VERSION;
options.securityLevel = S1;
DistributedKvDataManager manager;
std::shared_ptr<SingleKvStore> kvStore;
auto status = manager.GetSingleKvStore(options, appId_, storeId_, kvStore);
ASSERT_EQ(status, SUCCESS);
status = kvStore->Put("upgrade test", "upgrade value");
ASSERT_EQ(status, SUCCESS);
status = manager.CloseKvStore(appId_, kvStore);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(kvStore, nullptr);
options.area = EL1;
options.baseDir = "/data/service/el1/public/database/ut_test";
status = manager.GetSingleKvStore(options, appId_, storeId_, kvStore);
ASSERT_EQ(status, SUCCESS);
Value value;
status = kvStore->Get("upgrade test", value);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(value.ToString(), std::string("upgrade value"));
}
/**
* @tc.name: Rollback
* @tc.desc: rollback normal kv store
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(UpgradeTest, Rollback, TestSize.Level0)
{
Options options;
options.kvStoreType = SINGLE_VERSION;
options.securityLevel = S1;
options.area = EL1;
options.baseDir = "/data/service/el1/public/database/ut_test";
DistributedKvDataManager manager;
std::shared_ptr<SingleKvStore> kvStore;
auto status = manager.GetSingleKvStore(options, appId_, storeId_, kvStore);
ASSERT_EQ(status, SUCCESS);
status = kvStore->Put("rollback test", "rollback value");
ASSERT_EQ(status, SUCCESS);
status = manager.CloseKvStore(appId_, kvStore);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(kvStore, nullptr);
options.area = EL1;
options.baseDir = "";
status = manager.GetSingleKvStore(options, appId_, storeId_, kvStore);
ASSERT_EQ(status, SUCCESS);
Value value;
status = kvStore->Get("rollback test", value);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(value.ToString(), std::string("rollback value"));
}
/**
* @tc.name: RollbackEncrypt
* @tc.desc: rollback encrypt kv store
* @tc.type: FUNC
* @tc.require: I4XVQQ
* @tc.author: Sven Wang
*/
HWTEST_F(UpgradeTest, RollbackEncrypt, TestSize.Level0)
{
Options options;
options.kvStoreType = SINGLE_VERSION;
options.securityLevel = S1;
options.area = EL1;
options.baseDir = "/data/service/el1/public/database/ut_test";
DistributedKvDataManager manager;
std::shared_ptr<SingleKvStore> kvStore;
auto status = manager.GetSingleKvStore(options, appId_, storeId_, kvStore);
ASSERT_EQ(status, SUCCESS);
status = kvStore->Put("rollback test", "rollback value");
ASSERT_EQ(status, SUCCESS);
status = manager.CloseKvStore(appId_, kvStore);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(kvStore, nullptr);
options.area = EL1;
options.baseDir = "";
status = manager.GetSingleKvStore(options, appId_, storeId_, kvStore);
ASSERT_EQ(status, SUCCESS);
Value value;
status = kvStore->Get("rollback test", value);
ASSERT_EQ(status, SUCCESS);
ASSERT_EQ(value.ToString(), std::string("rollback value"));
}

View File

@ -1,93 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 I_OBJECT_CALLBACK_H
#define I_OBJECT_CALLBACK_H
#include <map>
#include "iremote_broker.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
#include "types.h"
namespace OHOS {
namespace DistributedObject {
using namespace DistributedKv;
class IObjectSaveCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedObject.IObjectSaveCallback");
virtual void Completed(const std::map<std::string, int32_t> &results) = 0;
};
class ObjectSaveCallbackStub : public IRemoteStub<IObjectSaveCallback> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
};
class ObjectSaveCallbackProxy : public IRemoteProxy<IObjectSaveCallback> {
public:
explicit ObjectSaveCallbackProxy(const sptr<IRemoteObject> &impl);
~ObjectSaveCallbackProxy() = default;
void Completed(const std::map<std::string, int32_t> &results) override;
private:
static inline BrokerDelegator<ObjectSaveCallbackProxy> delegator_;
};
class IObjectRevokeSaveCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedObject.IObjectRevokeSaveCallback");
virtual void Completed(int32_t status) = 0;
};
class ObjectRevokeSaveCallbackStub : public IRemoteStub<IObjectRevokeSaveCallback> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
};
class ObjectRevokeSaveCallbackProxy : public IRemoteProxy<IObjectRevokeSaveCallback> {
public:
explicit ObjectRevokeSaveCallbackProxy(const sptr<IRemoteObject> &impl);
~ObjectRevokeSaveCallbackProxy() = default;
void Completed(int32_t status) override;
private:
static inline BrokerDelegator<ObjectRevokeSaveCallbackProxy> delegator_;
};
class IObjectRetrieveCallback : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedObject.IObjectRetrieveCallback");
virtual void Completed(const std::map<std::string, std::vector<uint8_t>> &results) = 0;
};
class ObjectRetrieveCallbackStub : public IRemoteStub<IObjectRetrieveCallback> {
public:
int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
};
class ObjectRetrieveCallbackProxy : public IRemoteProxy<IObjectRetrieveCallback> {
public:
explicit ObjectRetrieveCallbackProxy(const sptr<IRemoteObject> &impl);
~ObjectRetrieveCallbackProxy() = default;
void Completed(const std::map<std::string, std::vector<uint8_t>> &results) override;
private:
static inline BrokerDelegator<ObjectRetrieveCallbackProxy> delegator_;
};
} // namespace DistributedKv
} // namespace OHOS
#endif // I_KVSTORE_SYNC_CALLBACK_H

View File

@ -1,36 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 DISTRIBUTEDDATAFWK_IOBJECT_SERVICE_H
#define DISTRIBUTEDDATAFWK_IOBJECT_SERVICE_H
#include <string>
#include <iremote_broker.h>
#include "object_service.h"
namespace OHOS::DistributedObject {
class IObjectService : public ObjectService, public IRemoteBroker {
public:
enum {
OBJECTSTORE_SAVE,
OBJECTSTORE_REVOKE_SAVE,
OBJECTSTORE_RETRIEVE,
OBJECTSTORE_SERVICE_CMD_MAX
};
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedObject.IObjectService");
};
} // namespace OHOS::DistributedRdb
#endif

View File

@ -1,36 +0,0 @@
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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 DISTRIBUTED_OBJECT_SERVICE_H
#define DISTRIBUTED_OBJECT_SERVICE_H
#include <map>
#include <string>
#include <vector>
#include "iobject_callback.h"
namespace OHOS::DistributedObject {
class ObjectService {
public:
virtual int32_t ObjectStoreSave(const std::string &bundleName, const std::string &sessionId,
const std::string &deviceId, const std::map<std::string, std::vector<uint8_t>> &data,
sptr<IObjectSaveCallback> callback) = 0;
virtual int32_t ObjectStoreRetrieve(
const std::string &bundleName, const std::string &sessionId, sptr<IObjectRetrieveCallback> callback) = 0;
virtual int32_t ObjectStoreRevokeSave(
const std::string &bundleName, const std::string &sessionId, sptr<IObjectRevokeSaveCallback> callback) = 0;
};
} // namespace OHOS::DistributedObject
#endif

Some files were not shown because too many files have changed in this diff Show More