1 /*
2  * Copyright (c) 2024 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 OHOS_STORAGE_MANAGER_STORAGE_MONITOR_SERVICE_H
17 #define OHOS_STORAGE_MANAGER_STORAGE_MONITOR_SERVICE_H
18 
19 #include <iostream>
20 #include <nocopyable.h>
21 #include <singleton.h>
22 #include <thread>
23 #include <vector>
24 #include "event_handler.h"
25 
26 namespace OHOS {
27 namespace StorageManager {
28 const int SMART_EVENT_INTERVAL = 24; // 24h
29 const int SMART_EVENT_INTERVAL_HIGH_FREQ = 5; // 5m
30 class StorageMonitorService : public NoCopyable  {
31     DECLARE_DELAYED_SINGLETON(StorageMonitorService);
32 
33 public:
34     void StartStorageMonitorTask();
35 
36 private:
37     void StartEventHandler();
38     void Execute();
39     void MonitorAndManageStorage();
40     void CleanBundleCache(int64_t lowThreshold);
41     int64_t GetLowerThreshold(int64_t totalSize);
42     void CheckAndCleanCache(int64_t freeSize, int64_t totalSize);
43     void CheckAndEventNotify(int64_t freeSize, int64_t totalSize);
44     void SendSmartNotificationEvent(const std::string &faultDesc, const std::string &faultSuggest, bool isHighFreq);
45     void EventNotifyHighFreqHandler();
46     void CleanBundleCacheByInterval(const std::string &timestamp,
47                                     int64_t lowThreshold, int32_t checkInterval);
48     std::mutex eventMutex_;
49     std::thread eventThread_;
50     std::condition_variable eventCon_;
51     std::shared_ptr<AppExecFwk::EventHandler> eventHandler_ = nullptr;
52     std::chrono::steady_clock::time_point lastNotificationTime_ =
53             std::chrono::time_point_cast<std::chrono::steady_clock::duration>(
54                     std::chrono::steady_clock::now()) - std::chrono::hours(SMART_EVENT_INTERVAL);
55     std::chrono::steady_clock::time_point lastNotificationTimeHighFreq_ =
56             std::chrono::time_point_cast<std::chrono::steady_clock::duration>(
57                     std::chrono::steady_clock::now()) - std::chrono::minutes(SMART_EVENT_INTERVAL_HIGH_FREQ);
58 };
59 } // StorageManager
60 } // OHOS
61 
62 #endif // OHOS_STORAGE_MANAGER_STORAGE_MONITOR_SERVICE_H