1 /*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "perfstatsd"
18
19 #include <perfstatsd.h>
20
21 using namespace android::pixel::perfstatsd;
22
Perfstatsd(void)23 Perfstatsd::Perfstatsd(void) {
24 mRefreshPeriod = DEFAULT_DATA_COLLECT_PERIOD;
25
26 std::unique_ptr<StatsType> cpuUsage(new CpuUsage);
27 cpuUsage->setBufferSize(CPU_USAGE_BUFFER_SIZE);
28 mStats.emplace_back(std::move(cpuUsage));
29
30 std::unique_ptr<StatsType> ioUsage(new IoUsage);
31 ioUsage->setBufferSize(IO_USAGE_BUFFER_SIZE);
32 mStats.emplace_back(std::move(ioUsage));
33 }
34
refresh(void)35 void Perfstatsd::refresh(void) {
36 for (auto const &stats : mStats) {
37 stats->refresh();
38 }
39 return;
40 }
41
getHistory(std::string * ret)42 void Perfstatsd::getHistory(std::string *ret) {
43 std::priority_queue<StatsData, std::vector<StatsData>, StatsdataCompare> mergedQueue;
44 for (auto const &stats : mStats) {
45 stats->dump(&mergedQueue);
46 }
47
48 while (!mergedQueue.empty()) {
49 StatsData data = mergedQueue.top();
50 auto raw_time = data.getTime();
51 auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(raw_time);
52 auto d = raw_time - seconds;
53 auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(d);
54 std::string content = data.getData();
55
56 time_t t = std::chrono::system_clock::to_time_t(raw_time);
57 char buff[20];
58 strftime(buff, sizeof(buff), "%m-%d %H:%M:%S", localtime(&t));
59
60 ret->append(std::string(buff) + ".");
61 ret->append(std::to_string(milliseconds.count()) + "\n");
62 ret->append(content + "\n");
63 mergedQueue.pop();
64 }
65
66 if (ret->size() > 400_KiB)
67 LOG_TO(SYSTEM, WARNING) << "Data might be too large. size: " << ret->size() << " bytes\n"
68 << *ret;
69 }
70
setOptions(const std::string & key,const std::string & value)71 void Perfstatsd::setOptions(const std::string &key, const std::string &value) {
72 if (key == PERFSTATSD_PERIOD) {
73 uint32_t val = 0;
74 if (!base::ParseUint(value, &val) || val < 1) {
75 LOG_TO(SYSTEM, ERROR) << "Invalid value. Minimum refresh period is 1 second";
76 } else {
77 mRefreshPeriod = val;
78 LOG_TO(SYSTEM, INFO) << "set period to " << value << " seconds";
79 }
80 return;
81 }
82
83 for (auto const &stats : mStats) {
84 stats->setOptions(std::forward<const std::string>(key),
85 std::forward<const std::string>(value));
86 }
87 return;
88 }
89