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