• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 private:
175     static constexpr int MAX_TP_THREADS = 10;  // max threads of the task pool.
176     static constexpr int MIN_TP_THREADS = 1;   // min threads of the task pool.
177     static constexpr int TASK_POOL_REPORTS_INTERVAL = 10000;   // task pool reports its state every 10 seconds.
178 
179     int PrepareLoop(IEventLoop *&loop);
180     int PrepareTaskPool();
181     int AllocTimerId(IEvent *evTimer, TimerId &timerId);
182     std::shared_ptr<DBStatusAdapter> GetDBStatusAdapter();
183     std::shared_ptr<SubscribeRecorder> GetSubscribeRecorder();
184 
185     int ScheduleTaskByThreadPool(const TaskAction &task) const __attribute__((no_sanitize("cfi")));
186 
187     int SetTimerByThreadPool(int milliSeconds, const TimerAction &action,
188         const TimerFinalizer &finalizer, bool allocTimerId, TimerId &timerId) __attribute__((no_sanitize("cfi")));
189 
190     int ModifyTimerByThreadPool(TimerId timerId, int milliSeconds);
191 
192     void RemoveTimerByThreadPool(TimerId timerId, bool wait) __attribute__((no_sanitize("cfi")));
193 
194     void ThreadPoolTimerAction(int milliSeconds, const TimerAction &action, TimerId timerId);
195 
196     // Context fields
197     mutable std::mutex labelMutex_;
198     std::string processLabel_;
199 
200     // Communicator
201     mutable std::mutex communicatorLock_;
202     IAdapter *adapter_;
203     ICommunicatorAggregator *communicatorAggregator_;
204 
205     // Loop and timer
206     mutable std::mutex loopLock_;
207     IEventLoop *mainLoop_;
208     std::mutex timersLock_;
209     TimerId currentTimerId_;
210     std::map<TimerId, IEvent *> timers_;
211 
212     // Task pool
213     std::mutex taskLock_;
214     TaskPool *taskPool_;
215     TimerId taskPoolReportsTimerId_;
216 
217     // TimeTick
218     mutable std::mutex timeTickMonitorLock_;
219     std::unique_ptr<TimeTickMonitor> timeTickMonitor_;
220 
221     mutable std::shared_mutex permissionCheckCallbackMutex_ {};
222     PermissionCheckCallback permissionCheckCallback_;
223     PermissionCheckCallbackV2 permissionCheckCallbackV2_;
224     PermissionCheckCallbackV3 permissionCheckCallbackV3_;
225 
226     AutoLaunch autoLaunch_;
227 
228     // System api
229     mutable std::recursive_mutex systemApiAdapterLock_;
230     std::shared_ptr<IProcessSystemApiAdapter> systemApiAdapter_;
231     mutable std::mutex lockStatusLock_; // Mutex for lockStatusObserver_.
232     LockStatusObserver *lockStatusObserver_;
233 
234     mutable std::shared_mutex databaseStatusCallbackMutex_ {};
235     StoreStatusNotifier databaseStatusNotifyCallback_;
236 
237     mutable std::shared_mutex syncActivationCheckCallbackMutex_ {};
238     SyncActivationCheckCallback syncActivationCheckCallback_;
239     SyncActivationCheckCallbackV2 syncActivationCheckCallbackV2_;
240 
241     mutable std::mutex userChangeMonitorLock_;
242     std::unique_ptr<UserChangeMonitor> userChangeMonitor_;
243 
244     std::atomic<uint32_t> currentSessionId_;
245 
246     // Get map from this callback, use for run permission check in remote device
247     mutable std::shared_mutex permissionConditionLock_;
248     PermissionConditionCallback permissionConditionCallback_;
249 
250     mutable std::mutex statusAdapterMutex_;
251     std::shared_ptr<DBStatusAdapter> dbStatusAdapter_;
252 
253     mutable std::mutex subscribeRecorderMutex_;
254     std::shared_ptr<SubscribeRecorder> subscribeRecorder_;
255 
256     mutable std::mutex translateToDeviceIdLock_;
257     TranslateToDeviceIdCallback translateToDeviceIdCallback_;
258     std::map<std::string, std::map<std::string, std::string>> deviceIdCache_; // cache <uuid, <appId, newDeviceId>>
259 
260     mutable std::shared_mutex threadPoolLock_;
261     std::shared_ptr<IThreadPool> threadPool_;
262 
263     mutable std::mutex timerTaskLock_;
264     std::map<TimerId, TaskId> taskIds_;
265     std::map<TimerId, TimerFinalizer> timerFinalizers_;
266 
267     mutable std::shared_mutex dataTranslateLock_;
268     std::shared_ptr<ICloudDataTranslate> dataTranslate_;
269 };
270 } // namespace DistributedDB
271 
272 #endif // RUNTIME_CONTEXT_IMPL_H
273