1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "storage_engine.h"
17
18 #include <algorithm>
19
20 #include "db_common.h"
21 #include "db_errno.h"
22 #include "log_print.h"
23
24 namespace DistributedDB {
25 const int StorageEngine::MAX_WAIT_TIME = 30;
26 const int StorageEngine::MAX_WRITE_SIZE = 1;
27 const int StorageEngine::MAX_READ_SIZE = 16;
28
StorageEngine()29 StorageEngine::StorageEngine()
30 : isUpdated_(false),
31 isMigrating_(false),
32 engineState_(EngineState::INVALID),
33 commitNotifyFunc_(nullptr),
34 isInitialized_(false),
35 perm_(OperatePerm::NORMAL_PERM),
36 operateAbort_(false),
37 isExistConnection_(false)
38 {}
39
~StorageEngine()40 StorageEngine::~StorageEngine()
41 {
42 CloseExecutor();
43 }
44
InitReadWriteExecutors()45 int StorageEngine::InitReadWriteExecutors()
46 {
47 int errCode = E_OK;
48 std::scoped_lock initLock(writeMutex_, readMutex_);
49 // only for create the database avoid the minimum number is 0.
50 StorageExecutor *handle = nullptr;
51 if (engineAttr_.minReadNum == 0 && engineAttr_.minWriteNum == 0) {
52 errCode = CreateNewExecutor(true, handle);
53 if (errCode != E_OK) {
54 return errCode;
55 }
56
57 if (handle != nullptr) {
58 delete handle;
59 handle = nullptr;
60 }
61 }
62
63 for (uint32_t i = 0; i < engineAttr_.minWriteNum; i++) {
64 handle = nullptr;
65 errCode = CreateNewExecutor(true, handle);
66 if (errCode != E_OK) {
67 return errCode;
68 }
69 AddStorageExecutor(handle);
70 }
71
72 for (uint32_t i = 0; i < engineAttr_.minReadNum; i++) {
73 handle = nullptr;
74 errCode = CreateNewExecutor(false, handle);
75 if (errCode != E_OK) {
76 return errCode;
77 }
78 AddStorageExecutor(handle);
79 }
80 return E_OK;
81 }
82
83
Init()84 int StorageEngine::Init()
85 {
86 if (isInitialized_.load()) {
87 LOGD("Storage engine has been initialized!");
88 return E_OK;
89 }
90
91 int errCode = InitReadWriteExecutors();
92 if (errCode == E_OK) {
93 isInitialized_.store(true);
94 initCondition_.notify_all();
95 return E_OK;
96 } else if (errCode == -E_EKEYREVOKED) {
97 // Assumed file system has classification function, can only get one write handle
98 std::unique_lock<std::mutex> lock(writeMutex_);
99 if (!writeIdleList_.empty() || !writeUsingList_.empty()) {
100 isInitialized_.store(true);
101 initCondition_.notify_all();
102 return E_OK;
103 }
104 }
105 initCondition_.notify_all();
106 Release();
107 return errCode;
108 }
109
FindExecutor(bool writable,OperatePerm perm,int & errCode,int waitTime)110 StorageExecutor *StorageEngine::FindExecutor(bool writable, OperatePerm perm, int &errCode, int waitTime)
111 {
112 if (GetEngineState() == EngineState::ENGINE_BUSY) {
113 LOGI("Storage engine is busy!");
114 errCode = -E_BUSY;
115 return nullptr;
116 }
117
118 {
119 std::unique_lock<std::mutex> lock(initMutex_);
120 bool result = initCondition_.wait_for(lock, std::chrono::seconds(waitTime), [this]() {
121 return isInitialized_.load();
122 });
123 if (!result || !isInitialized_.load()) {
124 LOGE("Storage engine is not initialized");
125 errCode = -E_BUSY; // Usually in reinitialize engine, return BUSY
126 return nullptr;
127 }
128 }
129
130 if (writable) {
131 return FindWriteExecutor(perm, errCode, waitTime);
132 }
133
134 return FindReadExecutor(perm, errCode, waitTime);
135 }
136
FindWriteExecutor(OperatePerm perm,int & errCode,int waitTime)137 StorageExecutor *StorageEngine::FindWriteExecutor(OperatePerm perm, int &errCode, int waitTime)
138 {
139 std::unique_lock<std::mutex> lock(writeMutex_);
140 errCode = -E_BUSY;
141 if (perm_ == OperatePerm::DISABLE_PERM || perm_ != perm) {
142 LOGI("Not permitted to get the executor[%u]", static_cast<unsigned>(perm_));
143 return nullptr;
144 }
145 if (waitTime <= 0) { // non-blocking.
146 if (writeIdleList_.empty() &&
147 writeIdleList_.size() + writeUsingList_.size() == engineAttr_.maxWriteNum) {
148 return nullptr;
149 }
150 return FetchStorageExecutor(true, writeIdleList_, writeUsingList_, errCode);
151 }
152
153 // Not prohibited and there is an available handle
154 bool result = writeCondition_.wait_for(lock, std::chrono::seconds(waitTime),
155 [this, &perm]() {
156 return (perm_ == OperatePerm::NORMAL_PERM || perm_ == perm) && (!writeIdleList_.empty() ||
157 (writeIdleList_.size() + writeUsingList_.size() < engineAttr_.maxWriteNum) ||
158 operateAbort_);
159 });
160 if (operateAbort_) {
161 LOGI("Abort write executor and executor and busy for operate!");
162 return nullptr;
163 }
164 if (!result) {
165 LOGI("Get write handle result[%d], permissType[%u], operType[%u], write[%zu-%zu-%" PRIu32 "]", result,
166 static_cast<unsigned>(perm_), static_cast<unsigned>(perm), writeIdleList_.size(), writeUsingList_.size(),
167 engineAttr_.maxWriteNum);
168 return nullptr;
169 }
170 return FetchStorageExecutor(true, writeIdleList_, writeUsingList_, errCode);
171 }
172
FindReadExecutor(OperatePerm perm,int & errCode,int waitTime)173 StorageExecutor *StorageEngine::FindReadExecutor(OperatePerm perm, int &errCode, int waitTime)
174 {
175 std::unique_lock<std::mutex> lock(readMutex_);
176 errCode = -E_BUSY;
177 if (perm_ == OperatePerm::DISABLE_PERM || perm_ != perm) {
178 LOGI("Not permitted to get the executor[%u]", static_cast<unsigned>(perm_));
179 return nullptr;
180 }
181
182 if (waitTime <= 0) { // non-blocking.
183 if (readIdleList_.empty() &&
184 readIdleList_.size() + readUsingList_.size() == engineAttr_.maxReadNum) {
185 return nullptr;
186 }
187 return FetchStorageExecutor(false, readIdleList_, readUsingList_, errCode);
188 }
189
190 // Not prohibited and there is an available handle
191 bool result = readCondition_.wait_for(lock, std::chrono::seconds(waitTime),
192 [this, &perm]() {
193 return (perm_ == OperatePerm::NORMAL_PERM || perm_ == perm) &&
194 (!readIdleList_.empty() || (readIdleList_.size() + readUsingList_.size() < engineAttr_.maxReadNum) ||
195 operateAbort_);
196 });
197 if (operateAbort_) {
198 LOGI("Abort find read executor and busy for operate!");
199 return nullptr;
200 }
201 if (!result) {
202 LOGI("Get read handle result[%d], permissType[%u], operType[%u], read[%zu-%zu-%" PRIu32 "]", result,
203 static_cast<unsigned>(perm_), static_cast<unsigned>(perm), readIdleList_.size(), readUsingList_.size(),
204 engineAttr_.maxReadNum);
205 return nullptr;
206 }
207 return FetchStorageExecutor(false, readIdleList_, readUsingList_, errCode);
208 }
209
Recycle(StorageExecutor * & handle)210 void StorageEngine::Recycle(StorageExecutor *&handle)
211 {
212 if (handle == nullptr) {
213 return;
214 }
215 std::string id = DBCommon::TransferStringToHex(identifier_);
216 LOGD("Recycle executor[%d] for id[%.6s]", handle->GetWritable(), id.c_str());
217 if (handle->GetWritable()) {
218 std::unique_lock<std::mutex> lock(writeMutex_);
219 auto iter = std::find(writeUsingList_.begin(), writeUsingList_.end(), handle);
220 if (iter != writeUsingList_.end()) {
221 writeUsingList_.remove(handle);
222 if (writeIdleList_.size() >= 1) {
223 delete handle;
224 handle = nullptr;
225 return;
226 }
227 handle->Reset();
228 writeIdleList_.push_back(handle);
229 writeCondition_.notify_one();
230 idleCondition_.notify_all();
231 }
232 } else {
233 std::unique_lock<std::mutex> lock(readMutex_);
234 auto iter = std::find(readUsingList_.begin(), readUsingList_.end(), handle);
235 if (iter != readUsingList_.end()) {
236 readUsingList_.remove(handle);
237 if (readIdleList_.size() >= 1) {
238 delete handle;
239 handle = nullptr;
240 return;
241 }
242 handle->Reset();
243 readIdleList_.push_back(handle);
244 readCondition_.notify_one();
245 }
246 }
247 handle = nullptr;
248 }
249
ClearCorruptedFlag()250 void StorageEngine::ClearCorruptedFlag()
251 {
252 return;
253 }
254
Release()255 void StorageEngine::Release()
256 {
257 CloseExecutor();
258 isInitialized_.store(false);
259 isUpdated_ = false;
260 ClearCorruptedFlag();
261 SetEngineState(EngineState::INVALID);
262 }
263
TryToDisable(bool isNeedCheckAll,OperatePerm disableType)264 int StorageEngine::TryToDisable(bool isNeedCheckAll, OperatePerm disableType)
265 {
266 if (engineState_ != EngineState::MAINDB && engineState_ != EngineState::INVALID) {
267 LOGE("Not support disable handle when cacheDB existed! state = [%d]", engineState_);
268 return(engineState_ == EngineState::CACHEDB) ? -E_NOT_SUPPORT : -E_BUSY;
269 }
270
271 std::lock(writeMutex_, readMutex_);
272 std::lock_guard<std::mutex> writeLock(writeMutex_, std::adopt_lock);
273 std::lock_guard<std::mutex> readLock(readMutex_, std::adopt_lock);
274
275 if (!isNeedCheckAll) {
276 goto END;
277 }
278
279 if (!writeUsingList_.empty() || !readUsingList_.empty()) {
280 LOGE("Database handle used");
281 return -E_BUSY;
282 }
283 END:
284 if (perm_ == OperatePerm::NORMAL_PERM) {
285 LOGI("database is disable for re-build:%d", static_cast<int>(disableType));
286 perm_ = disableType;
287 writeCondition_.notify_all();
288 readCondition_.notify_all();
289 }
290 return E_OK;
291 }
292
Enable(OperatePerm enableType)293 void StorageEngine::Enable(OperatePerm enableType)
294 {
295 std::lock(writeMutex_, readMutex_);
296 std::lock_guard<std::mutex> writeLock(writeMutex_, std::adopt_lock);
297 std::lock_guard<std::mutex> readLock(readMutex_, std::adopt_lock);
298 if (perm_ == enableType) {
299 LOGI("Re-enable the database");
300 perm_ = OperatePerm::NORMAL_PERM;
301 writeCondition_.notify_all();
302 readCondition_.notify_all();
303 }
304 }
305
Abort(OperatePerm enableType)306 void StorageEngine::Abort(OperatePerm enableType)
307 {
308 std::lock(writeMutex_, readMutex_);
309 std::lock_guard<std::mutex> writeLock(writeMutex_, std::adopt_lock);
310 std::lock_guard<std::mutex> readLock(readMutex_, std::adopt_lock);
311 if (perm_ == enableType) {
312 LOGI("Abort the handle occupy, release all!");
313 perm_ = OperatePerm::NORMAL_PERM;
314 operateAbort_ = true;
315
316 writeCondition_.notify_all();
317 readCondition_.notify_all();
318 }
319 }
320
IsNeedTobeReleased() const321 bool StorageEngine::IsNeedTobeReleased() const
322 {
323 return true;
324 }
325
GetIdentifier() const326 const std::string &StorageEngine::GetIdentifier() const
327 {
328 return identifier_;
329 }
330
GetEngineState() const331 EngineState StorageEngine::GetEngineState() const
332 {
333 return engineState_;
334 }
335
SetEngineState(EngineState state)336 void StorageEngine::SetEngineState(EngineState state)
337 {
338 LOGI("Storage engine state to [%d]!", state);
339 engineState_ = state;
340 }
341
ExecuteMigrate()342 int StorageEngine::ExecuteMigrate()
343 {
344 LOGW("Migration is not supported!");
345 return -E_NOT_SUPPORT;
346 }
347
SetNotifiedCallback(const std::function<void (int,KvDBCommitNotifyFilterAbleData *)> & callback)348 void StorageEngine::SetNotifiedCallback(const std::function<void(int, KvDBCommitNotifyFilterAbleData *)> &callback)
349 {
350 std::unique_lock<std::shared_mutex> lock(notifyMutex_);
351 commitNotifyFunc_ = callback;
352 }
353
SetConnectionFlag(bool isExisted)354 void StorageEngine::SetConnectionFlag(bool isExisted)
355 {
356 return isExistConnection_.store(isExisted);
357 }
358
IsExistConnection() const359 bool StorageEngine::IsExistConnection() const
360 {
361 return isExistConnection_.load();
362 }
363
ClearEnginePasswd()364 void StorageEngine::ClearEnginePasswd()
365 {
366 return;
367 }
368
CheckEngineOption(const KvDBProperties & kvdbOption) const369 int StorageEngine::CheckEngineOption(const KvDBProperties &kvdbOption) const
370 {
371 return E_OK;
372 }
373
AddStorageExecutor(StorageExecutor * handle)374 void StorageEngine::AddStorageExecutor(StorageExecutor *handle)
375 {
376 if (handle == nullptr) {
377 return;
378 }
379
380 if (handle->GetWritable()) {
381 writeIdleList_.push_back(handle);
382 } else {
383 readIdleList_.push_back(handle);
384 }
385 }
386
CloseExecutor()387 void StorageEngine::CloseExecutor()
388 {
389 {
390 std::lock_guard<std::mutex> lock(writeMutex_);
391 for (auto &item : writeIdleList_) {
392 if (item != nullptr) {
393 delete item;
394 item = nullptr;
395 }
396 }
397 writeIdleList_.clear();
398 }
399
400 {
401 std::lock_guard<std::mutex> lock(readMutex_);
402 for (auto &item : readIdleList_) {
403 if (item != nullptr) {
404 delete item;
405 item = nullptr;
406 }
407 }
408 readIdleList_.clear();
409 }
410 }
411
FetchStorageExecutor(bool isWrite,std::list<StorageExecutor * > & idleList,std::list<StorageExecutor * > & usingList,int & errCode)412 StorageExecutor *StorageEngine::FetchStorageExecutor(bool isWrite, std::list<StorageExecutor *> &idleList,
413 std::list<StorageExecutor *> &usingList, int &errCode)
414 {
415 if (idleList.empty()) {
416 StorageExecutor *handle = nullptr;
417 errCode = CreateNewExecutor(isWrite, handle);
418 if ((errCode != E_OK) || (handle == nullptr)) {
419 if (errCode != -E_EKEYREVOKED) {
420 return nullptr;
421 }
422 LOGE("Key revoked status, couldn't create the new executor");
423 if (!usingList.empty()) {
424 LOGE("Can't create new executor for revoked");
425 errCode = -E_BUSY;
426 }
427 return nullptr;
428 }
429
430 AddStorageExecutor(handle);
431 }
432 auto item = idleList.front();
433 usingList.push_back(item);
434 idleList.remove(item);
435 LOGD("Get executor[%d] from [%.3s]", isWrite,
436 DBCommon::TransferStringToHex(identifier_).c_str());
437 errCode = E_OK;
438 return item;
439 }
440
CheckEngineAttr(const StorageEngineAttr & poolSize)441 bool StorageEngine::CheckEngineAttr(const StorageEngineAttr &poolSize)
442 {
443 return (poolSize.maxReadNum > MAX_READ_SIZE ||
444 poolSize.maxWriteNum > MAX_WRITE_SIZE ||
445 poolSize.minReadNum > poolSize.maxReadNum ||
446 poolSize.minWriteNum > poolSize.maxWriteNum);
447 }
448
IsMigrating() const449 bool StorageEngine::IsMigrating() const
450 {
451 return isMigrating_.load();
452 }
453
WaitWriteHandleIdle()454 void StorageEngine::WaitWriteHandleIdle()
455 {
456 std::unique_lock<std::mutex> autoLock(idleMutex_);
457 LOGD("Wait wHandle release id[%s]. write[%zu-%zu-%" PRIu32 "]", DBCommon::TransferStringToHex(identifier_).c_str(),
458 writeIdleList_.size(), writeUsingList_.size(), engineAttr_.maxWriteNum);
459 idleCondition_.wait(autoLock, [this]() {
460 return writeUsingList_.empty();
461 });
462 LOGD("Wait wHandle release finish id[%s]. write[%zu-%zu-%" PRIu32 "]",
463 DBCommon::TransferStringToHex(identifier_).c_str(), writeIdleList_.size(), writeUsingList_.size(),
464 engineAttr_.maxWriteNum);
465 }
466 }
467