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 #include "memory_catcher.h"
16
17 #include "collect_result.h"
18 #include "file_util.h"
19 #include "memory_collector.h"
20
21 namespace OHOS {
22 namespace HiviewDFX {
23 using namespace UCollect;
24 using namespace UCollectUtil;
MemoryCatcher()25 MemoryCatcher::MemoryCatcher() : EventLogCatcher()
26 {
27 name_ = "MemoryCatcher";
28 }
29
Initialize(const std::string& strParam1, int intParam1, int intParam2)30 bool MemoryCatcher::Initialize(const std::string& strParam1, int intParam1, int intParam2)
31 {
32 // this catcher do not need parameters, just return true
33 description_ = "MemoryCatcher --\n";
34 return true;
35 };
36
Catch(int fd, int jsonFd)37 int MemoryCatcher::Catch(int fd, int jsonFd)
38 {
39 int originSize = GetFdSize(fd);
40 std::shared_ptr<MemoryCollector> collector = MemoryCollector::Create();
41 CollectResult<SysMemory> result = collector->CollectSysMemory();
42 if (result.retCode == UcError::SUCCESS) {
43 std::string pressMemInfo = "";
44 FileUtil::LoadStringFromFile("/proc/pressure/memory", pressMemInfo);
45 FileUtil::SaveStringToFd(fd, pressMemInfo);
46 FileUtil::SaveStringToFd(fd, "memTotal " + std::to_string(result.data.memTotal) + "\n");
47 FileUtil::SaveStringToFd(fd, "memFree " + std::to_string(result.data.memFree) + "\n");
48 FileUtil::SaveStringToFd(fd, "memAvailable " + std::to_string(result.data.memAvailable) + "\n");
49 FileUtil::SaveStringToFd(fd, "zramUsed " + std::to_string(result.data.zramUsed) + "\n");
50 FileUtil::SaveStringToFd(fd, "swapCached " + std::to_string(result.data.swapCached) + "\n");
51 FileUtil::SaveStringToFd(fd, "cached " + std::to_string(result.data.cached) + "\n");
52 }
53 logSize_ = GetFdSize(fd) - originSize;
54 if (logSize_ <= 0) {
55 FileUtil::SaveStringToFd(fd, "sysMemory content is empty!");
56 }
57
58 collector->CollectRawMemInfo();
59 collector->ExportMemView();
60
61 return logSize_;
62 };
63 } // namespace HiviewDFX
64 } // namespace OHOS
65