blob: a48ebc35a3e3ce9cad0ca8ed0f218d70cb5f6487 [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;
David Chenc136f452017-11-27 11:52:26 -080048const int FIELD_ID_UIDMAP_STATS = 8;
Bookatz1d0136d2017-12-01 11:13:32 -080049const int FIELD_ID_ANOMALY_ALARM_STATS = 9;
Yao Chenb3561512017-11-21 18:07:17 -080050
51const int FIELD_ID_MATCHER_STATS_NAME = 1;
52const int FIELD_ID_MATCHER_STATS_COUNT = 2;
53
54const int FIELD_ID_CONDITION_STATS_NAME = 1;
55const int FIELD_ID_CONDITION_STATS_COUNT = 2;
56
57const int FIELD_ID_METRIC_STATS_NAME = 1;
58const int FIELD_ID_METRIC_STATS_COUNT = 2;
59
60const int FIELD_ID_ATOM_STATS_TAG = 1;
61const int FIELD_ID_ATOM_STATS_COUNT = 2;
62
Bookatz1d0136d2017-12-01 11:13:32 -080063const int FIELD_ID_ANOMALY_ALARMS_REGISTERED = 1;
64
Yao Chenb3561512017-11-21 18:07:17 -080065// TODO: add stats for pulled atoms.
66StatsdStats::StatsdStats() {
67 mPushedAtomStats.resize(android::util::kMaxPushedAtomId + 1);
Yao Chen69f1baf2017-11-27 17:25:36 -080068 mStartTimeSec = time(nullptr);
Yao Chenb3561512017-11-21 18:07:17 -080069}
70
71StatsdStats& StatsdStats::getInstance() {
72 static StatsdStats statsInstance;
73 return statsInstance;
74}
75
76void StatsdStats::noteConfigReceived(const ConfigKey& key, int metricsCount, int conditionsCount,
77 int matchersCount, int alertsCount, bool isValid) {
78 lock_guard<std::mutex> lock(mLock);
79 int32_t nowTimeSec = time(nullptr);
80
81 // If there is an existing config for the same key, icebox the old config.
82 noteConfigRemovedInternalLocked(key);
83
84 StatsdStatsReport_ConfigStats configStats;
85 configStats.set_uid(key.GetUid());
86 configStats.set_name(key.GetName());
87 configStats.set_creation_time_sec(nowTimeSec);
88 configStats.set_metric_count(metricsCount);
89 configStats.set_condition_count(conditionsCount);
90 configStats.set_matcher_count(matchersCount);
91 configStats.set_alert_count(alertsCount);
92 configStats.set_is_valid(isValid);
93
94 if (isValid) {
95 mConfigStats[key] = configStats;
96 } else {
97 configStats.set_deletion_time_sec(nowTimeSec);
98 mIceBox.push_back(configStats);
99 }
100}
101
102void StatsdStats::noteConfigRemovedInternalLocked(const ConfigKey& key) {
103 auto it = mConfigStats.find(key);
104 if (it != mConfigStats.end()) {
105 int32_t nowTimeSec = time(nullptr);
106 it->second.set_deletion_time_sec(nowTimeSec);
107 // Add condition stats, metrics stats, matcher stats
108 addSubStatsToConfig(key, it->second);
109 // Remove them after they are added to the config stats.
110 mMatcherStats.erase(key);
111 mMetricsStats.erase(key);
112 mConditionStats.erase(key);
113 mIceBox.push_back(it->second);
Yao Chen69f1baf2017-11-27 17:25:36 -0800114 mConfigStats.erase(it);
Yao Chenb3561512017-11-21 18:07:17 -0800115 }
116}
117
118void StatsdStats::noteConfigRemoved(const ConfigKey& key) {
119 lock_guard<std::mutex> lock(mLock);
120 noteConfigRemovedInternalLocked(key);
121}
122
123void StatsdStats::noteBroadcastSent(const ConfigKey& key) {
Yao Chen0fac5b12017-11-28 16:07:02 -0800124 noteBroadcastSent(key, time(nullptr));
125}
126
127void StatsdStats::noteBroadcastSent(const ConfigKey& key, int32_t timeSec) {
Yao Chenb3561512017-11-21 18:07:17 -0800128 lock_guard<std::mutex> lock(mLock);
129 auto it = mConfigStats.find(key);
130 if (it == mConfigStats.end()) {
131 ALOGE("Config key %s not found!", key.ToString().c_str());
132 return;
133 }
Yao Chen0fac5b12017-11-28 16:07:02 -0800134 if (it->second.broadcast_sent_time_sec_size() >= kMaxTimestampCount) {
135 auto timestampList = it->second.mutable_broadcast_sent_time_sec();
136 // This is O(N) operation. It shouldn't happen often, and N is only 20.
137 timestampList->erase(timestampList->begin());
138 }
139 it->second.add_broadcast_sent_time_sec(timeSec);
Yao Chenb3561512017-11-21 18:07:17 -0800140}
141
Yao Chen69f1baf2017-11-27 17:25:36 -0800142void StatsdStats::noteDataDropped(const ConfigKey& key) {
Yao Chen0fac5b12017-11-28 16:07:02 -0800143 noteDataDropped(key, time(nullptr));
144}
145
146void StatsdStats::noteDataDropped(const ConfigKey& key, int32_t timeSec) {
Yao Chenb3561512017-11-21 18:07:17 -0800147 lock_guard<std::mutex> lock(mLock);
148 auto it = mConfigStats.find(key);
149 if (it == mConfigStats.end()) {
150 ALOGE("Config key %s not found!", key.ToString().c_str());
151 return;
152 }
Yao Chen0fac5b12017-11-28 16:07:02 -0800153 if (it->second.data_drop_time_sec_size() >= kMaxTimestampCount) {
154 auto timestampList = it->second.mutable_data_drop_time_sec();
155 // This is O(N) operation. It shouldn't happen often, and N is only 20.
156 timestampList->erase(timestampList->begin());
157 }
158 it->second.add_data_drop_time_sec(timeSec);
Yao Chenb3561512017-11-21 18:07:17 -0800159}
160
Yao Chen69f1baf2017-11-27 17:25:36 -0800161void StatsdStats::noteMetricsReportSent(const ConfigKey& key) {
Yao Chen0fac5b12017-11-28 16:07:02 -0800162 noteMetricsReportSent(key, time(nullptr));
163}
164
165void StatsdStats::noteMetricsReportSent(const ConfigKey& key, int32_t timeSec) {
Yao Chen69f1baf2017-11-27 17:25:36 -0800166 lock_guard<std::mutex> lock(mLock);
167 auto it = mConfigStats.find(key);
168 if (it == mConfigStats.end()) {
169 ALOGE("Config key %s not found!", key.ToString().c_str());
170 return;
171 }
Yao Chen0fac5b12017-11-28 16:07:02 -0800172 if (it->second.dump_report_time_sec_size() >= kMaxTimestampCount) {
173 auto timestampList = it->second.mutable_dump_report_time_sec();
174 // This is O(N) operation. It shouldn't happen often, and N is only 20.
175 timestampList->erase(timestampList->begin());
176 }
177 it->second.add_dump_report_time_sec(timeSec);
Yao Chen69f1baf2017-11-27 17:25:36 -0800178}
179
David Chenc136f452017-11-27 11:52:26 -0800180void StatsdStats::noteUidMapDropped(int snapshots, int deltas) {
181 lock_guard<std::mutex> lock(mLock);
182 mUidMapStats.set_dropped_snapshots(mUidMapStats.dropped_snapshots() + snapshots);
183 mUidMapStats.set_dropped_changes(mUidMapStats.dropped_changes() + deltas);
184}
185
186void StatsdStats::setUidMapSnapshots(int snapshots) {
187 lock_guard<std::mutex> lock(mLock);
188 mUidMapStats.set_snapshots(snapshots);
189}
190
191void StatsdStats::setUidMapChanges(int changes) {
192 lock_guard<std::mutex> lock(mLock);
193 mUidMapStats.set_changes(changes);
194}
195
196void StatsdStats::setCurrentUidMapMemory(int bytes) {
197 lock_guard<std::mutex> lock(mLock);
198 mUidMapStats.set_bytes_used(bytes);
199}
200
Yao Chenb3561512017-11-21 18:07:17 -0800201void StatsdStats::noteConditionDimensionSize(const ConfigKey& key, const string& name, int size) {
202 lock_guard<std::mutex> lock(mLock);
203 // if name doesn't exist before, it will create the key with count 0.
204 auto& conditionSizeMap = mConditionStats[key];
205 if (size > conditionSizeMap[name]) {
206 conditionSizeMap[name] = size;
207 }
208}
209
210void StatsdStats::noteMetricDimensionSize(const ConfigKey& key, const string& name, int size) {
211 lock_guard<std::mutex> lock(mLock);
212 // if name doesn't exist before, it will create the key with count 0.
213 auto& metricsDimensionMap = mMetricsStats[key];
214 if (size > metricsDimensionMap[name]) {
215 metricsDimensionMap[name] = size;
216 }
217}
218
219void StatsdStats::noteMatcherMatched(const ConfigKey& key, const string& name) {
220 lock_guard<std::mutex> lock(mLock);
221 auto& matcherStats = mMatcherStats[key];
222 matcherStats[name]++;
223}
224
Bookatz1d0136d2017-12-01 11:13:32 -0800225void StatsdStats::noteRegisteredAnomalyAlarmChanged() {
226 lock_guard<std::mutex> lock(mLock);
227 mAnomalyAlarmRegisteredStats++;
228}
229
Yao Chenb3561512017-11-21 18:07:17 -0800230void StatsdStats::noteAtomLogged(int atomId, int32_t timeSec) {
231 lock_guard<std::mutex> lock(mLock);
232
Yao Chen69f1baf2017-11-27 17:25:36 -0800233 if (timeSec < mStartTimeSec) {
Yao Chenb3561512017-11-21 18:07:17 -0800234 return;
235 }
236
237 if (atomId > android::util::kMaxPushedAtomId) {
238 ALOGW("not interested in atom %d", atomId);
239 return;
240 }
241
242 mPushedAtomStats[atomId]++;
243}
244
245void StatsdStats::reset() {
246 lock_guard<std::mutex> lock(mLock);
247 resetInternalLocked();
248}
249
250void StatsdStats::resetInternalLocked() {
251 // Reset the historical data, but keep the active ConfigStats
Yao Chen69f1baf2017-11-27 17:25:36 -0800252 mStartTimeSec = time(nullptr);
Yao Chenb3561512017-11-21 18:07:17 -0800253 mIceBox.clear();
254 mConditionStats.clear();
255 mMetricsStats.clear();
256 std::fill(mPushedAtomStats.begin(), mPushedAtomStats.end(), 0);
Bookatz1d0136d2017-12-01 11:13:32 -0800257 mAnomalyAlarmRegisteredStats = 0;
Yao Chenb3561512017-11-21 18:07:17 -0800258 mMatcherStats.clear();
Yao Chen0fac5b12017-11-28 16:07:02 -0800259 for (auto& config : mConfigStats) {
260 config.second.clear_broadcast_sent_time_sec();
261 config.second.clear_data_drop_time_sec();
262 config.second.clear_dump_report_time_sec();
263 config.second.clear_matcher_stats();
264 config.second.clear_condition_stats();
265 config.second.clear_metric_stats();
266 }
Yao Chenb3561512017-11-21 18:07:17 -0800267}
268
269void StatsdStats::addSubStatsToConfig(const ConfigKey& key,
270 StatsdStatsReport_ConfigStats& configStats) {
271 // Add matcher stats
272 if (mMatcherStats.find(key) != mMatcherStats.end()) {
273 const auto& matcherStats = mMatcherStats[key];
274 for (const auto& stats : matcherStats) {
275 auto output = configStats.add_matcher_stats();
276 output->set_name(stats.first);
277 output->set_matched_times(stats.second);
278 VLOG("matcher %s matched %d times", stats.first.c_str(), stats.second);
279 }
280 }
281 // Add condition stats
282 if (mConditionStats.find(key) != mConditionStats.end()) {
283 const auto& conditionStats = mConditionStats[key];
284 for (const auto& stats : conditionStats) {
285 auto output = configStats.add_condition_stats();
286 output->set_name(stats.first);
287 output->set_max_tuple_counts(stats.second);
288 VLOG("condition %s max output tuple size %d", stats.first.c_str(), stats.second);
289 }
290 }
291 // Add metrics stats
292 if (mMetricsStats.find(key) != mMetricsStats.end()) {
293 const auto& conditionStats = mMetricsStats[key];
294 for (const auto& stats : conditionStats) {
295 auto output = configStats.add_metric_stats();
296 output->set_name(stats.first);
297 output->set_max_tuple_counts(stats.second);
298 VLOG("metrics %s max output tuple size %d", stats.first.c_str(), stats.second);
299 }
300 }
301}
302
Yao Chen69f1baf2017-11-27 17:25:36 -0800303void StatsdStats::dumpStats(std::vector<uint8_t>* output, bool reset) {
Yao Chenb3561512017-11-21 18:07:17 -0800304 lock_guard<std::mutex> lock(mLock);
305
306 if (DEBUG) {
Yao Chen69f1baf2017-11-27 17:25:36 -0800307 time_t t = mStartTimeSec;
Yao Chenb3561512017-11-21 18:07:17 -0800308 struct tm* tm = localtime(&t);
309 char timeBuffer[80];
310 strftime(timeBuffer, sizeof(timeBuffer), "%Y-%m-%d %I:%M%p", tm);
311 VLOG("=================StatsdStats dump begins====================");
312 VLOG("Stats collection start second: %s", timeBuffer);
313 }
314 ProtoOutputStream proto;
Yao Chen69f1baf2017-11-27 17:25:36 -0800315 proto.write(FIELD_TYPE_INT32 | FIELD_ID_BEGIN_TIME, mStartTimeSec);
Yao Chenb3561512017-11-21 18:07:17 -0800316 proto.write(FIELD_TYPE_INT32 | FIELD_ID_END_TIME, (int32_t)time(nullptr));
317
318 VLOG("%lu Config in icebox: ", (unsigned long)mIceBox.size());
319 for (const auto& configStats : mIceBox) {
320 const int numBytes = configStats.ByteSize();
321 vector<char> buffer(numBytes);
322 configStats.SerializeToArray(&buffer[0], numBytes);
323 proto.write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_CONFIG_STATS, &buffer[0],
324 buffer.size());
325
326 // surround the whole block with DEBUG, so that compiler can strip out the code
327 // in production.
328 if (DEBUG) {
329 VLOG("*****ICEBOX*****");
330 VLOG("Config {%d-%s}: creation=%d, deletion=%d, #metric=%d, #condition=%d, "
331 "#matcher=%d, #alert=%d, #valid=%d",
332 configStats.uid(), configStats.name().c_str(), configStats.creation_time_sec(),
333 configStats.deletion_time_sec(), configStats.metric_count(),
334 configStats.condition_count(), configStats.matcher_count(),
335 configStats.alert_count(), configStats.is_valid());
336
337 for (const auto& broadcastTime : configStats.broadcast_sent_time_sec()) {
338 VLOG("\tbroadcast time: %d", broadcastTime);
339 }
340
341 for (const auto& dataDropTime : configStats.data_drop_time_sec()) {
342 VLOG("\tdata drop time: %d", dataDropTime);
343 }
344 }
345 }
346
347 for (auto& pair : mConfigStats) {
348 auto& configStats = pair.second;
349 if (DEBUG) {
350 VLOG("********Active Configs***********");
351 VLOG("Config {%d-%s}: creation=%d, deletion=%d, #metric=%d, #condition=%d, "
352 "#matcher=%d, #alert=%d, #valid=%d",
353 configStats.uid(), configStats.name().c_str(), configStats.creation_time_sec(),
354 configStats.deletion_time_sec(), configStats.metric_count(),
355 configStats.condition_count(), configStats.matcher_count(),
356 configStats.alert_count(), configStats.is_valid());
357 for (const auto& broadcastTime : configStats.broadcast_sent_time_sec()) {
358 VLOG("\tbroadcast time: %d", broadcastTime);
359 }
360
361 for (const auto& dataDropTime : configStats.data_drop_time_sec()) {
362 VLOG("\tdata drop time: %d", dataDropTime);
363 }
Yao Chen69f1baf2017-11-27 17:25:36 -0800364
365 for (const auto& dumpTime : configStats.dump_report_time_sec()) {
366 VLOG("\tdump report time: %d", dumpTime);
367 }
Yao Chenb3561512017-11-21 18:07:17 -0800368 }
369
370 addSubStatsToConfig(pair.first, configStats);
371
372 const int numBytes = configStats.ByteSize();
373 vector<char> buffer(numBytes);
374 configStats.SerializeToArray(&buffer[0], numBytes);
375 proto.write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_CONFIG_STATS, &buffer[0],
376 buffer.size());
377 // reset the sub stats, the source of truth is in the individual map
378 // they will be repopulated when dumpStats() is called again.
379 configStats.clear_matcher_stats();
380 configStats.clear_condition_stats();
381 configStats.clear_metric_stats();
382 }
383
384 VLOG("********Atom stats***********");
385 const size_t atomCounts = mPushedAtomStats.size();
386 for (size_t i = 2; i < atomCounts; i++) {
387 if (mPushedAtomStats[i] > 0) {
388 long long token =
389 proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_ATOM_STATS | FIELD_COUNT_REPEATED);
390 proto.write(FIELD_TYPE_INT32 | FIELD_ID_ATOM_STATS_TAG, (int32_t)i);
391 proto.write(FIELD_TYPE_INT32 | FIELD_ID_ATOM_STATS_COUNT, mPushedAtomStats[i]);
392 proto.end(token);
393
394 VLOG("Atom %lu->%d\n", (unsigned long)i, mPushedAtomStats[i]);
395 }
396 }
397
Bookatz1d0136d2017-12-01 11:13:32 -0800398 if (mAnomalyAlarmRegisteredStats > 0) {
399 VLOG("********AnomalyAlarmStats stats***********");
400 long long token = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_ANOMALY_ALARM_STATS);
401 proto.write(FIELD_TYPE_INT32 | FIELD_ID_ANOMALY_ALARMS_REGISTERED,
402 mAnomalyAlarmRegisteredStats);
403 proto.end(token);
404 VLOG("Anomaly alarm registrations: %d", mAnomalyAlarmRegisteredStats);
405 }
406
David Chenc136f452017-11-27 11:52:26 -0800407 const int numBytes = mUidMapStats.ByteSize();
408 vector<char> buffer(numBytes);
409 mUidMapStats.SerializeToArray(&buffer[0], numBytes);
410 proto.write(FIELD_TYPE_MESSAGE | FIELD_ID_UIDMAP_STATS, &buffer[0], buffer.size());
411 VLOG("UID map stats: bytes=%d, snapshots=%d, changes=%d, snapshots lost=%d, changes "
412 "lost=%d",
413 mUidMapStats.bytes_used(), mUidMapStats.snapshots(), mUidMapStats.changes(),
414 mUidMapStats.dropped_snapshots(), mUidMapStats.dropped_changes());
415
Yao Chenb3561512017-11-21 18:07:17 -0800416 output->clear();
417 size_t bufferSize = proto.size();
418 output->resize(bufferSize);
419
420 size_t pos = 0;
421 auto it = proto.data();
422 while (it.readBuffer() != NULL) {
423 size_t toRead = it.currentToRead();
424 std::memcpy(&((*output)[pos]), it.readBuffer(), toRead);
425 pos += toRead;
426 it.rp()->move(toRead);
427 }
428
429 if (reset) {
430 resetInternalLocked();
431 }
432
433 VLOG("reset=%d, returned proto size %lu", reset, (unsigned long)bufferSize);
434 VLOG("=================StatsdStats dump ends====================");
435}
436
437} // namespace statsd
438} // namespace os
439} // namespace android