blob: 2ab1146208ee032f556d4ac218fe77ce229bab9f [file] [log] [blame]
Yao Chenb3561512017-11-21 18:07:17 -08001/*
2 * Copyright 2017, 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#define DEBUG true // STOPSHIP if true
17#include "Log.h"
18
19#include "StatsdStats.h"
20
21#include <android/util/ProtoOutputStream.h>
22#include "statslog.h"
23
24namespace android {
25namespace os {
26namespace statsd {
27
28using android::util::FIELD_COUNT_REPEATED;
29using android::util::FIELD_TYPE_BOOL;
30using android::util::FIELD_TYPE_FLOAT;
31using android::util::FIELD_TYPE_INT32;
32using android::util::FIELD_TYPE_INT64;
33using android::util::FIELD_TYPE_MESSAGE;
34using android::util::FIELD_TYPE_STRING;
35using android::util::ProtoOutputStream;
36using std::lock_guard;
37using std::map;
38using std::string;
39using std::vector;
40
41const int FIELD_ID_BEGIN_TIME = 1;
42const int FIELD_ID_END_TIME = 2;
43const int FIELD_ID_CONFIG_STATS = 3;
44const int FIELD_ID_MATCHER_STATS = 4;
45const int FIELD_ID_CONDITION_STATS = 5;
46const int FIELD_ID_METRIC_STATS = 6;
47const int FIELD_ID_ATOM_STATS = 7;
48
49const int FIELD_ID_MATCHER_STATS_NAME = 1;
50const int FIELD_ID_MATCHER_STATS_COUNT = 2;
51
52const int FIELD_ID_CONDITION_STATS_NAME = 1;
53const int FIELD_ID_CONDITION_STATS_COUNT = 2;
54
55const int FIELD_ID_METRIC_STATS_NAME = 1;
56const int FIELD_ID_METRIC_STATS_COUNT = 2;
57
58const int FIELD_ID_ATOM_STATS_TAG = 1;
59const int FIELD_ID_ATOM_STATS_COUNT = 2;
60
61// TODO: add stats for pulled atoms.
62StatsdStats::StatsdStats() {
63 mPushedAtomStats.resize(android::util::kMaxPushedAtomId + 1);
Yao Chen69f1baf2017-11-27 17:25:36 -080064 mStartTimeSec = time(nullptr);
Yao Chenb3561512017-11-21 18:07:17 -080065}
66
67StatsdStats& StatsdStats::getInstance() {
68 static StatsdStats statsInstance;
69 return statsInstance;
70}
71
72void StatsdStats::noteConfigReceived(const ConfigKey& key, int metricsCount, int conditionsCount,
73 int matchersCount, int alertsCount, bool isValid) {
74 lock_guard<std::mutex> lock(mLock);
75 int32_t nowTimeSec = time(nullptr);
76
77 // If there is an existing config for the same key, icebox the old config.
78 noteConfigRemovedInternalLocked(key);
79
80 StatsdStatsReport_ConfigStats configStats;
81 configStats.set_uid(key.GetUid());
82 configStats.set_name(key.GetName());
83 configStats.set_creation_time_sec(nowTimeSec);
84 configStats.set_metric_count(metricsCount);
85 configStats.set_condition_count(conditionsCount);
86 configStats.set_matcher_count(matchersCount);
87 configStats.set_alert_count(alertsCount);
88 configStats.set_is_valid(isValid);
89
90 if (isValid) {
91 mConfigStats[key] = configStats;
92 } else {
93 configStats.set_deletion_time_sec(nowTimeSec);
94 mIceBox.push_back(configStats);
95 }
96}
97
98void StatsdStats::noteConfigRemovedInternalLocked(const ConfigKey& key) {
99 auto it = mConfigStats.find(key);
100 if (it != mConfigStats.end()) {
101 int32_t nowTimeSec = time(nullptr);
102 it->second.set_deletion_time_sec(nowTimeSec);
103 // Add condition stats, metrics stats, matcher stats
104 addSubStatsToConfig(key, it->second);
105 // Remove them after they are added to the config stats.
106 mMatcherStats.erase(key);
107 mMetricsStats.erase(key);
108 mConditionStats.erase(key);
109 mIceBox.push_back(it->second);
Yao Chen69f1baf2017-11-27 17:25:36 -0800110 mConfigStats.erase(it);
Yao Chenb3561512017-11-21 18:07:17 -0800111 }
112}
113
114void StatsdStats::noteConfigRemoved(const ConfigKey& key) {
115 lock_guard<std::mutex> lock(mLock);
116 noteConfigRemovedInternalLocked(key);
117}
118
119void StatsdStats::noteBroadcastSent(const ConfigKey& key) {
120 lock_guard<std::mutex> lock(mLock);
121 auto it = mConfigStats.find(key);
122 if (it == mConfigStats.end()) {
123 ALOGE("Config key %s not found!", key.ToString().c_str());
124 return;
125 }
126
127 it->second.add_broadcast_sent_time_sec(time(nullptr));
128}
129
Yao Chen69f1baf2017-11-27 17:25:36 -0800130void StatsdStats::noteDataDropped(const ConfigKey& key) {
Yao Chenb3561512017-11-21 18:07:17 -0800131 lock_guard<std::mutex> lock(mLock);
132 auto it = mConfigStats.find(key);
133 if (it == mConfigStats.end()) {
134 ALOGE("Config key %s not found!", key.ToString().c_str());
135 return;
136 }
137
138 it->second.add_data_drop_time_sec(time(nullptr));
139}
140
Yao Chen69f1baf2017-11-27 17:25:36 -0800141void StatsdStats::noteMetricsReportSent(const ConfigKey& key) {
142 lock_guard<std::mutex> lock(mLock);
143 auto it = mConfigStats.find(key);
144 if (it == mConfigStats.end()) {
145 ALOGE("Config key %s not found!", key.ToString().c_str());
146 return;
147 }
148
149 it->second.add_dump_report_time_sec(time(nullptr));
150}
151
Yao Chenb3561512017-11-21 18:07:17 -0800152void StatsdStats::noteConditionDimensionSize(const ConfigKey& key, const string& name, int size) {
153 lock_guard<std::mutex> lock(mLock);
154 // if name doesn't exist before, it will create the key with count 0.
155 auto& conditionSizeMap = mConditionStats[key];
156 if (size > conditionSizeMap[name]) {
157 conditionSizeMap[name] = size;
158 }
159}
160
161void StatsdStats::noteMetricDimensionSize(const ConfigKey& key, const string& name, int size) {
162 lock_guard<std::mutex> lock(mLock);
163 // if name doesn't exist before, it will create the key with count 0.
164 auto& metricsDimensionMap = mMetricsStats[key];
165 if (size > metricsDimensionMap[name]) {
166 metricsDimensionMap[name] = size;
167 }
168}
169
170void StatsdStats::noteMatcherMatched(const ConfigKey& key, const string& name) {
171 lock_guard<std::mutex> lock(mLock);
172 auto& matcherStats = mMatcherStats[key];
173 matcherStats[name]++;
174}
175
176void StatsdStats::noteAtomLogged(int atomId, int32_t timeSec) {
177 lock_guard<std::mutex> lock(mLock);
178
Yao Chen69f1baf2017-11-27 17:25:36 -0800179 if (timeSec < mStartTimeSec) {
Yao Chenb3561512017-11-21 18:07:17 -0800180 return;
181 }
182
183 if (atomId > android::util::kMaxPushedAtomId) {
184 ALOGW("not interested in atom %d", atomId);
185 return;
186 }
187
188 mPushedAtomStats[atomId]++;
189}
190
191void StatsdStats::reset() {
192 lock_guard<std::mutex> lock(mLock);
193 resetInternalLocked();
194}
195
196void StatsdStats::resetInternalLocked() {
197 // Reset the historical data, but keep the active ConfigStats
Yao Chen69f1baf2017-11-27 17:25:36 -0800198 mStartTimeSec = time(nullptr);
Yao Chenb3561512017-11-21 18:07:17 -0800199 mIceBox.clear();
200 mConditionStats.clear();
201 mMetricsStats.clear();
202 std::fill(mPushedAtomStats.begin(), mPushedAtomStats.end(), 0);
203 mMatcherStats.clear();
204}
205
206void StatsdStats::addSubStatsToConfig(const ConfigKey& key,
207 StatsdStatsReport_ConfigStats& configStats) {
208 // Add matcher stats
209 if (mMatcherStats.find(key) != mMatcherStats.end()) {
210 const auto& matcherStats = mMatcherStats[key];
211 for (const auto& stats : matcherStats) {
212 auto output = configStats.add_matcher_stats();
213 output->set_name(stats.first);
214 output->set_matched_times(stats.second);
215 VLOG("matcher %s matched %d times", stats.first.c_str(), stats.second);
216 }
217 }
218 // Add condition stats
219 if (mConditionStats.find(key) != mConditionStats.end()) {
220 const auto& conditionStats = mConditionStats[key];
221 for (const auto& stats : conditionStats) {
222 auto output = configStats.add_condition_stats();
223 output->set_name(stats.first);
224 output->set_max_tuple_counts(stats.second);
225 VLOG("condition %s max output tuple size %d", stats.first.c_str(), stats.second);
226 }
227 }
228 // Add metrics stats
229 if (mMetricsStats.find(key) != mMetricsStats.end()) {
230 const auto& conditionStats = mMetricsStats[key];
231 for (const auto& stats : conditionStats) {
232 auto output = configStats.add_metric_stats();
233 output->set_name(stats.first);
234 output->set_max_tuple_counts(stats.second);
235 VLOG("metrics %s max output tuple size %d", stats.first.c_str(), stats.second);
236 }
237 }
238}
239
Yao Chen69f1baf2017-11-27 17:25:36 -0800240void StatsdStats::dumpStats(std::vector<uint8_t>* output, bool reset) {
Yao Chenb3561512017-11-21 18:07:17 -0800241 lock_guard<std::mutex> lock(mLock);
242
243 if (DEBUG) {
Yao Chen69f1baf2017-11-27 17:25:36 -0800244 time_t t = mStartTimeSec;
Yao Chenb3561512017-11-21 18:07:17 -0800245 struct tm* tm = localtime(&t);
246 char timeBuffer[80];
247 strftime(timeBuffer, sizeof(timeBuffer), "%Y-%m-%d %I:%M%p", tm);
248 VLOG("=================StatsdStats dump begins====================");
249 VLOG("Stats collection start second: %s", timeBuffer);
250 }
251 ProtoOutputStream proto;
Yao Chen69f1baf2017-11-27 17:25:36 -0800252 proto.write(FIELD_TYPE_INT32 | FIELD_ID_BEGIN_TIME, mStartTimeSec);
Yao Chenb3561512017-11-21 18:07:17 -0800253 proto.write(FIELD_TYPE_INT32 | FIELD_ID_END_TIME, (int32_t)time(nullptr));
254
255 VLOG("%lu Config in icebox: ", (unsigned long)mIceBox.size());
256 for (const auto& configStats : mIceBox) {
257 const int numBytes = configStats.ByteSize();
258 vector<char> buffer(numBytes);
259 configStats.SerializeToArray(&buffer[0], numBytes);
260 proto.write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_CONFIG_STATS, &buffer[0],
261 buffer.size());
262
263 // surround the whole block with DEBUG, so that compiler can strip out the code
264 // in production.
265 if (DEBUG) {
266 VLOG("*****ICEBOX*****");
267 VLOG("Config {%d-%s}: creation=%d, deletion=%d, #metric=%d, #condition=%d, "
268 "#matcher=%d, #alert=%d, #valid=%d",
269 configStats.uid(), configStats.name().c_str(), configStats.creation_time_sec(),
270 configStats.deletion_time_sec(), configStats.metric_count(),
271 configStats.condition_count(), configStats.matcher_count(),
272 configStats.alert_count(), configStats.is_valid());
273
274 for (const auto& broadcastTime : configStats.broadcast_sent_time_sec()) {
275 VLOG("\tbroadcast time: %d", broadcastTime);
276 }
277
278 for (const auto& dataDropTime : configStats.data_drop_time_sec()) {
279 VLOG("\tdata drop time: %d", dataDropTime);
280 }
281 }
282 }
283
284 for (auto& pair : mConfigStats) {
285 auto& configStats = pair.second;
286 if (DEBUG) {
287 VLOG("********Active Configs***********");
288 VLOG("Config {%d-%s}: creation=%d, deletion=%d, #metric=%d, #condition=%d, "
289 "#matcher=%d, #alert=%d, #valid=%d",
290 configStats.uid(), configStats.name().c_str(), configStats.creation_time_sec(),
291 configStats.deletion_time_sec(), configStats.metric_count(),
292 configStats.condition_count(), configStats.matcher_count(),
293 configStats.alert_count(), configStats.is_valid());
294 for (const auto& broadcastTime : configStats.broadcast_sent_time_sec()) {
295 VLOG("\tbroadcast time: %d", broadcastTime);
296 }
297
298 for (const auto& dataDropTime : configStats.data_drop_time_sec()) {
299 VLOG("\tdata drop time: %d", dataDropTime);
300 }
Yao Chen69f1baf2017-11-27 17:25:36 -0800301
302 for (const auto& dumpTime : configStats.dump_report_time_sec()) {
303 VLOG("\tdump report time: %d", dumpTime);
304 }
Yao Chenb3561512017-11-21 18:07:17 -0800305 }
306
307 addSubStatsToConfig(pair.first, configStats);
308
309 const int numBytes = configStats.ByteSize();
310 vector<char> buffer(numBytes);
311 configStats.SerializeToArray(&buffer[0], numBytes);
312 proto.write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_CONFIG_STATS, &buffer[0],
313 buffer.size());
314 // reset the sub stats, the source of truth is in the individual map
315 // they will be repopulated when dumpStats() is called again.
316 configStats.clear_matcher_stats();
317 configStats.clear_condition_stats();
318 configStats.clear_metric_stats();
319 }
320
321 VLOG("********Atom stats***********");
322 const size_t atomCounts = mPushedAtomStats.size();
323 for (size_t i = 2; i < atomCounts; i++) {
324 if (mPushedAtomStats[i] > 0) {
325 long long token =
326 proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_ATOM_STATS | FIELD_COUNT_REPEATED);
327 proto.write(FIELD_TYPE_INT32 | FIELD_ID_ATOM_STATS_TAG, (int32_t)i);
328 proto.write(FIELD_TYPE_INT32 | FIELD_ID_ATOM_STATS_COUNT, mPushedAtomStats[i]);
329 proto.end(token);
330
331 VLOG("Atom %lu->%d\n", (unsigned long)i, mPushedAtomStats[i]);
332 }
333 }
334
335 output->clear();
336 size_t bufferSize = proto.size();
337 output->resize(bufferSize);
338
339 size_t pos = 0;
340 auto it = proto.data();
341 while (it.readBuffer() != NULL) {
342 size_t toRead = it.currentToRead();
343 std::memcpy(&((*output)[pos]), it.readBuffer(), toRead);
344 pos += toRead;
345 it.rp()->move(toRead);
346 }
347
348 if (reset) {
349 resetInternalLocked();
350 }
351
352 VLOG("reset=%d, returned proto size %lu", reset, (unsigned long)bufferSize);
353 VLOG("=================StatsdStats dump ends====================");
354}
355
356} // namespace statsd
357} // namespace os
358} // namespace android