1 /*
2  * Copyright (c) 2022 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 #ifndef NATIVE_RDB_SQLITE_CONNECTION_POOL_H
17 #define NATIVE_RDB_SQLITE_CONNECTION_POOL_H
18 
19 #include <atomic>
20 #include <condition_variable>
21 #include <iostream>
22 #include <iterator>
23 #include <list>
24 #include <memory>
25 #include <mutex>
26 #include <sstream>
27 #include <stack>
28 #include <vector>
29 
30 #include "base_transaction.h"
31 #include "connection.h"
32 #include "rdb_common.h"
33 #include "rdb_store_config.h"
34 namespace OHOS {
35 namespace NativeRdb {
36 class ConnectionPool : public std::enable_shared_from_this<ConnectionPool> {
37 public:
38     using SharedConn = std::shared_ptr<Connection>;
39     using SharedConns = std::vector<SharedConn>;
40     static constexpr std::chrono::milliseconds INVALID_TIME = std::chrono::milliseconds(0);
41     static std::shared_ptr<ConnectionPool> Create(const RdbStoreConfig &config, int &errCode);
42     ~ConnectionPool();
43     static std::pair<RebuiltType, std::shared_ptr<ConnectionPool>> HandleDataCorruption
44         (const RdbStoreConfig &storeConfig, int &errCode);
45     std::pair<int32_t, std::shared_ptr<Connection>> CreateTransConn(bool limited = true);
46     SharedConn AcquireConnection(bool isReadOnly);
47     SharedConn Acquire(bool isReadOnly, std::chrono::milliseconds ms = INVALID_TIME);
48     // this interface is only provided for resultSet
49     SharedConn AcquireRef(bool isReadOnly, std::chrono::milliseconds ms = INVALID_TIME);
50     std::pair<SharedConn, SharedConns> AcquireAll(int32_t time);
51     std::pair<int32_t, SharedConn> DisableWal();
52     int32_t EnableWal();
53     int32_t Dump(bool isWriter, const char *header);
54 
55     int RestartReaders();
56     int ConfigLocale(const std::string &localeStr);
57     int ChangeDbFileForRestore(const std::string &newPath, const std::string &backupPath,
58         const std::vector<uint8_t> &newKey, SlaveStatus &slaveStatus);
59     std::stack<BaseTransaction> &GetTransactionStack();
60     std::mutex &GetTransactionStackMutex();
61     int AcquireTransaction();
62     void ReleaseTransaction();
63     void CloseAllConnections();
64     bool IsInTransaction();
65     void SetInTransaction(bool isInTransaction);
66 
67 private:
68     struct ConnNode {
69         bool using_ = false;
70         int32_t tid_ = 0;
71         int32_t id_ = 0;
72         std::chrono::steady_clock::time_point time_ = std::chrono::steady_clock::now();
73         std::shared_ptr<Connection> connect_;
74 
75         explicit ConnNode(std::shared_ptr<Connection> conn);
76         std::shared_ptr<Connection> GetConnect();
77         int64_t GetUsingTime() const;
78         bool IsWriter() const;
79         int32_t Unused(int32_t count, bool timeout);
80     };
81 
82     struct Container {
83         using Creator = std::function<std::pair<int32_t, std::shared_ptr<Connection>>()>;
84         static constexpr int32_t MAX_RIGHT = 0x4FFFFFFF;
85         static constexpr int32_t MIN_TRANS_ID = 10000;
86         bool disable_ = true;
87         int max_ = 0;
88         int total_ = 0;
89         int count_ = 0;
90         int trans_ = 0;
91         int32_t left_ = 0;
92         int32_t right_ = 0;
93         std::chrono::seconds timeout_;
94         std::list<std::shared_ptr<ConnNode>> nodes_;
95         std::list<std::weak_ptr<ConnNode>> details_;
96         std::mutex mutex_;
97         std::condition_variable cond_;
98         Creator creator_ = nullptr;
99         std::pair<int32_t, std::shared_ptr<ConnNode>> Initialize(Creator creator, int32_t max, int32_t timeout,
100             bool disable, bool acquire = false);
101         int32_t ConfigLocale(const std::string &locale);
102         std::shared_ptr<ConnNode> Acquire(std::chrono::milliseconds milliS);
103         std::list<std::shared_ptr<ConnNode>> AcquireAll(std::chrono::milliseconds milliS);
104         std::pair<int32_t, std::shared_ptr<ConnNode>> Create();
105 
106         void Disable();
107         void Enable();
108         int32_t Release(std::shared_ptr<ConnNode> node);
109         int32_t Drop(std::shared_ptr<ConnNode> node);
110         int32_t Clear();
111         bool IsFull();
112         int32_t Dump(const char *header, int32_t count);
113 
114     private:
115         int32_t ExtendNode();
116         int32_t RelDetails(std::shared_ptr<ConnNode> node);
117     };
118 
119     explicit ConnectionPool(const RdbStoreConfig &storeConfig);
120     std::pair<int32_t, std::shared_ptr<Connection>> Init(bool isAttach = false, bool needWriter = false);
121     int32_t GetMaxReaders(const RdbStoreConfig &config);
122     std::shared_ptr<Connection> Convert2AutoConn(std::shared_ptr<ConnNode> node, bool isTrans = false);
123     void ReleaseNode(std::shared_ptr<ConnNode> node, bool reuse = true);
124     int RestoreByDbSqliteType(const std::string &newPath, const std::string &backupPath, SlaveStatus &slaveStatus);
125     int RestoreMasterDb(const std::string &newPath, const std::string &backupPath);
126     bool CheckIntegrity(const std::string &dbPath);
127 
128     static constexpr uint32_t CHECK_POINT_INTERVAL = 5; // 5 min
129     static constexpr int LIMITATION = 1024;
130     static constexpr uint32_t ITER_V1 = 5000;
131     static constexpr uint32_t ITERS_COUNT = 2;
132     static constexpr uint32_t MAX_TRANS = 4;
133     const RdbStoreConfig &config_;
134     RdbStoreConfig attachConfig_;
135     Container writers_;
136     Container readers_;
137     int32_t maxReader_ = 0;
138 
139     std::stack<BaseTransaction> transactionStack_;
140     std::mutex transactionStackMutex_;
141     std::condition_variable transCondition_;
142     std::mutex transMutex_;
143     bool transactionUsed_;
144     std::atomic<bool> isInTransaction_ = false;
145     std::atomic<uint32_t> transCount_ = 0;
146     std::atomic<std::chrono::steady_clock::time_point> failedTime_;
147 };
148 
149 } // namespace NativeRdb
150 } // namespace OHOS
151 #endif
152