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 private: 194 static constexpr int MAX_TP_THREADS = 10; // max threads of the task pool. 195 static constexpr int MIN_TP_THREADS = 1; // min threads of the task pool. 196 static constexpr int TASK_POOL_REPORTS_INTERVAL = 10000; // task pool reports its state every 10 seconds. 197 198 int PrepareLoop(IEventLoop *&loop); 199 int PrepareTaskPool(); 200 int AllocTimerId(IEvent *evTimer, TimerId &timerId); 201 std::shared_ptr<DBStatusAdapter> GetDBStatusAdapter(); 202 std::shared_ptr<SubscribeRecorder> GetSubscribeRecorder(); 203 204 int ScheduleTaskByThreadPool(const TaskAction &task) const; 205 206 int SetTimerByThreadPool(int milliSeconds, const TimerAction &action, 207 const TimerFinalizer &finalizer, bool allocTimerId, TimerId &timerId); 208 209 int ModifyTimerByThreadPool(TimerId timerId, int milliSeconds); 210 211 void RemoveTimerByThreadPool(TimerId timerId, bool wait); 212 213 void ThreadPoolTimerAction(int milliSeconds, const TimerAction &action, TimerId timerId); 214 215 // Context fields 216 mutable std::mutex labelMutex_; 217 std::string processLabel_; 218 219 // Communicator 220 mutable std::mutex communicatorLock_; 221 IAdapter *adapter_; 222 ICommunicatorAggregator *communicatorAggregator_; 223 224 // Loop and timer 225 mutable std::mutex loopLock_; 226 IEventLoop *mainLoop_; 227 std::mutex timersLock_; 228 TimerId currentTimerId_; 229 std::map<TimerId, IEvent *> timers_; 230 231 // Task pool 232 std::mutex taskLock_; 233 TaskPool *taskPool_; 234 TimerId taskPoolReportsTimerId_; 235 236 // TimeTick 237 mutable std::mutex timeTickMonitorLock_; 238 std::shared_ptr<TimeTickMonitor> timeTickMonitor_; 239 240 mutable std::shared_mutex permissionCheckCallbackMutex_ {}; 241 PermissionCheckCallback permissionCheckCallback_; 242 PermissionCheckCallbackV2 permissionCheckCallbackV2_; 243 PermissionCheckCallbackV3 permissionCheckCallbackV3_; 244 PermissionCheckCallbackV4 permissionCheckCallbackV4_; 245 246 AutoLaunch autoLaunch_; 247 248 // System api 249 mutable std::recursive_mutex systemApiAdapterLock_; 250 std::shared_ptr<IProcessSystemApiAdapter> systemApiAdapter_; 251 mutable std::mutex lockStatusLock_; // Mutex for lockStatusObserver_. 252 LockStatusObserver *lockStatusObserver_; 253 254 mutable std::shared_mutex databaseStatusCallbackMutex_ {}; 255 StoreStatusNotifier databaseStatusNotifyCallback_; 256 StoreStatusNotifierV2 databaseStatusNotifyCallbackV2_; 257 258 mutable std::shared_mutex syncActivationCheckCallbackMutex_ {}; 259 SyncActivationCheckCallback syncActivationCheckCallback_; 260 SyncActivationCheckCallbackV2 syncActivationCheckCallbackV2_; 261 262 mutable std::mutex userChangeMonitorLock_; 263 std::unique_ptr<UserChangeMonitor> userChangeMonitor_; 264 265 std::atomic<uint32_t> currentSessionId_; 266 267 // Get map from this callback, use for run permission check in remote device 268 mutable std::shared_mutex permissionConditionLock_; 269 PermissionConditionCallback permissionConditionCallback_; 270 271 mutable std::mutex statusAdapterMutex_; 272 std::shared_ptr<DBStatusAdapter> dbStatusAdapter_; 273 274 mutable std::mutex subscribeRecorderMutex_; 275 std::shared_ptr<SubscribeRecorder> subscribeRecorder_; 276 277 mutable std::mutex translateToDeviceIdLock_; 278 TranslateToDeviceIdCallback translateToDeviceIdCallback_; 279 std::map<std::string, std::map<std::string, std::string>> deviceIdCache_; // cache <uuid, <appId, newDeviceId>> 280 281 mutable std::shared_mutex threadPoolLock_; 282 std::shared_ptr<IThreadPool> threadPool_; 283 284 mutable std::mutex timerTaskLock_; 285 std::map<TimerId, TaskId> taskIds_; 286 std::map<TimerId, TimerFinalizer> timerFinalizers_; 287 288 mutable std::shared_mutex dataTranslateLock_; 289 std::shared_ptr<ICloudDataTranslate> dataTranslate_; 290 291 mutable std::mutex deviceTimeInfoLock_; 292 std::map<std::string, DeviceTimeInfo> deviceTimeInfos_; 293 std::map<std::vector<uint8_t>, bool> dbTimeChange_; 294 295 std::atomic<bool> isBatchDownloadAssets_; 296 297 mutable std::mutex assetsDownloadManagerLock_; 298 std::shared_ptr<AssetsDownloadManager> assetsDownloadManager_; 299 }; 300 } // namespace DistributedDB 301 302 #endif // RUNTIME_CONTEXT_IMPL_H 303