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 SetPermissionCheckCallback(const PermissionCheckCallbackV4 &callback) override; 75 76 int RunPermissionCheck(const PermissionCheckParam ¶m, uint8_t flag) const override; 77 78 int EnableKvStoreAutoLaunch(const KvDBProperties &properties, AutoLaunchNotifier notifier, 79 const AutoLaunchOption &option) override; 80 81 int DisableKvStoreAutoLaunch(const std::string &normalIdentifier, const std::string &dualTupleIdentifier, 82 const std::string &userId) override; 83 84 void GetAutoLaunchSyncDevices(const std::string &identifier, std::vector<std::string> &devices) const override; 85 86 void SetAutoLaunchRequestCallback(const AutoLaunchRequestCallback &callback, DBTypeInner type) override; 87 88 NotificationChain::Listener *RegisterLockStatusLister(const LockStatusNotifier &action, int &errCode) override; 89 90 bool IsAccessControlled() const override; 91 92 int SetSecurityOption(const std::string &filePath, const SecurityOption &option) const override; 93 94 int GetSecurityOption(const std::string &filePath, SecurityOption &option) const override; 95 96 bool CheckDeviceSecurityAbility(const std::string &devId, const SecurityOption &option) const override; 97 98 int SetProcessSystemApiAdapter(const std::shared_ptr<IProcessSystemApiAdapter> &adapter) override; 99 100 bool IsProcessSystemApiAdapterValid() const override; 101 102 bool IsCommunicatorAggregatorValid() const override; 103 104 // Notify TIME_CHANGE_EVENT. 105 void NotifyTimestampChanged(TimeOffset offset) const override; 106 107 void SetStoreStatusNotifier(const StoreStatusNotifier ¬ifier) override; 108 109 void SetStoreStatusNotifier(const StoreStatusNotifierV2 ¬ifier) override; 110 111 void NotifyDatabaseStatusChange(const StoreStatusNotifierParam ¶m, bool onlineStatus) override; 112 113 int SetSyncActivationCheckCallback(const SyncActivationCheckCallback &callback) override; 114 115 int SetSyncActivationCheckCallback(const SyncActivationCheckCallbackV2 &callback) override; 116 117 bool IsSyncerNeedActive(const DBProperties &properties) const override; 118 119 // Register a user changed lister, it will be callback when user change. 120 NotificationChain::Listener *RegisterUserChangedListener(const UserChangedAction &action, 121 EventType event) override; 122 // Notify TIME_CHANGE_EVENT. 123 int NotifyUserChanged() const override; 124 125 uint32_t GenerateSessionId() override; 126 127 void DumpCommonInfo(int fd) override; 128 129 void CloseAutoLaunchConnection(DBTypeInner type, const DBProperties &properties) override; 130 131 int SetPermissionConditionCallback(const PermissionConditionCallback &callback) override; 132 133 std::map<std::string, std::string> GetPermissionCheckParam(const DBProperties &properties) override; 134 135 void StopTaskPool() override; 136 137 void StopTimeTickMonitorIfNeed() override; 138 139 void SetDBInfoHandle(const std::shared_ptr<DBInfoHandle> &handle) override; 140 141 void NotifyDBInfos(const DeviceInfos &devInfos, const std::vector<DBInfo> &dbInfos) override; 142 143 void RecordRemoteSubscribe(const DBInfo &dbInfo, const DeviceID &deviceId, const QuerySyncObject &query) override; 144 145 void RemoveRemoteSubscribe(const DeviceID &deviceId) override; 146 147 void RemoveRemoteSubscribe(const DBInfo &dbInfo) override; 148 149 void RemoveRemoteSubscribe(const DBInfo &dbInfo, const DeviceID &deviceId) override; 150 151 void RemoveRemoteSubscribe(const DBInfo &dbInfo, const DeviceID &deviceId, const QuerySyncObject &query) override; 152 153 void GetSubscribeQuery(const DBInfo &dbInfo, 154 std::map<std::string, std::vector<QuerySyncObject>> &subscribeQuery) override; 155 156 bool IsNeedAutoSync(const std::string &userId, const std::string &appId, const std::string &storeId, 157 const std::string &devInfo) override; 158 159 void SetRemoteOptimizeCommunication(const std::string &dev, bool optimize) override; 160 161 void SetTranslateToDeviceIdCallback(const TranslateToDeviceIdCallback &callback) override; 162 163 int TranslateDeviceId(const std::string &deviceId, 164 const StoreInfo &info, std::string &newDeviceId) override; 165 166 bool ExistTranslateDevIdCallback() const override; 167 168 void SetThreadPool(const std::shared_ptr<IThreadPool> &threadPool) override; 169 170 std::shared_ptr<IThreadPool> GetThreadPool() const override; 171 172 void SetCloudTranslate(const std::shared_ptr<ICloudDataTranslate> &dataTranslate) override; 173 int AssetToBlob(const Asset &asset, std::vector<uint8_t> &blob) override; 174 int AssetsToBlob(const Assets &assets, std::vector<uint8_t> &blob) override; 175 int BlobToAsset(const std::vector<uint8_t> &blob, Asset &asset) override; 176 int BlobToAssets(const std::vector<uint8_t> &blob, Assets &assets) override; 177 178 std::pair<int, DeviceTimeInfo> GetDeviceTimeInfo(const std::string &device) const override; 179 void SetDeviceTimeInfo(const std::string &device, const DeviceTimeInfo &deviceTimeInfo) override; 180 void ClearDeviceTimeInfo(const std::string &device) override; 181 void ClearAllDeviceTimeInfo() override; 182 void RecordAllTimeChange() override; 183 void ResetDBTimeChangeStatus(const std::vector<uint8_t> &dbId) override; 184 bool CheckDBTimeChange(const std::vector<uint8_t> &dbId) override; 185 bool IsTimeTickMonitorValid() const override; 186 bool IsTimeChanged() const override; 187 void SetTimeChanged(bool timeChange) override; 188 189 bool IsBatchDownloadAssets() const override; 190 void SetBatchDownloadAssets(bool isBatchDownload) override; 191 192 std::shared_ptr<AssetsDownloadManager> GetAssetsDownloadManager() override; 193 194 void ClearOnlineLabel() override; 195 private: 196 static constexpr int MAX_TP_THREADS = 10; // max threads of the task pool. 197 static constexpr int MIN_TP_THREADS = 1; // min threads of the task pool. 198 static constexpr int TASK_POOL_REPORTS_INTERVAL = 10000; // task pool reports its state every 10 seconds. 199 200 int PrepareLoop(IEventLoop *&loop); 201 int PrepareTaskPool(); 202 int AllocTimerId(IEvent *evTimer, TimerId &timerId); 203 std::shared_ptr<DBStatusAdapter> GetDBStatusAdapter(); 204 std::shared_ptr<SubscribeRecorder> GetSubscribeRecorder(); 205 206 int ScheduleTaskByThreadPool(const TaskAction &task) const; 207 208 int SetTimerByThreadPool(int milliSeconds, const TimerAction &action, 209 const TimerFinalizer &finalizer, bool allocTimerId, TimerId &timerId); 210 211 int ModifyTimerByThreadPool(TimerId timerId, int milliSeconds); 212 213 void RemoveTimerByThreadPool(TimerId timerId, bool wait); 214 215 void ThreadPoolTimerAction(int milliSeconds, const TimerAction &action, TimerId timerId); 216 217 // Context fields 218 mutable std::mutex labelMutex_; 219 std::string processLabel_; 220 221 // Communicator 222 mutable std::mutex communicatorLock_; 223 IAdapter *adapter_; 224 ICommunicatorAggregator *communicatorAggregator_; 225 226 // Loop and timer 227 mutable std::mutex loopLock_; 228 IEventLoop *mainLoop_; 229 std::mutex timersLock_; 230 TimerId currentTimerId_; 231 std::map<TimerId, IEvent *> timers_; 232 233 // Task pool 234 std::mutex taskLock_; 235 TaskPool *taskPool_; 236 TimerId taskPoolReportsTimerId_; 237 238 // TimeTick 239 mutable std::mutex timeTickMonitorLock_; 240 std::shared_ptr<TimeTickMonitor> timeTickMonitor_; 241 242 mutable std::shared_mutex permissionCheckCallbackMutex_ {}; 243 PermissionCheckCallback permissionCheckCallback_; 244 PermissionCheckCallbackV2 permissionCheckCallbackV2_; 245 PermissionCheckCallbackV3 permissionCheckCallbackV3_; 246 PermissionCheckCallbackV4 permissionCheckCallbackV4_; 247 248 AutoLaunch autoLaunch_; 249 250 // System api 251 mutable std::recursive_mutex systemApiAdapterLock_; 252 std::shared_ptr<IProcessSystemApiAdapter> systemApiAdapter_; 253 mutable std::mutex lockStatusLock_; // Mutex for lockStatusObserver_. 254 LockStatusObserver *lockStatusObserver_; 255 256 mutable std::shared_mutex databaseStatusCallbackMutex_ {}; 257 StoreStatusNotifier databaseStatusNotifyCallback_; 258 StoreStatusNotifierV2 databaseStatusNotifyCallbackV2_; 259 260 mutable std::shared_mutex syncActivationCheckCallbackMutex_ {}; 261 SyncActivationCheckCallback syncActivationCheckCallback_; 262 SyncActivationCheckCallbackV2 syncActivationCheckCallbackV2_; 263 264 mutable std::mutex userChangeMonitorLock_; 265 std::unique_ptr<UserChangeMonitor> userChangeMonitor_; 266 267 std::atomic<uint32_t> currentSessionId_; 268 269 // Get map from this callback, use for run permission check in remote device 270 mutable std::shared_mutex permissionConditionLock_; 271 PermissionConditionCallback permissionConditionCallback_; 272 273 mutable std::mutex statusAdapterMutex_; 274 std::shared_ptr<DBStatusAdapter> dbStatusAdapter_; 275 276 mutable std::mutex subscribeRecorderMutex_; 277 std::shared_ptr<SubscribeRecorder> subscribeRecorder_; 278 279 mutable std::mutex translateToDeviceIdLock_; 280 TranslateToDeviceIdCallback translateToDeviceIdCallback_; 281 std::map<std::string, std::map<std::string, std::string>> deviceIdCache_; // cache <uuid, <appId, newDeviceId>> 282 283 mutable std::shared_mutex threadPoolLock_; 284 std::shared_ptr<IThreadPool> threadPool_; 285 286 mutable std::mutex timerTaskLock_; 287 std::map<TimerId, TaskId> taskIds_; 288 std::map<TimerId, TimerFinalizer> timerFinalizers_; 289 290 mutable std::shared_mutex dataTranslateLock_; 291 std::shared_ptr<ICloudDataTranslate> dataTranslate_; 292 293 mutable std::mutex deviceTimeInfoLock_; 294 std::map<std::string, DeviceTimeInfo> deviceTimeInfos_; 295 std::map<std::vector<uint8_t>, bool> dbTimeChange_; 296 297 std::atomic<bool> isBatchDownloadAssets_; 298 299 mutable std::mutex assetsDownloadManagerLock_; 300 std::shared_ptr<AssetsDownloadManager> assetsDownloadManager_; 301 }; 302 } // namespace DistributedDB 303 304 #endif // RUNTIME_CONTEXT_IMPL_H 305