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 #ifndef RUNTIME_CONTEXT_IMPL_H
17 #define RUNTIME_CONTEXT_IMPL_H
18 
19 #include <map>
20 #include <mutex>
21 #include <shared_mutex>
22 
23 #include "auto_launch.h"
24 #include "db_status_adapter.h"
25 #include "evloop/src/ievent.h"
26 #include "evloop/src/ievent_loop.h"
27 #include "icommunicator_aggregator.h"
28 #include "lock_status_observer.h"
29 #include "subscribe_recorder.h"
30 #include "task_pool.h"
31 #include "time_tick_monitor.h"
32 #include "user_change_monitor.h"
33 
34 namespace DistributedDB {
35 class RuntimeContextImpl final : public RuntimeContext {
36 public:
37     RuntimeContextImpl();
38     ~RuntimeContextImpl() override;
39 
40     // Get/Set the label of this process.
41     void SetProcessLabel(const std::string &label) override;
42     std::string GetProcessLabel() const override;
43     int SetCommunicatorAdapter(IAdapter *adapter) override;
44     int GetCommunicatorAggregator(ICommunicatorAggregator *&outAggregator) override;
45     void SetCommunicatorAggregator(ICommunicatorAggregator *inAggregator) override;
46     int GetLocalIdentity(std::string &outTarget) override;
47     // Add and start a timer.
48     int SetTimer(int milliSeconds, const TimerAction &action,
49         const TimerFinalizer &finalizer, TimerId &timerId) override;
50 
51     // Modify the interval of the timer.
52     int ModifyTimer(TimerId timerId, int milliSeconds) override;
53 
54     // Remove the timer.
55     void RemoveTimer(TimerId timerId, bool wait) override;
56 
57     // Task interfaces.
58     int ScheduleTask(const TaskAction &task) override;
59     int ScheduleQueuedTask(const std::string &queueTag, const TaskAction &task) override;
60 
61     // Shrink as much memory as possible.
62     void ShrinkMemory(const std::string &description) override;
63 
64     // Register a time changed lister, it will be callback when local time changed.
65     NotificationChain::Listener *RegisterTimeChangedLister(const TimeChangedAction &action,
66         const TimeFinalizeAction &finalize, int &errCode) override;
67 
68     int SetPermissionCheckCallback(const PermissionCheckCallback &callback) override;
69 
70     int SetPermissionCheckCallback(const PermissionCheckCallbackV2 &callback) override;
71 
72     int SetPermissionCheckCallback(const PermissionCheckCallbackV3 &callback) override;
73 
74     int RunPermissionCheck(const PermissionCheckParam &param, uint8_t flag) const override;
75 
76     int EnableKvStoreAutoLaunch(const KvDBProperties &properties, AutoLaunchNotifier notifier,
77         const AutoLaunchOption &option) override;
78 
79     int DisableKvStoreAutoLaunch(const std::string &normalIdentifier, const std::string &dualTupleIdentifier,
80         const std::string &userId) override;
81 
82     void GetAutoLaunchSyncDevices(const std::string &identifier, std::vector<std::string> &devices) const override;
83 
84     void SetAutoLaunchRequestCallback(const AutoLaunchRequestCallback &callback, DBTypeInner type) override;
85 
86     NotificationChain::Listener *RegisterLockStatusLister(const LockStatusNotifier &action, int &errCode) override;
87 
88     bool IsAccessControlled() const override;
89 
90     int SetSecurityOption(const std::string &filePath, const SecurityOption &option) const override;
91 
92     int GetSecurityOption(const std::string &filePath, SecurityOption &option) const override;
93 
94     bool CheckDeviceSecurityAbility(const std::string &devId, const SecurityOption &option) const override;
95 
96     int SetProcessSystemApiAdapter(const std::shared_ptr<IProcessSystemApiAdapter> &adapter) override;
97 
98     bool IsProcessSystemApiAdapterValid() const override;
99 
100     bool IsCommunicatorAggregatorValid() const override;
101 
102     // Notify TIME_CHANGE_EVENT.
103     void NotifyTimestampChanged(TimeOffset offset) const override;
104 
105     void SetStoreStatusNotifier(const StoreStatusNotifier &notifier) override;
106 
107     void NotifyDatabaseStatusChange(const std::string &userId, const std::string &appId, const std::string &storeId,
108         const std::string &deviceId, bool onlineStatus) override;
109 
110     int SetSyncActivationCheckCallback(const SyncActivationCheckCallback &callback) override;
111 
112     int SetSyncActivationCheckCallback(const SyncActivationCheckCallbackV2 &callback) override;
113 
114     bool IsSyncerNeedActive(const DBProperties &properties) const override;
115 
116     // Register a user changed lister, it will be callback when user change.
117     NotificationChain::Listener *RegisterUserChangedListener(const UserChangedAction &action,
118         EventType event) override;
119     // Notify TIME_CHANGE_EVENT.
120     int NotifyUserChanged() const override;
121 
122     uint32_t GenerateSessionId() override;
123 
124     void DumpCommonInfo(int fd) override;
125 
126     void CloseAutoLaunchConnection(DBTypeInner type, const DBProperties &properties) override;
127 
128     int SetPermissionConditionCallback(const PermissionConditionCallback &callback) override;
129 
130     std::map<std::string, std::string> GetPermissionCheckParam(const DBProperties &properties) override;
131 
132     void StopTaskPool() override;
133 
134     void StopTimeTickMonitorIfNeed() override;
135 
136     void SetDBInfoHandle(const std::shared_ptr<DBInfoHandle> &handle) override;
137 
138     void NotifyDBInfos(const DeviceInfos &devInfos, const std::vector<DBInfo> &dbInfos) override;
139 
140     void RecordRemoteSubscribe(const DBInfo &dbInfo, const DeviceID &deviceId, const QuerySyncObject &query) override;
141 
142     void RemoveRemoteSubscribe(const DeviceID &deviceId) override;
143 
144     void RemoveRemoteSubscribe(const DBInfo &dbInfo) override;
145 
146     void RemoveRemoteSubscribe(const DBInfo &dbInfo, const DeviceID &deviceId) override;
147 
148     void RemoveRemoteSubscribe(const DBInfo &dbInfo, const DeviceID &deviceId, const QuerySyncObject &query) override;
149 
150     void GetSubscribeQuery(const DBInfo &dbInfo,
151         std::map<std::string, std::vector<QuerySyncObject>> &subscribeQuery) override;
152 
153     bool IsNeedAutoSync(const std::string &userId, const std::string &appId, const std::string &storeId,
154         const std::string &devInfo) override;
155 
156     void SetRemoteOptimizeCommunication(const std::string &dev, bool optimize) override;
157 
158     void SetTranslateToDeviceIdCallback(const TranslateToDeviceIdCallback &callback) override;
159 
160     int TranslateDeviceId(const std::string &deviceId,
161         const StoreInfo &info, std::string &newDeviceId) override;
162 
163     bool ExistTranslateDevIdCallback() const override;
164 
165     void SetThreadPool(const std::shared_ptr<IThreadPool> &threadPool) override;
166 
167     std::shared_ptr<IThreadPool> GetThreadPool() const override;
168 
169     void SetCloudTranslate(const std::shared_ptr<ICloudDataTranslate> &dataTranslate) override;
170     int AssetToBlob(const Asset &asset, std::vector<uint8_t> &blob) override;
171     int AssetsToBlob(const Assets &assets, std::vector<uint8_t> &blob) override;
172     int BlobToAsset(const std::vector<uint8_t> &blob, Asset &asset) override;
173     int BlobToAssets(const std::vector<uint8_t> &blob, Assets &assets) override;
174 
175     std::pair<int, DeviceTimeInfo> GetDeviceTimeInfo(const std::string &device) const override;
176     void SetDeviceTimeInfo(const std::string &device, const DeviceTimeInfo &deviceTimeInfo) override;
177     void ClearDeviceTimeInfo(const std::string &device) override;
178     void ClearAllDeviceTimeInfo() override;
179     void RecordAllTimeChange() override;
180     void ResetDBTimeChangeStatus(const std::vector<uint8_t> &dbId) override;
181     bool CheckDBTimeChange(const std::vector<uint8_t> &dbId) override;
182     bool IsTimeTickMonitorValid() const override;
183     bool IsTimeChanged() const override;
184     void SetTimeChanged(bool timeChange) override;
185 private:
186     static constexpr int MAX_TP_THREADS = 10;  // max threads of the task pool.
187     static constexpr int MIN_TP_THREADS = 1;   // min threads of the task pool.
188     static constexpr int TASK_POOL_REPORTS_INTERVAL = 10000;   // task pool reports its state every 10 seconds.
189 
190     int PrepareLoop(IEventLoop *&loop);
191     int PrepareTaskPool();
192     int AllocTimerId(IEvent *evTimer, TimerId &timerId);
193     std::shared_ptr<DBStatusAdapter> GetDBStatusAdapter();
194     std::shared_ptr<SubscribeRecorder> GetSubscribeRecorder();
195 
196     int ScheduleTaskByThreadPool(const TaskAction &task) const __attribute__((no_sanitize("cfi")));
197 
198     int SetTimerByThreadPool(int milliSeconds, const TimerAction &action,
199         const TimerFinalizer &finalizer, bool allocTimerId, TimerId &timerId) __attribute__((no_sanitize("cfi")));
200 
201     int ModifyTimerByThreadPool(TimerId timerId, int milliSeconds);
202 
203     void RemoveTimerByThreadPool(TimerId timerId, bool wait) __attribute__((no_sanitize("cfi")));
204 
205     void ThreadPoolTimerAction(int milliSeconds, const TimerAction &action, TimerId timerId);
206 
207     // Context fields
208     mutable std::mutex labelMutex_;
209     std::string processLabel_;
210 
211     // Communicator
212     mutable std::mutex communicatorLock_;
213     IAdapter *adapter_;
214     ICommunicatorAggregator *communicatorAggregator_;
215 
216     // Loop and timer
217     mutable std::mutex loopLock_;
218     IEventLoop *mainLoop_;
219     std::mutex timersLock_;
220     TimerId currentTimerId_;
221     std::map<TimerId, IEvent *> timers_;
222 
223     // Task pool
224     std::mutex taskLock_;
225     TaskPool *taskPool_;
226     TimerId taskPoolReportsTimerId_;
227 
228     // TimeTick
229     mutable std::mutex timeTickMonitorLock_;
230     std::unique_ptr<TimeTickMonitor> timeTickMonitor_;
231 
232     mutable std::shared_mutex permissionCheckCallbackMutex_ {};
233     PermissionCheckCallback permissionCheckCallback_;
234     PermissionCheckCallbackV2 permissionCheckCallbackV2_;
235     PermissionCheckCallbackV3 permissionCheckCallbackV3_;
236 
237     AutoLaunch autoLaunch_;
238 
239     // System api
240     mutable std::recursive_mutex systemApiAdapterLock_;
241     std::shared_ptr<IProcessSystemApiAdapter> systemApiAdapter_;
242     mutable std::mutex lockStatusLock_; // Mutex for lockStatusObserver_.
243     LockStatusObserver *lockStatusObserver_;
244 
245     mutable std::shared_mutex databaseStatusCallbackMutex_ {};
246     StoreStatusNotifier databaseStatusNotifyCallback_;
247 
248     mutable std::shared_mutex syncActivationCheckCallbackMutex_ {};
249     SyncActivationCheckCallback syncActivationCheckCallback_;
250     SyncActivationCheckCallbackV2 syncActivationCheckCallbackV2_;
251 
252     mutable std::mutex userChangeMonitorLock_;
253     std::unique_ptr<UserChangeMonitor> userChangeMonitor_;
254 
255     std::atomic<uint32_t> currentSessionId_;
256 
257     // Get map from this callback, use for run permission check in remote device
258     mutable std::shared_mutex permissionConditionLock_;
259     PermissionConditionCallback permissionConditionCallback_;
260 
261     mutable std::mutex statusAdapterMutex_;
262     std::shared_ptr<DBStatusAdapter> dbStatusAdapter_;
263 
264     mutable std::mutex subscribeRecorderMutex_;
265     std::shared_ptr<SubscribeRecorder> subscribeRecorder_;
266 
267     mutable std::mutex translateToDeviceIdLock_;
268     TranslateToDeviceIdCallback translateToDeviceIdCallback_;
269     std::map<std::string, std::map<std::string, std::string>> deviceIdCache_; // cache <uuid, <appId, newDeviceId>>
270 
271     mutable std::shared_mutex threadPoolLock_;
272     std::shared_ptr<IThreadPool> threadPool_;
273 
274     mutable std::mutex timerTaskLock_;
275     std::map<TimerId, TaskId> taskIds_;
276     std::map<TimerId, TimerFinalizer> timerFinalizers_;
277 
278     mutable std::shared_mutex dataTranslateLock_;
279     std::shared_ptr<ICloudDataTranslate> dataTranslate_;
280 
281     mutable std::mutex deviceTimeInfoLock_;
282     std::map<std::string, DeviceTimeInfo> deviceTimeInfos_;
283     std::map<std::vector<uint8_t>, bool> dbTimeChange_;
284 };
285 } // namespace DistributedDB
286 
287 #endif // RUNTIME_CONTEXT_IMPL_H
288