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_) {
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 Release();
105 }
106 initCondition_.notify_all();
107 Release();
108 return errCode;
109 }
110
FindExecutor(bool writable,OperatePerm perm,int & errCode,int waitTime)111 StorageExecutor *StorageEngine::FindExecutor(bool writable, OperatePerm perm, int &errCode, int waitTime)
112 {
113 if (GetEngineState() == EngineState::ENGINE_BUSY) {
114 LOGI("Storage engine is busy!");
115 errCode = -E_BUSY;
116 return nullptr;
117 }
118
119 {
120 std::unique_lock<std::mutex> lock(initMutex_);
121 bool result = initCondition_.wait_for(lock, std::chrono::seconds(waitTime), [this]() {
122 return isInitialized_.load();
123 });
124 if (!result || !isInitialized_.load()) {
125 LOGE("Storage engine is not initialized");
126 errCode = -E_BUSY; // Usually in reinitialize engine, return BUSY
127 return nullptr;
128 }
129 }
130
131 if (writable) {
132 return FindWriteExecutor(perm, errCode, waitTime);
133 }
134
135 return FindReadExecutor(perm, errCode, waitTime);
136 }
137
FindWriteExecutor(OperatePerm perm,int & errCode,int waitTime)138 StorageExecutor *StorageEngine::FindWriteExecutor(OperatePerm perm, int &errCode, int waitTime)
139 {
140 std::unique_lock<std::mutex> lock(writeMutex_);
141 errCode = -E_BUSY;
142 if (perm_ == OperatePerm::DISABLE_PERM || perm_ != perm) {
143 LOGI("Not permitted to get the executor[%u]", static_cast<unsigned>(perm_));
144 return nullptr;
145 }
146 if (waitTime <= 0) { // non-blocking.
147 if (writeIdleList_.empty() &&
148 writeIdleList_.size() + writeUsingList_.size() == engineAttr_.maxWriteNum) {
149 return nullptr;
150 }
151 return FetchStorageExecutor(true, writeIdleList_, writeUsingList_, errCode);
152 }
153
154 // Not prohibited and there is an available handle
155 bool result = writeCondition_.wait_for(lock, std::chrono::seconds(waitTime),
156 [this, &perm]() {
157 return (perm_ == OperatePerm::NORMAL_PERM || perm_ == perm) && (!writeIdleList_.empty() ||
158 (writeIdleList_.size() + writeUsingList_.size() < engineAttr_.maxWriteNum) ||
159 operateAbort_);
160 });
161 if (operateAbort_) {
162 LOGI("Abort write executor and executor and busy for operate!");
163 return nullptr;
164 }
165 if (!result) {
166 LOGI("Get write handle result[%d], permissType[%u], operType[%u], write[%zu-%zu-%" PRIu32 "]", result,
167 static_cast<unsigned>(perm_), static_cast<unsigned>(perm), writeIdleList_.size(), writeUsingList_.size(),
168 engineAttr_.maxWriteNum);
169 return nullptr;
170 }
171 return FetchStorageExecutor(true, writeIdleList_, writeUsingList_, errCode);
172 }
173
FindReadExecutor(OperatePerm perm,int & errCode,int waitTime)174 StorageExecutor *StorageEngine::FindReadExecutor(OperatePerm perm, int &errCode, int waitTime)
175 {
176 std::unique_lock<std::mutex> lock(readMutex_);
177 errCode = -E_BUSY;
178 if (perm_ == OperatePerm::DISABLE_PERM || perm_ != perm) {
179 LOGI("Not permitted to get the executor[%u]", static_cast<unsigned>(perm_));
180 return nullptr;
181 }
182
183 if (waitTime <= 0) { // non-blocking.
184 if (readIdleList_.empty() &&
185 readIdleList_.size() + readUsingList_.size() == engineAttr_.maxReadNum) {
186 return nullptr;
187 }
188 return FetchStorageExecutor(false, readIdleList_, readUsingList_, errCode);
189 }
190
191 // Not prohibited and there is an available handle
192 bool result = readCondition_.wait_for(lock, std::chrono::seconds(waitTime),
193 [this, &perm]() {
194 return (perm_ == OperatePerm::NORMAL_PERM || perm_ == perm) &&
195 (!readIdleList_.empty() || (readIdleList_.size() + readUsingList_.size() < engineAttr_.maxReadNum) ||
196 operateAbort_);
197 });
198 if (operateAbort_) {
199 LOGI("Abort find read executor and busy for operate!");
200 return nullptr;
201 }
202 if (!result) {
203 LOGI("Get read handle result[%d], permissType[%u], operType[%u], read[%zu-%zu-%" PRIu32 "]", result,
204 static_cast<unsigned>(perm_), static_cast<unsigned>(perm), readIdleList_.size(), readUsingList_.size(),
205 engineAttr_.maxReadNum);
206 return nullptr;
207 }
208 return FetchStorageExecutor(false, readIdleList_, readUsingList_, errCode);
209 }
210
Recycle(StorageExecutor * & handle)211 void StorageEngine::Recycle(StorageExecutor *&handle)
212 {
213 if (handle == nullptr) {
214 return;
215 }
216 std::string id = DBCommon::TransferStringToHex(identifier_);
217 LOGD("Recycle executor[%d] for id[%.6s]", handle->GetWritable(), id.c_str());
218 if (handle->GetWritable()) {
219 std::unique_lock<std::mutex> lock(writeMutex_);
220 auto iter = std::find(writeUsingList_.begin(), writeUsingList_.end(), handle);
221 if (iter != writeUsingList_.end()) {
222 writeUsingList_.remove(handle);
223 if (writeIdleList_.size() >= 1) {
224 delete handle;
225 handle = nullptr;
226 return;
227 }
228 handle->Reset();
229 writeIdleList_.push_back(handle);
230 writeCondition_.notify_one();
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_ = 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
IsNeedMigrate() const342 bool StorageEngine::IsNeedMigrate() const
343 {
344 LOGI("No need to migrate!");
345 return false;
346 }
347
ExecuteMigrate()348 int StorageEngine::ExecuteMigrate()
349 {
350 LOGW("Migration is not supported!");
351 return -E_NOT_SUPPORT;
352 }
353
SetNotifiedCallback(const std::function<void (int,KvDBCommitNotifyFilterAbleData *)> & callback)354 void StorageEngine::SetNotifiedCallback(const std::function<void(int, KvDBCommitNotifyFilterAbleData *)> &callback)
355 {
356 std::unique_lock<std::shared_mutex> lock(notifyMutex_);
357 commitNotifyFunc_ = callback;
358 return;
359 }
360
SetConnectionFlag(bool isExisted)361 void StorageEngine::SetConnectionFlag(bool isExisted)
362 {
363 return isExistConnection_.store(isExisted);
364 }
365
IsExistConnection() const366 bool StorageEngine::IsExistConnection() const
367 {
368 return isExistConnection_.load();
369 }
370
ClearEnginePasswd()371 void StorageEngine::ClearEnginePasswd()
372 {
373 return;
374 }
375
CheckEngineOption(const KvDBProperties & kvdbOption) const376 int StorageEngine::CheckEngineOption(const KvDBProperties &kvdbOption) const
377 {
378 return E_OK;
379 }
380
AddStorageExecutor(StorageExecutor * handle)381 void StorageEngine::AddStorageExecutor(StorageExecutor *handle)
382 {
383 if (handle == nullptr) {
384 return;
385 }
386
387 if (handle->GetWritable()) {
388 writeIdleList_.push_back(handle);
389 } else {
390 readIdleList_.push_back(handle);
391 }
392 }
393
CloseExecutor()394 void StorageEngine::CloseExecutor()
395 {
396 {
397 std::lock_guard<std::mutex> lock(writeMutex_);
398 for (auto &item : writeIdleList_) {
399 if (item != nullptr) {
400 delete item;
401 item = nullptr;
402 }
403 }
404 writeIdleList_.clear();
405 }
406
407 {
408 std::lock_guard<std::mutex> lock(readMutex_);
409 for (auto &item : readIdleList_) {
410 if (item != nullptr) {
411 delete item;
412 item = nullptr;
413 }
414 }
415 readIdleList_.clear();
416 }
417 }
418
FetchStorageExecutor(bool isWrite,std::list<StorageExecutor * > & idleList,std::list<StorageExecutor * > & usingList,int & errCode)419 StorageExecutor *StorageEngine::FetchStorageExecutor(bool isWrite, std::list<StorageExecutor *> &idleList,
420 std::list<StorageExecutor *> &usingList, int &errCode)
421 {
422 if (idleList.empty()) {
423 StorageExecutor *handle = nullptr;
424 errCode = CreateNewExecutor(isWrite, handle);
425 if ((errCode != E_OK) || (handle == nullptr)) {
426 if (errCode != -E_EKEYREVOKED) {
427 return nullptr;
428 }
429 LOGE("Key revoked status, couldn't create the new executor");
430 if (!usingList.empty()) {
431 LOGE("Can't create new executor for revoked");
432 errCode = -E_BUSY;
433 }
434 return nullptr;
435 }
436
437 AddStorageExecutor(handle);
438 }
439 auto item = idleList.front();
440 usingList.push_back(item);
441 idleList.remove(item);
442 LOGD("Get executor[%d] from [%.6s], using[%zu]", isWrite,
443 DBCommon::TransferStringToHex(identifier_).c_str(), usingList.size());
444 errCode = E_OK;
445 return item;
446 }
447
CheckEngineAttr(const StorageEngineAttr & poolSize)448 bool StorageEngine::CheckEngineAttr(const StorageEngineAttr &poolSize)
449 {
450 return (poolSize.maxReadNum > MAX_READ_SIZE ||
451 poolSize.maxWriteNum > MAX_WRITE_SIZE ||
452 poolSize.minReadNum > poolSize.maxReadNum ||
453 poolSize.minWriteNum > poolSize.maxWriteNum);
454 }
455
IsMigrating() const456 bool StorageEngine::IsMigrating() const
457 {
458 return isMigrating_.load();
459 }
460 }
461