blob: 2bd36126d340e75bed20c3234743e3a4c89466fa [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) {
Yao Chen0fac5b12017-11-28 16:07:02 -0800120 noteBroadcastSent(key, time(nullptr));
121}
122
123void StatsdStats::noteBroadcastSent(const ConfigKey& key, int32_t timeSec) {
Yao Chenb3561512017-11-21 18:07:17 -0800124 lock_guard<std::mutex> lock(mLock);
125 auto it = mConfigStats.find(key);
126 if (it == mConfigStats.end()) {
127 ALOGE("Config key %s not found!", key.ToString().c_str());
128 return;
129 }
Yao Chen0fac5b12017-11-28 16:07:02 -0800130 if (it->second.broadcast_sent_time_sec_size() >= kMaxTimestampCount) {
131 auto timestampList = it->second.mutable_broadcast_sent_time_sec();
132 // This is O(N) operation. It shouldn't happen often, and N is only 20.
133 timestampList->erase(timestampList->begin());
134 }
135 it->second.add_broadcast_sent_time_sec(timeSec);
Yao Chenb3561512017-11-21 18:07:17 -0800136}
137
Yao Chen69f1baf2017-11-27 17:25:36 -0800138void StatsdStats::noteDataDropped(const ConfigKey& key) {
Yao Chen0fac5b12017-11-28 16:07:02 -0800139 noteDataDropped(key, time(nullptr));
140}
141
142void StatsdStats::noteDataDropped(const ConfigKey& key, int32_t timeSec) {
Yao Chenb3561512017-11-21 18:07:17 -0800143 lock_guard<std::mutex> lock(mLock);
144 auto it = mConfigStats.find(key);
145 if (it == mConfigStats.end()) {
146 ALOGE("Config key %s not found!", key.ToString().c_str());
147 return;
148 }
Yao Chen0fac5b12017-11-28 16:07:02 -0800149 if (it->second.data_drop_time_sec_size() >= kMaxTimestampCount) {
150 auto timestampList = it->second.mutable_data_drop_time_sec();
151 // This is O(N) operation. It shouldn't happen often, and N is only 20.
152 timestampList->erase(timestampList->begin());
153 }
154 it->second.add_data_drop_time_sec(timeSec);
Yao Chenb3561512017-11-21 18:07:17 -0800155}
156
Yao Chen69f1baf2017-11-27 17:25:36 -0800157void StatsdStats::noteMetricsReportSent(const ConfigKey& key) {
Yao Chen0fac5b12017-11-28 16:07:02 -0800158 noteMetricsReportSent(key, time(nullptr));
159}
160
161void StatsdStats::noteMetricsReportSent(const ConfigKey& key, int32_t timeSec) {
Yao Chen69f1baf2017-11-27 17:25:36 -0800162 lock_guard<std::mutex> lock(mLock);
163 auto it = mConfigStats.find(key);
164 if (it == mConfigStats.end()) {
165 ALOGE("Config key %s not found!", key.ToString().c_str());
166 return;
167 }
Yao Chen0fac5b12017-11-28 16:07:02 -0800168 if (it->second.dump_report_time_sec_size() >= kMaxTimestampCount) {
169 auto timestampList = it->second.mutable_dump_report_time_sec();
170 // This is O(N) operation. It shouldn't happen often, and N is only 20.
171 timestampList->erase(timestampList->begin());
172 }
173 it->second.add_dump_report_time_sec(timeSec);
Yao Chen69f1baf2017-11-27 17:25:36 -0800174}
175
Yao Chenb3561512017-11-21 18:07:17 -0800176void StatsdStats::noteConditionDimensionSize(const ConfigKey& key, const string& name, int size) {
177 lock_guard<std::mutex> lock(mLock);
178 // if name doesn't exist before, it will create the key with count 0.
179 auto& conditionSizeMap = mConditionStats[key];
180 if (size > conditionSizeMap[name]) {
181 conditionSizeMap[name] = size;
182 }
183}
184
185void StatsdStats::noteMetricDimensionSize(const ConfigKey& key, const string& name, int size) {
186 lock_guard<std::mutex> lock(mLock);
187 // if name doesn't exist before, it will create the key with count 0.
188 auto& metricsDimensionMap = mMetricsStats[key];
189 if (size > metricsDimensionMap[name]) {
190 metricsDimensionMap[name] = size;
191 }
192}
193
194void StatsdStats::noteMatcherMatched(const ConfigKey& key, const string& name) {
195 lock_guard<std::mutex> lock(mLock);
196 auto& matcherStats = mMatcherStats[key];
197 matcherStats[name]++;
198}
199
200void StatsdStats::noteAtomLogged(int atomId, int32_t timeSec) {
201 lock_guard<std::mutex> lock(mLock);
202
Yao Chen69f1baf2017-11-27 17:25:36 -0800203 if (timeSec < mStartTimeSec) {
Yao Chenb3561512017-11-21 18:07:17 -0800204 return;
205 }
206
207 if (atomId > android::util::kMaxPushedAtomId) {
208 ALOGW("not interested in atom %d", atomId);
209 return;
210 }
211
212 mPushedAtomStats[atomId]++;
213}
214
215void StatsdStats::reset() {
216 lock_guard<std::mutex> lock(mLock);
217 resetInternalLocked();
218}
219
220void StatsdStats::resetInternalLocked() {
221 // Reset the historical data, but keep the active ConfigStats
Yao Chen69f1baf2017-11-27 17:25:36 -0800222 mStartTimeSec = time(nullptr);
Yao Chenb3561512017-11-21 18:07:17 -0800223 mIceBox.clear();
224 mConditionStats.clear();
225 mMetricsStats.clear();
226 std::fill(mPushedAtomStats.begin(), mPushedAtomStats.end(), 0);
227 mMatcherStats.clear();
Yao Chen0fac5b12017-11-28 16:07:02 -0800228 for (auto& config : mConfigStats) {
229 config.second.clear_broadcast_sent_time_sec();
230 config.second.clear_data_drop_time_sec();
231 config.second.clear_dump_report_time_sec();
232 config.second.clear_matcher_stats();
233 config.second.clear_condition_stats();
234 config.second.clear_metric_stats();
235 }
Yao Chenb3561512017-11-21 18:07:17 -0800236}
237
238void StatsdStats::addSubStatsToConfig(const ConfigKey& key,
239 StatsdStatsReport_ConfigStats& configStats) {
240 // Add matcher stats
241 if (mMatcherStats.find(key) != mMatcherStats.end()) {
242 const auto& matcherStats = mMatcherStats[key];
243 for (const auto& stats : matcherStats) {
244 auto output = configStats.add_matcher_stats();
245 output->set_name(stats.first);
246 output->set_matched_times(stats.second);
247 VLOG("matcher %s matched %d times", stats.first.c_str(), stats.second);
248 }
249 }
250 // Add condition stats
251 if (mConditionStats.find(key) != mConditionStats.end()) {
252 const auto& conditionStats = mConditionStats[key];
253 for (const auto& stats : conditionStats) {
254 auto output = configStats.add_condition_stats();
255 output->set_name(stats.first);
256 output->set_max_tuple_counts(stats.second);
257 VLOG("condition %s max output tuple size %d", stats.first.c_str(), stats.second);
258 }
259 }
260 // Add metrics stats
261 if (mMetricsStats.find(key) != mMetricsStats.end()) {
262 const auto& conditionStats = mMetricsStats[key];
263 for (const auto& stats : conditionStats) {
264 auto output = configStats.add_metric_stats();
265 output->set_name(stats.first);
266 output->set_max_tuple_counts(stats.second);
267 VLOG("metrics %s max output tuple size %d", stats.first.c_str(), stats.second);
268 }
269 }
270}
271
Yao Chen69f1baf2017-11-27 17:25:36 -0800272void StatsdStats::dumpStats(std::vector<uint8_t>* output, bool reset) {
Yao Chenb3561512017-11-21 18:07:17 -0800273 lock_guard<std::mutex> lock(mLock);
274
275 if (DEBUG) {
Yao Chen69f1baf2017-11-27 17:25:36 -0800276 time_t t = mStartTimeSec;
Yao Chenb3561512017-11-21 18:07:17 -0800277 struct tm* tm = localtime(&t);
278 char timeBuffer[80];
279 strftime(timeBuffer, sizeof(timeBuffer), "%Y-%m-%d %I:%M%p", tm);
280 VLOG("=================StatsdStats dump begins====================");
281 VLOG("Stats collection start second: %s", timeBuffer);
282 }
283 ProtoOutputStream proto;
Yao Chen69f1baf2017-11-27 17:25:36 -0800284 proto.write(FIELD_TYPE_INT32 | FIELD_ID_BEGIN_TIME, mStartTimeSec);
Yao Chenb3561512017-11-21 18:07:17 -0800285 proto.write(FIELD_TYPE_INT32 | FIELD_ID_END_TIME, (int32_t)time(nullptr));
286
287 VLOG("%lu Config in icebox: ", (unsigned long)mIceBox.size());
288 for (const auto& configStats : mIceBox) {
289 const int numBytes = configStats.ByteSize();
290 vector<char> buffer(numBytes);
291 configStats.SerializeToArray(&buffer[0], numBytes);
292 proto.write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_CONFIG_STATS, &buffer[0],
293 buffer.size());
294
295 // surround the whole block with DEBUG, so that compiler can strip out the code
296 // in production.
297 if (DEBUG) {
298 VLOG("*****ICEBOX*****");
299 VLOG("Config {%d-%s}: creation=%d, deletion=%d, #metric=%d, #condition=%d, "
300 "#matcher=%d, #alert=%d, #valid=%d",
301 configStats.uid(), configStats.name().c_str(), configStats.creation_time_sec(),
302 configStats.deletion_time_sec(), configStats.metric_count(),
303 configStats.condition_count(), configStats.matcher_count(),
304 configStats.alert_count(), configStats.is_valid());
305
306 for (const auto& broadcastTime : configStats.broadcast_sent_time_sec()) {
307 VLOG("\tbroadcast time: %d", broadcastTime);
308 }
309
310 for (const auto& dataDropTime : configStats.data_drop_time_sec()) {
311 VLOG("\tdata drop time: %d", dataDropTime);
312 }
313 }
314 }
315
316 for (auto& pair : mConfigStats) {
317 auto& configStats = pair.second;
318 if (DEBUG) {
319 VLOG("********Active Configs***********");
320 VLOG("Config {%d-%s}: creation=%d, deletion=%d, #metric=%d, #condition=%d, "
321 "#matcher=%d, #alert=%d, #valid=%d",
322 configStats.uid(), configStats.name().c_str(), configStats.creation_time_sec(),
323 configStats.deletion_time_sec(), configStats.metric_count(),
324 configStats.condition_count(), configStats.matcher_count(),
325 configStats.alert_count(), configStats.is_valid());
326 for (const auto& broadcastTime : configStats.broadcast_sent_time_sec()) {
327 VLOG("\tbroadcast time: %d", broadcastTime);
328 }
329
330 for (const auto& dataDropTime : configStats.data_drop_time_sec()) {
331 VLOG("\tdata drop time: %d", dataDropTime);
332 }
Yao Chen69f1baf2017-11-27 17:25:36 -0800333
334 for (const auto& dumpTime : configStats.dump_report_time_sec()) {
335 VLOG("\tdump report time: %d", dumpTime);
336 }
Yao Chenb3561512017-11-21 18:07:17 -0800337 }
338
339 addSubStatsToConfig(pair.first, configStats);
340
341 const int numBytes = configStats.ByteSize();
342 vector<char> buffer(numBytes);
343 configStats.SerializeToArray(&buffer[0], numBytes);
344 proto.write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_CONFIG_STATS, &buffer[0],
345 buffer.size());
346 // reset the sub stats, the source of truth is in the individual map
347 // they will be repopulated when dumpStats() is called again.
348 configStats.clear_matcher_stats();
349 configStats.clear_condition_stats();
350 configStats.clear_metric_stats();
351 }
352
353 VLOG("********Atom stats***********");
354 const size_t atomCounts = mPushedAtomStats.size();
355 for (size_t i = 2; i < atomCounts; i++) {
356 if (mPushedAtomStats[i] > 0) {
357 long long token =
358 proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_ATOM_STATS | FIELD_COUNT_REPEATED);
359 proto.write(FIELD_TYPE_INT32 | FIELD_ID_ATOM_STATS_TAG, (int32_t)i);
360 proto.write(FIELD_TYPE_INT32 | FIELD_ID_ATOM_STATS_COUNT, mPushedAtomStats[i]);
361 proto.end(token);
362
363 VLOG("Atom %lu->%d\n", (unsigned long)i, mPushedAtomStats[i]);
364 }
365 }
366
367 output->clear();
368 size_t bufferSize = proto.size();
369 output->resize(bufferSize);
370
371 size_t pos = 0;
372 auto it = proto.data();
373 while (it.readBuffer() != NULL) {
374 size_t toRead = it.currentToRead();
375 std::memcpy(&((*output)[pos]), it.readBuffer(), toRead);
376 pos += toRead;
377 it.rp()->move(toRead);
378 }
379
380 if (reset) {
381 resetInternalLocked();
382 }
383
384 VLOG("reset=%d, returned proto size %lu", reset, (unsigned long)bufferSize);
385 VLOG("=================StatsdStats dump ends====================");
386}
387
388} // namespace statsd
389} // namespace os
390} // namespace android