1 /*
2  * Copyright (c) 2022 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 #include "app_event_log_cleaner.h"
16 
17 #include <algorithm>
18 #include <cerrno>
19 #include <cmath>
20 
21 #include "file_util.h"
22 #include "hilog/log.h"
23 
24 #undef LOG_DOMAIN
25 #define LOG_DOMAIN 0xD002D07
26 
27 #undef LOG_TAG
28 #define LOG_TAG "LogCleaner"
29 
30 namespace OHOS {
31 namespace HiviewDFX {
GetFilesSize()32 uint64_t AppEventLogCleaner::GetFilesSize()
33 {
34     return FileUtil::GetDirSize(path_);
35 }
36 
ClearSpace(uint64_t curSize,uint64_t maxSize)37 uint64_t AppEventLogCleaner::ClearSpace(uint64_t curSize, uint64_t maxSize)
38 {
39     HILOG_INFO(LOG_CORE, "start to clear the space occupied by log files");
40     std::vector<std::string> files;
41     FileUtil::GetDirFiles(path_, files);
42 
43     // delete log files one by one based on the timestamp order of the file name
44     sort(files.begin(), files.end());
45 
46     uint64_t nowSize = curSize;
47     while (!files.empty() && nowSize > maxSize) {
48         std::string delFile = files[0];
49         files.erase(files.begin());
50         if (!FileUtil::IsFileExists(delFile)) {
51             HILOG_ERROR(LOG_CORE, "failed to access the log file, errno=%{public}d", errno);
52             continue;
53         }
54         uint64_t delFileSize = FileUtil::GetFileSize(delFile);
55         if (!FileUtil::RemoveFile(delFile)) {
56             HILOG_ERROR(LOG_CORE, "failed to remove the log file, errno=%{public}d", errno);
57             continue;
58         }
59         nowSize -= std::min(delFileSize, nowSize);
60     }
61     return nowSize;
62 }
63 
ClearData()64 void AppEventLogCleaner::ClearData()
65 {
66     HILOG_INFO(LOG_CORE, "start to clear the log data");
67     std::vector<std::string> files;
68     FileUtil::GetDirFiles(path_, files);
69     for (const auto& file : files) {
70         if (!FileUtil::RemoveFile(file)) {
71             HILOG_WARN(LOG_CORE, "failed to remove the log file=%{public}s", file.c_str());
72         } else {
73             HILOG_INFO(LOG_CORE, "succ to remove the log file=%{public}s", file.c_str());
74         }
75     }
76 }
77 } // namespace HiviewDFX
78 } // namespace OHOS
79