blob: 69cb264ef2373737ff2a86224a0ef65fe8910e19 [file] [log] [blame]
Yao Chenab273e22017-09-06 12:53:50 -07001/*
2 * Copyright (C) 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
Yangster-mac754e29e2018-05-02 12:23:17 -070017#define DEBUG false // STOPSHIP if true
Joe Onorato9fc9edf2017-10-15 20:08:52 -070018#include "Log.h"
David Chen21582962017-11-01 17:32:46 -070019#include "statslog.h"
Yao Chenab273e22017-09-06 12:53:50 -070020
yro947fbce2017-11-15 22:50:23 -080021#include <android-base/file.h>
22#include <dirent.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070023#include "StatsLogProcessor.h"
Yangster-mac330af582018-02-08 15:24:38 -080024#include "stats_log_util.h"
yro947fbce2017-11-15 22:50:23 -080025#include "android-base/stringprintf.h"
Yao Chenb3561512017-11-21 18:07:17 -080026#include "guardrail/StatsdStats.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070027#include "metrics/CountMetricProducer.h"
Chenjie Yu85ed8382017-12-14 16:48:54 -080028#include "external/StatsPullerManager.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070029#include "stats_util.h"
yro947fbce2017-11-15 22:50:23 -080030#include "storage/StorageManager.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070031
yro00698da2017-09-15 10:06:40 -070032#include <log/log_event_list.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070033#include <utils/Errors.h>
David Chen16049572018-02-01 18:27:51 -080034#include <utils/SystemClock.h>
Yao Chenab273e22017-09-06 12:53:50 -070035
36using namespace android;
yro947fbce2017-11-15 22:50:23 -080037using android::base::StringPrintf;
yrob0378b02017-11-09 20:36:25 -080038using android::util::FIELD_COUNT_REPEATED;
yro17adac92017-11-08 23:16:29 -080039using android::util::FIELD_TYPE_BOOL;
40using android::util::FIELD_TYPE_FLOAT;
41using android::util::FIELD_TYPE_INT32;
42using android::util::FIELD_TYPE_INT64;
43using android::util::FIELD_TYPE_MESSAGE;
44using android::util::FIELD_TYPE_STRING;
45using android::util::ProtoOutputStream;
Yao Chen44cf27c2017-09-14 22:32:50 -070046using std::make_unique;
47using std::unique_ptr;
48using std::vector;
Bookatz906a35c2017-09-20 15:26:44 -070049
50namespace android {
51namespace os {
52namespace statsd {
Yao Chenab273e22017-09-06 12:53:50 -070053
yro947fbce2017-11-15 22:50:23 -080054// for ConfigMetricsReportList
yro17adac92017-11-08 23:16:29 -080055const int FIELD_ID_CONFIG_KEY = 1;
yro947fbce2017-11-15 22:50:23 -080056const int FIELD_ID_REPORTS = 2;
yro17adac92017-11-08 23:16:29 -080057// for ConfigKey
58const int FIELD_ID_UID = 1;
Yangster-mac94e197c2018-01-02 16:03:03 -080059const int FIELD_ID_ID = 2;
yro947fbce2017-11-15 22:50:23 -080060// for ConfigMetricsReport
Yao Chen4c959cb2018-02-13 13:27:48 -080061// const int FIELD_ID_METRICS = 1; // written in MetricsManager.cpp
yro947fbce2017-11-15 22:50:23 -080062const int FIELD_ID_UID_MAP = 2;
Yangster-mac330af582018-02-08 15:24:38 -080063const int FIELD_ID_LAST_REPORT_ELAPSED_NANOS = 3;
64const int FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS = 4;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -080065const int FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS = 5;
66const int FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS = 6;
Chenjie Yue36018b2018-04-16 15:18:30 -070067const int FIELD_ID_DUMP_REPORT_REASON = 8;
Yangster-mac9def8e32018-04-17 13:55:51 -070068const int FIELD_ID_STRINGS = 9;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -080069
Yangster-macb142cc82018-03-30 15:22:08 -070070#define NS_PER_HOUR 3600 * NS_PER_SEC
yro947fbce2017-11-15 22:50:23 -080071
yro03faf092017-12-12 00:17:50 -080072#define STATS_DATA_DIR "/data/misc/stats-data"
yro17adac92017-11-08 23:16:29 -080073
Tej Singh42f9e062018-11-09 10:01:00 -080074// Cool down period for writing data to disk to avoid overwriting files.
75#define WRITE_DATA_COOL_DOWN_SEC 5
76
yro31eb67b2017-10-24 13:33:21 -070077StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
Chenjie Yue2219202018-06-08 10:07:51 -070078 const sp<StatsPullerManager>& pullerManager,
Yangster-mac932ecec2018-02-01 10:23:52 -080079 const sp<AlarmMonitor>& anomalyAlarmMonitor,
80 const sp<AlarmMonitor>& periodicAlarmMonitor,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070081 const int64_t timeBaseNs,
David Chen48944902018-05-03 10:29:11 -070082 const std::function<bool(const ConfigKey&)>& sendBroadcast)
Chenjie Yu85ed8382017-12-14 16:48:54 -080083 : mUidMap(uidMap),
Chenjie Yue2219202018-06-08 10:07:51 -070084 mPullerManager(pullerManager),
Yangster-mac932ecec2018-02-01 10:23:52 -080085 mAnomalyAlarmMonitor(anomalyAlarmMonitor),
86 mPeriodicAlarmMonitor(periodicAlarmMonitor),
Chenjie Yu85ed8382017-12-14 16:48:54 -080087 mSendBroadcast(sendBroadcast),
Yangster-mac15f6bbc2018-04-08 11:52:26 -070088 mTimeBaseNs(timeBaseNs),
Yao Chen163d2602018-04-10 10:39:53 -070089 mLargestTimestampSeen(0),
90 mLastTimestampSeen(0) {
Chenjie Yue2219202018-06-08 10:07:51 -070091 mPullerManager->ForceClearPullerCache();
Yao Chenab273e22017-09-06 12:53:50 -070092}
93
Yao Chenef99c4f2017-09-22 16:26:54 -070094StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -070095}
96
Yangster-mace2cd6d52017-11-09 20:38:30 -080097void StatsLogProcessor::onAnomalyAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -070098 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -080099 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
Yangster-macb0d06282018-01-05 15:44:07 -0800100 std::lock_guard<std::mutex> lock(mMetricsMutex);
Bookatzcc5adef22017-11-21 14:36:23 -0800101 for (const auto& itr : mMetricsManagers) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800102 itr.second->onAnomalyAlarmFired(timestampNs, alarmSet);
103 }
104}
105void StatsLogProcessor::onPeriodicAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700106 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800107 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
108
109 std::lock_guard<std::mutex> lock(mMetricsMutex);
110 for (const auto& itr : mMetricsManagers) {
111 itr.second->onPeriodicAlarmFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800112 }
113}
114
Yao Chen8a8d16c2018-02-08 14:50:40 -0800115void updateUid(Value* value, int hostUid) {
116 int uid = value->int_value;
117 if (uid != hostUid) {
118 value->setInt(hostUid);
119 }
120}
121
Yangster-macd40053e2018-01-09 16:29:22 -0800122void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
Yao Chenc40a19d2018-03-15 16:48:25 -0700123 if (android::util::AtomsInfo::kAtomsWithAttributionChain.find(event->GetTagId()) !=
124 android::util::AtomsInfo::kAtomsWithAttributionChain.end()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800125 for (auto& value : *(event->getMutableValues())) {
126 if (value.mField.getPosAtDepth(0) > kAttributionField) {
127 break;
128 }
129 if (isAttributionUidField(value)) {
130 const int hostUid = mUidMap->getHostUidOrSelf(value.mValue.int_value);
131 updateUid(&value.mValue, hostUid);
132 }
Yangster-macd40053e2018-01-09 16:29:22 -0800133 }
Yao Chenc40a19d2018-03-15 16:48:25 -0700134 } else {
135 auto it = android::util::AtomsInfo::kAtomsWithUidField.find(event->GetTagId());
136 if (it != android::util::AtomsInfo::kAtomsWithUidField.end()) {
137 int uidField = it->second; // uidField is the field number in proto,
138 // starting from 1
139 if (uidField > 0 && (int)event->getValues().size() >= uidField &&
140 (event->getValues())[uidField - 1].mValue.getType() == INT) {
141 Value& value = (*event->getMutableValues())[uidField - 1].mValue;
142 const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
143 updateUid(&value, hostUid);
144 } else {
145 ALOGE("Malformed log, uid not found. %s", event->ToString().c_str());
146 }
147 }
Yao Chen312e8982017-12-05 15:29:03 -0800148 }
Yangster-macd40053e2018-01-09 16:29:22 -0800149}
150
151void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
152 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
153 bool is_create = event.GetBool(3, &err);
154 auto parent_uid = int(event.GetLong(1, &err2));
155 auto isolated_uid = int(event.GetLong(2, &err3));
156 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
157 if (is_create) {
158 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
159 } else {
Bookatz3c648862018-05-25 13:32:43 -0700160 mUidMap->removeIsolatedUid(isolated_uid);
Yangster-macd40053e2018-01-09 16:29:22 -0800161 }
162 } else {
163 ALOGE("Failed to parse uid in the isolated uid change event.");
164 }
165}
166
Yangster-mac892f3d32018-05-02 14:16:48 -0700167void StatsLogProcessor::resetConfigs() {
168 std::lock_guard<std::mutex> lock(mMetricsMutex);
169 resetConfigsLocked(getElapsedRealtimeNs());
170}
171
172void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs) {
173 std::vector<ConfigKey> configKeys;
174 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
175 configKeys.push_back(it->first);
176 }
177 resetConfigsLocked(timestampNs, configKeys);
178}
179
Yao Chen3ff3a492018-08-06 16:17:37 -0700180void StatsLogProcessor::OnLogEvent(LogEvent* event) {
Yangster-macd40053e2018-01-09 16:29:22 -0800181 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen876889c2018-05-02 11:16:16 -0700182
183#ifdef VERY_VERBOSE_PRINTING
184 if (mPrintAllLogs) {
185 ALOGI("%s", event->ToString().c_str());
186 }
187#endif
Yangster-macb142cc82018-03-30 15:22:08 -0700188 const int64_t currentTimestampNs = event->GetElapsedTimestampNs();
Yangster-macb8382a12018-04-04 10:39:12 -0700189
Yangster-macb142cc82018-03-30 15:22:08 -0700190 resetIfConfigTtlExpiredLocked(currentTimestampNs);
191
Yangster-macd40053e2018-01-09 16:29:22 -0800192 StatsdStats::getInstance().noteAtomLogged(
Yangster-mac330af582018-02-08 15:24:38 -0800193 event->GetTagId(), event->GetElapsedTimestampNs() / NS_PER_SEC);
Yangster-macd40053e2018-01-09 16:29:22 -0800194
David Chen21582962017-11-01 17:32:46 -0700195 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800196 // The field numbers need to be currently updated by hand with atoms.proto
Yangster-macd40053e2018-01-09 16:29:22 -0800197 if (event->GetTagId() == android::util::ISOLATED_UID_CHANGED) {
198 onIsolatedUidChangedEventLocked(*event);
David Chencfc311d2018-01-23 17:55:54 -0800199 }
200
201 if (mMetricsManagers.empty()) {
202 return;
203 }
204
Yangster-macb142cc82018-03-30 15:22:08 -0700205 int64_t curTimeSec = getElapsedRealtimeSec();
Yangster-mac330af582018-02-08 15:24:38 -0800206 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
Chenjie Yue2219202018-06-08 10:07:51 -0700207 mPullerManager->ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
Yangster-mac330af582018-02-08 15:24:38 -0800208 mLastPullerCacheClearTimeSec = curTimeSec;
Chenjie Yufa22d652018-02-05 14:37:48 -0800209 }
210
Yangster-macb142cc82018-03-30 15:22:08 -0700211
David Chencfc311d2018-01-23 17:55:54 -0800212 if (event->GetTagId() != android::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800213 // Map the isolated uid to host uid if necessary.
214 mapIsolatedUidToHostUidIfNecessaryLocked(event);
215 }
216
217 // pass the event to metrics managers.
218 for (auto& pair : mMetricsManagers) {
219 pair.second->onLogEvent(*event);
Yangster-mac330af582018-02-08 15:24:38 -0800220 flushIfNecessaryLocked(event->GetElapsedTimestampNs(), pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700221 }
Yao Chenab273e22017-09-06 12:53:50 -0700222}
223
Yangster-macc04feba2018-04-02 14:37:33 -0700224void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
225 const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800226 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac892f3d32018-05-02 14:16:48 -0700227 WriteDataToDiskLocked(key, timestampNs, CONFIG_UPDATED);
Yangster-macb142cc82018-03-30 15:22:08 -0700228 OnConfigUpdatedLocked(timestampNs, key, config);
229}
230
231void StatsLogProcessor::OnConfigUpdatedLocked(
232 const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
Tej Singh484524a2018-02-01 15:10:05 -0800233 VLOG("Updated configuration for key %s", key.ToString().c_str());
Yangster-mac932ecec2018-02-01 10:23:52 -0800234 sp<MetricsManager> newMetricsManager =
Chenjie Yue2219202018-06-08 10:07:51 -0700235 new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap, mPullerManager,
236 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
Yao Chencaf339d2017-10-06 16:01:10 -0700237 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700238 mUidMap->OnConfigUpdated(key);
Yao Chen147ce602017-12-22 14:35:34 -0800239 if (newMetricsManager->shouldAddUidMapListener()) {
Yao Chend10f7b12017-12-18 12:53:50 -0800240 // We have to add listener after the MetricsManager is constructed because it's
241 // not safe to create wp or sp from this pointer inside its constructor.
242 mUidMap->addListener(newMetricsManager.get());
243 }
Yangster-macb142cc82018-03-30 15:22:08 -0700244 newMetricsManager->refreshTtl(timestampNs);
Yao Chend10f7b12017-12-18 12:53:50 -0800245 mMetricsManagers[key] = newMetricsManager;
Yao Chenb3561512017-11-21 18:07:17 -0800246 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700247 } else {
248 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800249 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700250 }
yro00698da2017-09-15 10:06:40 -0700251}
Bookatz906a35c2017-09-20 15:26:44 -0700252
Yangster7c334a12017-11-22 14:24:24 -0800253size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800254 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700255 auto it = mMetricsManagers.find(key);
256 if (it == mMetricsManagers.end()) {
257 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800258 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700259 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800260 return it->second->byteSize();
261}
262
Yao Chena80e5c02018-09-04 13:55:29 -0700263void StatsLogProcessor::dumpStates(int out, bool verbose) {
Yao Chen884c8c12018-01-26 10:36:25 -0800264 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chena80e5c02018-09-04 13:55:29 -0700265 FILE* fout = fdopen(out, "w");
266 if (fout == NULL) {
267 return;
Yao Chen884c8c12018-01-26 10:36:25 -0800268 }
Yao Chena80e5c02018-09-04 13:55:29 -0700269 fprintf(fout, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
270 for (auto metricsManager : mMetricsManagers) {
271 metricsManager.second->dumpStates(fout, verbose);
272 }
273
274 fclose(fout);
Yao Chen884c8c12018-01-26 10:36:25 -0800275}
276
yro4beccbe2018-03-15 19:42:05 -0700277/*
Bookatz9cc7b662018-11-06 10:39:21 -0800278 * onDumpReport dumps serialized ConfigMetricsReportList into proto.
yro4beccbe2018-03-15 19:42:05 -0700279 */
Yangster-macb142cc82018-03-30 15:22:08 -0700280void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700281 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700282 const bool erase_data,
Chenjie Yue36018b2018-04-16 15:18:30 -0700283 const DumpReportReason dumpReportReason,
Bookatzff71cad2018-09-20 17:17:49 -0700284 ProtoOutputStream* proto) {
Yangster-macb0d06282018-01-05 15:44:07 -0800285 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800286
yro947fbce2017-11-15 22:50:23 -0800287 // Start of ConfigKey.
Bookatzff71cad2018-09-20 17:17:49 -0700288 uint64_t configKeyToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
289 proto->write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
290 proto->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
291 proto->end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800292 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800293
yro947fbce2017-11-15 22:50:23 -0800294 // Then, check stats-data directory to see there's any file containing
295 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
Bookatzc71d9012018-12-19 12:28:38 -0800296 StorageManager::appendConfigMetricsReport(key, proto, erase_data);
yro947fbce2017-11-15 22:50:23 -0800297
Yangster-mace68f3a52018-04-04 00:01:43 -0700298 auto it = mMetricsManagers.find(key);
299 if (it != mMetricsManagers.end()) {
300 // This allows another broadcast to be sent within the rate-limit period if we get close to
301 // filling the buffer again soon.
302 mLastBroadcastTimes.erase(key);
303
304 // Start of ConfigMetricsReport (reports).
305 uint64_t reportsToken =
Bookatzff71cad2018-09-20 17:17:49 -0700306 proto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
Chenjie Yue36018b2018-04-16 15:18:30 -0700307 onConfigMetricsReportLocked(key, dumpTimeStampNs, include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700308 erase_data, dumpReportReason, proto);
309 proto->end(reportsToken);
Yangster-mace68f3a52018-04-04 00:01:43 -0700310 // End of ConfigMetricsReport (reports).
311 } else {
312 ALOGW("Config source %s does not exist", key.ToString().c_str());
313 }
Bookatzff71cad2018-09-20 17:17:49 -0700314}
315
316/*
317 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
318 */
319void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
320 const bool include_current_partial_bucket,
321 const bool erase_data,
322 const DumpReportReason dumpReportReason,
323 vector<uint8_t>* outData) {
324 ProtoOutputStream proto;
325 onDumpReport(key, dumpTimeStampNs, include_current_partial_bucket, erase_data,
326 dumpReportReason, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700327
David Chen1d7b0cd2017-11-15 14:20:04 -0800328 if (outData != nullptr) {
329 outData->clear();
330 outData->resize(proto.size());
331 size_t pos = 0;
332 auto iter = proto.data();
333 while (iter.readBuffer() != NULL) {
334 size_t toRead = iter.currentToRead();
335 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
336 pos += toRead;
337 iter.rp()->move(toRead);
338 }
yro17adac92017-11-08 23:16:29 -0800339 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800340
Yangster-mace68f3a52018-04-04 00:01:43 -0700341 StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
Yao Chen729093d2017-10-16 10:33:26 -0700342}
343
yro4beccbe2018-03-15 19:42:05 -0700344/*
345 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
346 */
347void StatsLogProcessor::onConfigMetricsReportLocked(const ConfigKey& key,
Yangster-macb142cc82018-03-30 15:22:08 -0700348 const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700349 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700350 const bool erase_data,
Chenjie Yue36018b2018-04-16 15:18:30 -0700351 const DumpReportReason dumpReportReason,
yro4beccbe2018-03-15 19:42:05 -0700352 ProtoOutputStream* proto) {
353 // We already checked whether key exists in mMetricsManagers in
354 // WriteDataToDisk.
355 auto it = mMetricsManagers.find(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700356 if (it == mMetricsManagers.end()) {
357 return;
358 }
yro4beccbe2018-03-15 19:42:05 -0700359 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
360 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
361
Yangster-mac9def8e32018-04-17 13:55:51 -0700362 std::set<string> str_set;
363
yro4beccbe2018-03-15 19:42:05 -0700364 // First, fill in ConfigMetricsReport using current data on memory, which
365 // starts from filling in StatsLogReport's.
Yangster-mac9def8e32018-04-17 13:55:51 -0700366 it->second->onDumpReport(dumpTimeStampNs, include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700367 erase_data, &str_set, proto);
yro4beccbe2018-03-15 19:42:05 -0700368
David Chen9e6dbbd2018-05-07 17:52:29 -0700369 // Fill in UidMap if there is at least one metric to report.
370 // This skips the uid map if it's an empty config.
371 if (it->second->getNumMetrics() > 0) {
372 uint64_t uidMapToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
dwchen730403e2018-10-29 11:41:56 -0700373 mUidMap->appendUidMap(
374 dumpTimeStampNs, key, it->second->hashStringInReport() ? &str_set : nullptr,
375 it->second->versionStringsInReport(), it->second->installerInReport(), proto);
David Chen9e6dbbd2018-05-07 17:52:29 -0700376 proto->end(uidMapToken);
377 }
yro4beccbe2018-03-15 19:42:05 -0700378
379 // Fill in the timestamps.
380 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
381 (long long)lastReportTimeNs);
382 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
383 (long long)dumpTimeStampNs);
384 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
385 (long long)lastReportWallClockNs);
386 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
387 (long long)getWallClockNs());
Chenjie Yue36018b2018-04-16 15:18:30 -0700388 // Dump report reason
389 proto->write(FIELD_TYPE_INT32 | FIELD_ID_DUMP_REPORT_REASON, dumpReportReason);
Yangster-mac9def8e32018-04-17 13:55:51 -0700390
David Chen56ae0d92018-05-11 16:00:22 -0700391 for (const auto& str : str_set) {
392 proto->write(FIELD_TYPE_STRING | FIELD_COUNT_REPEATED | FIELD_ID_STRINGS, str);
Yangster-mac9def8e32018-04-17 13:55:51 -0700393 }
Yangster-macb142cc82018-03-30 15:22:08 -0700394}
yro4beccbe2018-03-15 19:42:05 -0700395
Yao Chen163d2602018-04-10 10:39:53 -0700396void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
397 const std::vector<ConfigKey>& configs) {
398 for (const auto& key : configs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700399 StatsdConfig config;
400 if (StorageManager::readConfigFromDisk(key, &config)) {
401 OnConfigUpdatedLocked(timestampNs, key, config);
402 StatsdStats::getInstance().noteConfigReset(key);
403 } else {
404 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
405 auto it = mMetricsManagers.find(key);
406 if (it != mMetricsManagers.end()) {
407 it->second->refreshTtl(timestampNs);
408 }
409 }
410 }
yro4beccbe2018-03-15 19:42:05 -0700411}
412
Yao Chen163d2602018-04-10 10:39:53 -0700413void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
414 std::vector<ConfigKey> configKeysTtlExpired;
415 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
416 if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
417 configKeysTtlExpired.push_back(it->first);
418 }
419 }
420 if (configKeysTtlExpired.size() > 0) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700421 WriteDataToDiskLocked(CONFIG_RESET);
Yao Chen163d2602018-04-10 10:39:53 -0700422 resetConfigsLocked(timestampNs, configKeysTtlExpired);
423 }
424}
425
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700426void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800427 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700428 auto it = mMetricsManagers.find(key);
429 if (it != mMetricsManagers.end()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700430 WriteDataToDiskLocked(key, getElapsedRealtimeNs(), CONFIG_REMOVED);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700431 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700432 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700433 }
Yao Chenb3561512017-11-21 18:07:17 -0800434 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800435
David Chen1d7b0cd2017-11-15 14:20:04 -0800436 mLastBroadcastTimes.erase(key);
Chenjie Yufa22d652018-02-05 14:37:48 -0800437
438 if (mMetricsManagers.empty()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700439 mPullerManager->ForceClearPullerCache();
Chenjie Yufa22d652018-02-05 14:37:48 -0800440 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700441}
442
Yangster-macb0d06282018-01-05 15:44:07 -0800443void StatsLogProcessor::flushIfNecessaryLocked(
Yangster-macb142cc82018-03-30 15:22:08 -0700444 int64_t timestampNs, const ConfigKey& key, MetricsManager& metricsManager) {
David Chend9269e22017-12-05 13:43:51 -0800445 auto lastCheckTime = mLastByteSizeTimes.find(key);
446 if (lastCheckTime != mLastByteSizeTimes.end()) {
447 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
448 return;
449 }
450 }
451
452 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
453 size_t totalBytes = metricsManager.byteSize();
454 mLastByteSizeTimes[key] = timestampNs;
David Chen48944902018-05-03 10:29:11 -0700455 bool requestDump = false;
David Chend9269e22017-12-05 13:43:51 -0800456 if (totalBytes >
457 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen06dba5d2018-01-26 13:38:16 -0800458 metricsManager.dropData(timestampNs);
Chenjie Yuc3c30c02018-10-26 09:48:07 -0700459 StatsdStats::getInstance().noteDataDropped(key, totalBytes);
David Chen12942952017-12-04 14:28:43 -0800460 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chen48944902018-05-03 10:29:11 -0700461 } else if ((totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) ||
462 (mOnDiskDataConfigs.find(key) != mOnDiskDataConfigs.end())) {
463 // Request to send a broadcast if:
464 // 1. in memory data > threshold OR
465 // 2. config has old data report on disk.
466 requestDump = true;
467 }
468
469 if (requestDump) {
David Chend9269e22017-12-05 13:43:51 -0800470 // Send broadcast so that receivers can pull data.
471 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
472 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
473 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
474 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800475 return;
476 }
477 }
David Chen48944902018-05-03 10:29:11 -0700478 if (mSendBroadcast(key)) {
479 mOnDiskDataConfigs.erase(key);
480 VLOG("StatsD triggered data fetch for %s", key.ToString().c_str());
481 mLastBroadcastTimes[key] = timestampNs;
482 StatsdStats::getInstance().noteBroadcastSent(key);
483 }
yro31eb67b2017-10-24 13:33:21 -0700484 }
485}
486
Chenjie Yue36018b2018-04-16 15:18:30 -0700487void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key,
Yangster-mac892f3d32018-05-02 14:16:48 -0700488 const int64_t timestampNs,
Chenjie Yue36018b2018-04-16 15:18:30 -0700489 const DumpReportReason dumpReportReason) {
yro028091c2018-05-09 16:03:27 -0700490 if (mMetricsManagers.find(key) == mMetricsManagers.end() ||
491 !mMetricsManagers.find(key)->second->shouldWriteToDisk()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700492 return;
493 }
Yangster-mace68f3a52018-04-04 00:01:43 -0700494 ProtoOutputStream proto;
David Chen56ae0d92018-05-11 16:00:22 -0700495 onConfigMetricsReportLocked(key, timestampNs, true /* include_current_partial_bucket*/,
Bookatzff71cad2018-09-20 17:17:49 -0700496 true /* erase_data */, dumpReportReason, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700497 string file_name = StringPrintf("%s/%ld_%d_%lld", STATS_DATA_DIR,
498 (long)getWallClockSec(), key.GetUid(), (long long)key.GetId());
499 android::base::unique_fd fd(open(file_name.c_str(),
500 O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
501 if (fd == -1) {
502 ALOGE("Attempt to write %s but failed", file_name.c_str());
503 return;
504 }
505 proto.flush(fd.get());
David Chen48944902018-05-03 10:29:11 -0700506 // We were able to write the ConfigMetricsReport to disk, so we should trigger collection ASAP.
507 mOnDiskDataConfigs.insert(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700508}
509
Chenjie Yue36018b2018-04-16 15:18:30 -0700510void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700511 const int64_t timeNs = getElapsedRealtimeNs();
Tej Singh42f9e062018-11-09 10:01:00 -0800512 // Do not write to disk if we already have in the last few seconds.
513 // This is to avoid overwriting files that would have the same name if we
514 // write twice in the same second.
515 if (static_cast<unsigned long long> (timeNs) <
516 mLastWriteTimeNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
517 ALOGI("Statsd skipping writing data to disk. Already wrote data in last %d seconds",
518 WRITE_DATA_COOL_DOWN_SEC);
519 return;
520 }
521 mLastWriteTimeNs = timeNs;
Yangster-mace68f3a52018-04-04 00:01:43 -0700522 for (auto& pair : mMetricsManagers) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700523 WriteDataToDiskLocked(pair.first, timeNs, dumpReportReason);
Yangster-mace68f3a52018-04-04 00:01:43 -0700524 }
525}
526
Yangster-mac892f3d32018-05-02 14:16:48 -0700527void StatsLogProcessor::WriteDataToDisk(const DumpReportReason dumpReportReason) {
Yangster-macb0d06282018-01-05 15:44:07 -0800528 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac892f3d32018-05-02 14:16:48 -0700529 WriteDataToDiskLocked(dumpReportReason);
yro947fbce2017-11-15 22:50:23 -0800530}
531
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700532void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
Yangster6df5fcc2018-04-12 11:04:29 -0700533 std::lock_guard<std::mutex> lock(mMetricsMutex);
Chenjie Yue2219202018-06-08 10:07:51 -0700534 mPullerManager->OnAlarmFired(timestampNs);
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700535}
536
David Chend37bc232018-04-12 18:05:11 -0700537int64_t StatsLogProcessor::getLastReportTimeNs(const ConfigKey& key) {
538 auto it = mMetricsManagers.find(key);
539 if (it == mMetricsManagers.end()) {
540 return 0;
541 } else {
542 return it->second->getLastReportTimeNs();
543 }
544}
545
David Chen48944902018-05-03 10:29:11 -0700546void StatsLogProcessor::noteOnDiskData(const ConfigKey& key) {
547 std::lock_guard<std::mutex> lock(mMetricsMutex);
548 mOnDiskDataConfigs.insert(key);
549}
550
Yao Chenef99c4f2017-09-22 16:26:54 -0700551} // namespace statsd
552} // namespace os
553} // namespace android