blob: dd18bd4cc8ad814104cae0865adcbb22904058c9 [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
Chenjie Yuc7939cb2019-02-04 17:25:45 -080017#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>
Chenjie Yuc7939cb2019-02-04 17:25:45 -080023#include <frameworks/base/cmds/statsd/src/active_config_list.pb.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070024#include "StatsLogProcessor.h"
yro947fbce2017-11-15 22:50:23 -080025#include "android-base/stringprintf.h"
Chenjie Yuc7939cb2019-02-04 17:25:45 -080026#include "external/StatsPullerManager.h"
Yao Chenb3561512017-11-21 18:07:17 -080027#include "guardrail/StatsdStats.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070028#include "metrics/CountMetricProducer.h"
Chenjie Yuc7939cb2019-02-04 17:25:45 -080029#include "stats_log_util.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070030#include "stats_util.h"
yro947fbce2017-11-15 22:50:23 -080031#include "storage/StorageManager.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070032
yro00698da2017-09-15 10:06:40 -070033#include <log/log_event_list.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070034#include <utils/Errors.h>
David Chen16049572018-02-01 18:27:51 -080035#include <utils/SystemClock.h>
Yao Chenab273e22017-09-06 12:53:50 -070036
37using namespace android;
yro947fbce2017-11-15 22:50:23 -080038using android::base::StringPrintf;
yrob0378b02017-11-09 20:36:25 -080039using android::util::FIELD_COUNT_REPEATED;
yro17adac92017-11-08 23:16:29 -080040using android::util::FIELD_TYPE_BOOL;
41using android::util::FIELD_TYPE_FLOAT;
42using android::util::FIELD_TYPE_INT32;
43using android::util::FIELD_TYPE_INT64;
44using android::util::FIELD_TYPE_MESSAGE;
45using android::util::FIELD_TYPE_STRING;
46using android::util::ProtoOutputStream;
Yao Chen44cf27c2017-09-14 22:32:50 -070047using std::make_unique;
48using std::unique_ptr;
49using std::vector;
Bookatz906a35c2017-09-20 15:26:44 -070050
51namespace android {
52namespace os {
53namespace statsd {
Yao Chenab273e22017-09-06 12:53:50 -070054
yro947fbce2017-11-15 22:50:23 -080055// for ConfigMetricsReportList
yro17adac92017-11-08 23:16:29 -080056const int FIELD_ID_CONFIG_KEY = 1;
yro947fbce2017-11-15 22:50:23 -080057const int FIELD_ID_REPORTS = 2;
yro17adac92017-11-08 23:16:29 -080058// for ConfigKey
59const int FIELD_ID_UID = 1;
Yangster-mac94e197c2018-01-02 16:03:03 -080060const int FIELD_ID_ID = 2;
yro947fbce2017-11-15 22:50:23 -080061// for ConfigMetricsReport
Yao Chen4c959cb2018-02-13 13:27:48 -080062// const int FIELD_ID_METRICS = 1; // written in MetricsManager.cpp
yro947fbce2017-11-15 22:50:23 -080063const int FIELD_ID_UID_MAP = 2;
Yangster-mac330af582018-02-08 15:24:38 -080064const int FIELD_ID_LAST_REPORT_ELAPSED_NANOS = 3;
65const int FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS = 4;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -080066const int FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS = 5;
67const int FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS = 6;
Chenjie Yue36018b2018-04-16 15:18:30 -070068const int FIELD_ID_DUMP_REPORT_REASON = 8;
Yangster-mac9def8e32018-04-17 13:55:51 -070069const int FIELD_ID_STRINGS = 9;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -080070
Chenjie Yuc7939cb2019-02-04 17:25:45 -080071const int FIELD_ID_ACTIVE_CONFIG_LIST = 1;
72const int FIELD_ID_CONFIG_ID = 1;
73const int FIELD_ID_CONFIG_UID = 2;
74const int FIELD_ID_ACTIVE_METRIC = 3;
75const int FIELD_ID_METRIC_ID = 1;
76const int FIELD_ID_TIME_TO_LIVE_NANOS = 2;
77
Yangster-macb142cc82018-03-30 15:22:08 -070078#define NS_PER_HOUR 3600 * NS_PER_SEC
yro947fbce2017-11-15 22:50:23 -080079
yro03faf092017-12-12 00:17:50 -080080#define STATS_DATA_DIR "/data/misc/stats-data"
Chenjie Yuc7939cb2019-02-04 17:25:45 -080081#define STATS_ACTIVE_METRIC_DIR "/data/misc/stats-active-metric"
yro17adac92017-11-08 23:16:29 -080082
Tej Singh42f9e062018-11-09 10:01:00 -080083// Cool down period for writing data to disk to avoid overwriting files.
84#define WRITE_DATA_COOL_DOWN_SEC 5
85
yro31eb67b2017-10-24 13:33:21 -070086StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
Chenjie Yue2219202018-06-08 10:07:51 -070087 const sp<StatsPullerManager>& pullerManager,
Yangster-mac932ecec2018-02-01 10:23:52 -080088 const sp<AlarmMonitor>& anomalyAlarmMonitor,
89 const sp<AlarmMonitor>& periodicAlarmMonitor,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070090 const int64_t timeBaseNs,
David Chen48944902018-05-03 10:29:11 -070091 const std::function<bool(const ConfigKey&)>& sendBroadcast)
Chenjie Yu85ed8382017-12-14 16:48:54 -080092 : mUidMap(uidMap),
Chenjie Yue2219202018-06-08 10:07:51 -070093 mPullerManager(pullerManager),
Yangster-mac932ecec2018-02-01 10:23:52 -080094 mAnomalyAlarmMonitor(anomalyAlarmMonitor),
95 mPeriodicAlarmMonitor(periodicAlarmMonitor),
Chenjie Yu85ed8382017-12-14 16:48:54 -080096 mSendBroadcast(sendBroadcast),
Yangster-mac15f6bbc2018-04-08 11:52:26 -070097 mTimeBaseNs(timeBaseNs),
Yao Chen163d2602018-04-10 10:39:53 -070098 mLargestTimestampSeen(0),
99 mLastTimestampSeen(0) {
Chenjie Yue2219202018-06-08 10:07:51 -0700100 mPullerManager->ForceClearPullerCache();
Yao Chenab273e22017-09-06 12:53:50 -0700101}
102
Yao Chenef99c4f2017-09-22 16:26:54 -0700103StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -0700104}
105
Yangster-mace2cd6d52017-11-09 20:38:30 -0800106void StatsLogProcessor::onAnomalyAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700107 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800108 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
Yangster-macb0d06282018-01-05 15:44:07 -0800109 std::lock_guard<std::mutex> lock(mMetricsMutex);
Bookatzcc5adef22017-11-21 14:36:23 -0800110 for (const auto& itr : mMetricsManagers) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800111 itr.second->onAnomalyAlarmFired(timestampNs, alarmSet);
112 }
113}
114void StatsLogProcessor::onPeriodicAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700115 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800116 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
117
118 std::lock_guard<std::mutex> lock(mMetricsMutex);
119 for (const auto& itr : mMetricsManagers) {
120 itr.second->onPeriodicAlarmFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800121 }
122}
123
Yao Chen8a8d16c2018-02-08 14:50:40 -0800124void updateUid(Value* value, int hostUid) {
125 int uid = value->int_value;
126 if (uid != hostUid) {
127 value->setInt(hostUid);
128 }
129}
130
Yangster-macd40053e2018-01-09 16:29:22 -0800131void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
Yao Chenc40a19d2018-03-15 16:48:25 -0700132 if (android::util::AtomsInfo::kAtomsWithAttributionChain.find(event->GetTagId()) !=
133 android::util::AtomsInfo::kAtomsWithAttributionChain.end()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800134 for (auto& value : *(event->getMutableValues())) {
135 if (value.mField.getPosAtDepth(0) > kAttributionField) {
136 break;
137 }
138 if (isAttributionUidField(value)) {
139 const int hostUid = mUidMap->getHostUidOrSelf(value.mValue.int_value);
140 updateUid(&value.mValue, hostUid);
141 }
Yangster-macd40053e2018-01-09 16:29:22 -0800142 }
Yao Chenc40a19d2018-03-15 16:48:25 -0700143 } else {
144 auto it = android::util::AtomsInfo::kAtomsWithUidField.find(event->GetTagId());
145 if (it != android::util::AtomsInfo::kAtomsWithUidField.end()) {
146 int uidField = it->second; // uidField is the field number in proto,
147 // starting from 1
148 if (uidField > 0 && (int)event->getValues().size() >= uidField &&
149 (event->getValues())[uidField - 1].mValue.getType() == INT) {
150 Value& value = (*event->getMutableValues())[uidField - 1].mValue;
151 const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
152 updateUid(&value, hostUid);
153 } else {
154 ALOGE("Malformed log, uid not found. %s", event->ToString().c_str());
155 }
156 }
Yao Chen312e8982017-12-05 15:29:03 -0800157 }
Yangster-macd40053e2018-01-09 16:29:22 -0800158}
159
160void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
161 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
162 bool is_create = event.GetBool(3, &err);
163 auto parent_uid = int(event.GetLong(1, &err2));
164 auto isolated_uid = int(event.GetLong(2, &err3));
165 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
166 if (is_create) {
167 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
168 } else {
Bookatz3c648862018-05-25 13:32:43 -0700169 mUidMap->removeIsolatedUid(isolated_uid);
Yangster-macd40053e2018-01-09 16:29:22 -0800170 }
171 } else {
172 ALOGE("Failed to parse uid in the isolated uid change event.");
173 }
174}
175
Yangster-mac892f3d32018-05-02 14:16:48 -0700176void StatsLogProcessor::resetConfigs() {
177 std::lock_guard<std::mutex> lock(mMetricsMutex);
178 resetConfigsLocked(getElapsedRealtimeNs());
179}
180
181void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs) {
182 std::vector<ConfigKey> configKeys;
183 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
184 configKeys.push_back(it->first);
185 }
186 resetConfigsLocked(timestampNs, configKeys);
187}
188
Yao Chen3ff3a492018-08-06 16:17:37 -0700189void StatsLogProcessor::OnLogEvent(LogEvent* event) {
Yangster-macd40053e2018-01-09 16:29:22 -0800190 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen876889c2018-05-02 11:16:16 -0700191
192#ifdef VERY_VERBOSE_PRINTING
193 if (mPrintAllLogs) {
194 ALOGI("%s", event->ToString().c_str());
195 }
196#endif
Yangster-macb142cc82018-03-30 15:22:08 -0700197 const int64_t currentTimestampNs = event->GetElapsedTimestampNs();
Yangster-macb8382a12018-04-04 10:39:12 -0700198
Yangster-macb142cc82018-03-30 15:22:08 -0700199 resetIfConfigTtlExpiredLocked(currentTimestampNs);
200
Yangster-macd40053e2018-01-09 16:29:22 -0800201 StatsdStats::getInstance().noteAtomLogged(
Yangster-mac330af582018-02-08 15:24:38 -0800202 event->GetTagId(), event->GetElapsedTimestampNs() / NS_PER_SEC);
Yangster-macd40053e2018-01-09 16:29:22 -0800203
David Chen21582962017-11-01 17:32:46 -0700204 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800205 // The field numbers need to be currently updated by hand with atoms.proto
Yangster-macd40053e2018-01-09 16:29:22 -0800206 if (event->GetTagId() == android::util::ISOLATED_UID_CHANGED) {
207 onIsolatedUidChangedEventLocked(*event);
David Chencfc311d2018-01-23 17:55:54 -0800208 }
209
210 if (mMetricsManagers.empty()) {
211 return;
212 }
213
Yangster-macb142cc82018-03-30 15:22:08 -0700214 int64_t curTimeSec = getElapsedRealtimeSec();
Yangster-mac330af582018-02-08 15:24:38 -0800215 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
Chenjie Yue2219202018-06-08 10:07:51 -0700216 mPullerManager->ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
Yangster-mac330af582018-02-08 15:24:38 -0800217 mLastPullerCacheClearTimeSec = curTimeSec;
Chenjie Yufa22d652018-02-05 14:37:48 -0800218 }
219
Yangster-macb142cc82018-03-30 15:22:08 -0700220
David Chencfc311d2018-01-23 17:55:54 -0800221 if (event->GetTagId() != android::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800222 // Map the isolated uid to host uid if necessary.
223 mapIsolatedUidToHostUidIfNecessaryLocked(event);
224 }
225
226 // pass the event to metrics managers.
227 for (auto& pair : mMetricsManagers) {
228 pair.second->onLogEvent(*event);
Yangster-mac330af582018-02-08 15:24:38 -0800229 flushIfNecessaryLocked(event->GetElapsedTimestampNs(), pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700230 }
Yao Chenab273e22017-09-06 12:53:50 -0700231}
232
Yangster-macc04feba2018-04-02 14:37:33 -0700233void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
234 const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800235 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac892f3d32018-05-02 14:16:48 -0700236 WriteDataToDiskLocked(key, timestampNs, CONFIG_UPDATED);
Yangster-macb142cc82018-03-30 15:22:08 -0700237 OnConfigUpdatedLocked(timestampNs, key, config);
238}
239
240void StatsLogProcessor::OnConfigUpdatedLocked(
241 const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
Tej Singh484524a2018-02-01 15:10:05 -0800242 VLOG("Updated configuration for key %s", key.ToString().c_str());
Yangster-mac932ecec2018-02-01 10:23:52 -0800243 sp<MetricsManager> newMetricsManager =
Chenjie Yue2219202018-06-08 10:07:51 -0700244 new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap, mPullerManager,
245 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
Yao Chencaf339d2017-10-06 16:01:10 -0700246 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700247 mUidMap->OnConfigUpdated(key);
Yao Chen147ce602017-12-22 14:35:34 -0800248 if (newMetricsManager->shouldAddUidMapListener()) {
Yao Chend10f7b12017-12-18 12:53:50 -0800249 // We have to add listener after the MetricsManager is constructed because it's
250 // not safe to create wp or sp from this pointer inside its constructor.
251 mUidMap->addListener(newMetricsManager.get());
252 }
Yangster-macb142cc82018-03-30 15:22:08 -0700253 newMetricsManager->refreshTtl(timestampNs);
Yao Chend10f7b12017-12-18 12:53:50 -0800254 mMetricsManagers[key] = newMetricsManager;
Yao Chenb3561512017-11-21 18:07:17 -0800255 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700256 } else {
257 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800258 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700259 }
yro00698da2017-09-15 10:06:40 -0700260}
Bookatz906a35c2017-09-20 15:26:44 -0700261
Yangster7c334a12017-11-22 14:24:24 -0800262size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800263 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700264 auto it = mMetricsManagers.find(key);
265 if (it == mMetricsManagers.end()) {
266 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800267 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700268 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800269 return it->second->byteSize();
270}
271
Yao Chena80e5c02018-09-04 13:55:29 -0700272void StatsLogProcessor::dumpStates(int out, bool verbose) {
Yao Chen884c8c12018-01-26 10:36:25 -0800273 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chena80e5c02018-09-04 13:55:29 -0700274 FILE* fout = fdopen(out, "w");
275 if (fout == NULL) {
276 return;
Yao Chen884c8c12018-01-26 10:36:25 -0800277 }
Yao Chena80e5c02018-09-04 13:55:29 -0700278 fprintf(fout, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
279 for (auto metricsManager : mMetricsManagers) {
280 metricsManager.second->dumpStates(fout, verbose);
281 }
282
283 fclose(fout);
Yao Chen884c8c12018-01-26 10:36:25 -0800284}
285
yro4beccbe2018-03-15 19:42:05 -0700286/*
Bookatz9cc7b662018-11-06 10:39:21 -0800287 * onDumpReport dumps serialized ConfigMetricsReportList into proto.
yro4beccbe2018-03-15 19:42:05 -0700288 */
Yangster-macb142cc82018-03-30 15:22:08 -0700289void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700290 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700291 const bool erase_data,
Chenjie Yue36018b2018-04-16 15:18:30 -0700292 const DumpReportReason dumpReportReason,
Bookatzff71cad2018-09-20 17:17:49 -0700293 ProtoOutputStream* proto) {
Yangster-macb0d06282018-01-05 15:44:07 -0800294 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800295
yro947fbce2017-11-15 22:50:23 -0800296 // Start of ConfigKey.
Bookatzff71cad2018-09-20 17:17:49 -0700297 uint64_t configKeyToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
298 proto->write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
299 proto->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
300 proto->end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800301 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800302
yro947fbce2017-11-15 22:50:23 -0800303 // Then, check stats-data directory to see there's any file containing
304 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
Bookatzc71d9012018-12-19 12:28:38 -0800305 StorageManager::appendConfigMetricsReport(key, proto, erase_data);
yro947fbce2017-11-15 22:50:23 -0800306
Yangster-mace68f3a52018-04-04 00:01:43 -0700307 auto it = mMetricsManagers.find(key);
308 if (it != mMetricsManagers.end()) {
309 // This allows another broadcast to be sent within the rate-limit period if we get close to
310 // filling the buffer again soon.
311 mLastBroadcastTimes.erase(key);
312
313 // Start of ConfigMetricsReport (reports).
314 uint64_t reportsToken =
Bookatzff71cad2018-09-20 17:17:49 -0700315 proto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
Chenjie Yue36018b2018-04-16 15:18:30 -0700316 onConfigMetricsReportLocked(key, dumpTimeStampNs, include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700317 erase_data, dumpReportReason, proto);
318 proto->end(reportsToken);
Yangster-mace68f3a52018-04-04 00:01:43 -0700319 // End of ConfigMetricsReport (reports).
320 } else {
321 ALOGW("Config source %s does not exist", key.ToString().c_str());
322 }
Bookatzff71cad2018-09-20 17:17:49 -0700323}
324
325/*
326 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
327 */
328void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
329 const bool include_current_partial_bucket,
330 const bool erase_data,
331 const DumpReportReason dumpReportReason,
332 vector<uint8_t>* outData) {
333 ProtoOutputStream proto;
334 onDumpReport(key, dumpTimeStampNs, include_current_partial_bucket, erase_data,
335 dumpReportReason, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700336
David Chen1d7b0cd2017-11-15 14:20:04 -0800337 if (outData != nullptr) {
338 outData->clear();
339 outData->resize(proto.size());
340 size_t pos = 0;
341 auto iter = proto.data();
342 while (iter.readBuffer() != NULL) {
343 size_t toRead = iter.currentToRead();
344 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
345 pos += toRead;
346 iter.rp()->move(toRead);
347 }
yro17adac92017-11-08 23:16:29 -0800348 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800349
Yangster-mace68f3a52018-04-04 00:01:43 -0700350 StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
Yao Chen729093d2017-10-16 10:33:26 -0700351}
352
yro4beccbe2018-03-15 19:42:05 -0700353/*
354 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
355 */
356void StatsLogProcessor::onConfigMetricsReportLocked(const ConfigKey& key,
Yangster-macb142cc82018-03-30 15:22:08 -0700357 const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700358 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700359 const bool erase_data,
Chenjie Yue36018b2018-04-16 15:18:30 -0700360 const DumpReportReason dumpReportReason,
yro4beccbe2018-03-15 19:42:05 -0700361 ProtoOutputStream* proto) {
362 // We already checked whether key exists in mMetricsManagers in
363 // WriteDataToDisk.
364 auto it = mMetricsManagers.find(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700365 if (it == mMetricsManagers.end()) {
366 return;
367 }
yro4beccbe2018-03-15 19:42:05 -0700368 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
369 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
370
Yangster-mac9def8e32018-04-17 13:55:51 -0700371 std::set<string> str_set;
372
yro4beccbe2018-03-15 19:42:05 -0700373 // First, fill in ConfigMetricsReport using current data on memory, which
374 // starts from filling in StatsLogReport's.
Yangster-mac9def8e32018-04-17 13:55:51 -0700375 it->second->onDumpReport(dumpTimeStampNs, include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700376 erase_data, &str_set, proto);
yro4beccbe2018-03-15 19:42:05 -0700377
David Chen9e6dbbd2018-05-07 17:52:29 -0700378 // Fill in UidMap if there is at least one metric to report.
379 // This skips the uid map if it's an empty config.
380 if (it->second->getNumMetrics() > 0) {
381 uint64_t uidMapToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
dwchen730403e2018-10-29 11:41:56 -0700382 mUidMap->appendUidMap(
383 dumpTimeStampNs, key, it->second->hashStringInReport() ? &str_set : nullptr,
384 it->second->versionStringsInReport(), it->second->installerInReport(), proto);
David Chen9e6dbbd2018-05-07 17:52:29 -0700385 proto->end(uidMapToken);
386 }
yro4beccbe2018-03-15 19:42:05 -0700387
388 // Fill in the timestamps.
389 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
390 (long long)lastReportTimeNs);
391 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
392 (long long)dumpTimeStampNs);
393 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
394 (long long)lastReportWallClockNs);
395 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
396 (long long)getWallClockNs());
Chenjie Yue36018b2018-04-16 15:18:30 -0700397 // Dump report reason
398 proto->write(FIELD_TYPE_INT32 | FIELD_ID_DUMP_REPORT_REASON, dumpReportReason);
Yangster-mac9def8e32018-04-17 13:55:51 -0700399
David Chen56ae0d92018-05-11 16:00:22 -0700400 for (const auto& str : str_set) {
401 proto->write(FIELD_TYPE_STRING | FIELD_COUNT_REPEATED | FIELD_ID_STRINGS, str);
Yangster-mac9def8e32018-04-17 13:55:51 -0700402 }
Yangster-macb142cc82018-03-30 15:22:08 -0700403}
yro4beccbe2018-03-15 19:42:05 -0700404
Yao Chen163d2602018-04-10 10:39:53 -0700405void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
406 const std::vector<ConfigKey>& configs) {
407 for (const auto& key : configs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700408 StatsdConfig config;
409 if (StorageManager::readConfigFromDisk(key, &config)) {
410 OnConfigUpdatedLocked(timestampNs, key, config);
411 StatsdStats::getInstance().noteConfigReset(key);
412 } else {
413 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
414 auto it = mMetricsManagers.find(key);
415 if (it != mMetricsManagers.end()) {
416 it->second->refreshTtl(timestampNs);
417 }
418 }
419 }
yro4beccbe2018-03-15 19:42:05 -0700420}
421
Yao Chen163d2602018-04-10 10:39:53 -0700422void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
423 std::vector<ConfigKey> configKeysTtlExpired;
424 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
425 if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
426 configKeysTtlExpired.push_back(it->first);
427 }
428 }
429 if (configKeysTtlExpired.size() > 0) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700430 WriteDataToDiskLocked(CONFIG_RESET);
Yao Chen163d2602018-04-10 10:39:53 -0700431 resetConfigsLocked(timestampNs, configKeysTtlExpired);
432 }
433}
434
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700435void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800436 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700437 auto it = mMetricsManagers.find(key);
438 if (it != mMetricsManagers.end()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700439 WriteDataToDiskLocked(key, getElapsedRealtimeNs(), CONFIG_REMOVED);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700440 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700441 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700442 }
Yao Chenb3561512017-11-21 18:07:17 -0800443 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800444
David Chen1d7b0cd2017-11-15 14:20:04 -0800445 mLastBroadcastTimes.erase(key);
Chenjie Yufa22d652018-02-05 14:37:48 -0800446
447 if (mMetricsManagers.empty()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700448 mPullerManager->ForceClearPullerCache();
Chenjie Yufa22d652018-02-05 14:37:48 -0800449 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700450}
451
Yangster-macb0d06282018-01-05 15:44:07 -0800452void StatsLogProcessor::flushIfNecessaryLocked(
Yangster-macb142cc82018-03-30 15:22:08 -0700453 int64_t timestampNs, const ConfigKey& key, MetricsManager& metricsManager) {
David Chend9269e22017-12-05 13:43:51 -0800454 auto lastCheckTime = mLastByteSizeTimes.find(key);
455 if (lastCheckTime != mLastByteSizeTimes.end()) {
456 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
457 return;
458 }
459 }
460
461 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
462 size_t totalBytes = metricsManager.byteSize();
463 mLastByteSizeTimes[key] = timestampNs;
David Chen48944902018-05-03 10:29:11 -0700464 bool requestDump = false;
David Chend9269e22017-12-05 13:43:51 -0800465 if (totalBytes >
466 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen06dba5d2018-01-26 13:38:16 -0800467 metricsManager.dropData(timestampNs);
Chenjie Yuc3c30c02018-10-26 09:48:07 -0700468 StatsdStats::getInstance().noteDataDropped(key, totalBytes);
David Chen12942952017-12-04 14:28:43 -0800469 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chen48944902018-05-03 10:29:11 -0700470 } else if ((totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) ||
471 (mOnDiskDataConfigs.find(key) != mOnDiskDataConfigs.end())) {
472 // Request to send a broadcast if:
473 // 1. in memory data > threshold OR
474 // 2. config has old data report on disk.
475 requestDump = true;
476 }
477
478 if (requestDump) {
David Chend9269e22017-12-05 13:43:51 -0800479 // Send broadcast so that receivers can pull data.
480 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
481 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
482 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
483 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800484 return;
485 }
486 }
David Chen48944902018-05-03 10:29:11 -0700487 if (mSendBroadcast(key)) {
488 mOnDiskDataConfigs.erase(key);
489 VLOG("StatsD triggered data fetch for %s", key.ToString().c_str());
490 mLastBroadcastTimes[key] = timestampNs;
491 StatsdStats::getInstance().noteBroadcastSent(key);
492 }
yro31eb67b2017-10-24 13:33:21 -0700493 }
494}
495
Chenjie Yue36018b2018-04-16 15:18:30 -0700496void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key,
Yangster-mac892f3d32018-05-02 14:16:48 -0700497 const int64_t timestampNs,
Chenjie Yue36018b2018-04-16 15:18:30 -0700498 const DumpReportReason dumpReportReason) {
yro028091c2018-05-09 16:03:27 -0700499 if (mMetricsManagers.find(key) == mMetricsManagers.end() ||
500 !mMetricsManagers.find(key)->second->shouldWriteToDisk()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700501 return;
502 }
Yangster-mace68f3a52018-04-04 00:01:43 -0700503 ProtoOutputStream proto;
David Chen56ae0d92018-05-11 16:00:22 -0700504 onConfigMetricsReportLocked(key, timestampNs, true /* include_current_partial_bucket*/,
Bookatzff71cad2018-09-20 17:17:49 -0700505 true /* erase_data */, dumpReportReason, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700506 string file_name = StringPrintf("%s/%ld_%d_%lld", STATS_DATA_DIR,
507 (long)getWallClockSec(), key.GetUid(), (long long)key.GetId());
508 android::base::unique_fd fd(open(file_name.c_str(),
509 O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
510 if (fd == -1) {
511 ALOGE("Attempt to write %s but failed", file_name.c_str());
512 return;
513 }
514 proto.flush(fd.get());
David Chen48944902018-05-03 10:29:11 -0700515 // We were able to write the ConfigMetricsReport to disk, so we should trigger collection ASAP.
516 mOnDiskDataConfigs.insert(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700517}
518
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800519void StatsLogProcessor::WriteMetricsActivationToDisk(int64_t currentTimeNs) {
520 std::lock_guard<std::mutex> lock(mMetricsMutex);
521 ProtoOutputStream proto;
522
523 for (const auto& pair : mMetricsManagers) {
524 uint64_t activeConfigListToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
525 FIELD_ID_ACTIVE_CONFIG_LIST);
526 proto.write(FIELD_TYPE_INT64 | FIELD_ID_CONFIG_ID, (long long)pair.first.GetId());
527 proto.write(FIELD_TYPE_INT32 | FIELD_ID_CONFIG_UID, pair.first.GetUid());
528
Chenjie Yua9a310e2019-02-06 13:40:10 -0800529 vector<MetricProducer*> activeMetrics;
530 pair.second->prepForShutDown(currentTimeNs);
531 pair.second->getActiveMetrics(activeMetrics);
532 for (MetricProducer* metric : activeMetrics) {
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800533 if (metric->isActive()) {
534 uint64_t metricToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
535 FIELD_ID_ACTIVE_METRIC);
536 proto.write(FIELD_TYPE_INT64 | FIELD_ID_METRIC_ID,
537 (long long)metric->getMetricId());
538 proto.write(FIELD_TYPE_INT64 | FIELD_ID_TIME_TO_LIVE_NANOS,
539 (long long)metric->getRemainingTtlNs(currentTimeNs));
540 proto.end(metricToken);
541 }
542 }
543 proto.end(activeConfigListToken);
544 }
545
546 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
547 StorageManager::deleteFile(file_name.c_str());
548 android::base::unique_fd fd(
549 open(file_name.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
550 if (fd == -1) {
551 ALOGE("Attempt to write %s but failed", file_name.c_str());
552 return;
553 }
554 proto.flush(fd.get());
555}
556
557void StatsLogProcessor::LoadMetricsActivationFromDisk() {
558 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
559 int fd = open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
560 if (fd != -1) {
561 string content;
562 if (android::base::ReadFdToString(fd, &content)) {
563 ActiveConfigList activeConfigList;
564 if (activeConfigList.ParseFromString(content)) {
565 for (int i = 0; i < activeConfigList.active_config_size(); i++) {
566 const auto& config = activeConfigList.active_config(i);
567 ConfigKey key(config.uid(), config.config_id());
568 auto it = mMetricsManagers.find(key);
569 if (it == mMetricsManagers.end()) {
570 ALOGE("No config found for config %s", key.ToString().c_str());
571 continue;
572 }
573 VLOG("Setting active config %s", key.ToString().c_str());
574 it->second->setActiveMetrics(config, mTimeBaseNs);
575 }
576 }
577 VLOG("Successfully loaded %d active configs.", activeConfigList.active_config_size());
578 }
579 close(fd);
580 }
581 StorageManager::deleteFile(file_name.c_str());
582}
583
Chenjie Yue36018b2018-04-16 15:18:30 -0700584void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700585 const int64_t timeNs = getElapsedRealtimeNs();
Tej Singh42f9e062018-11-09 10:01:00 -0800586 // Do not write to disk if we already have in the last few seconds.
587 // This is to avoid overwriting files that would have the same name if we
588 // write twice in the same second.
589 if (static_cast<unsigned long long> (timeNs) <
590 mLastWriteTimeNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
591 ALOGI("Statsd skipping writing data to disk. Already wrote data in last %d seconds",
592 WRITE_DATA_COOL_DOWN_SEC);
593 return;
594 }
595 mLastWriteTimeNs = timeNs;
Yangster-mace68f3a52018-04-04 00:01:43 -0700596 for (auto& pair : mMetricsManagers) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700597 WriteDataToDiskLocked(pair.first, timeNs, dumpReportReason);
Yangster-mace68f3a52018-04-04 00:01:43 -0700598 }
599}
600
Yangster-mac892f3d32018-05-02 14:16:48 -0700601void StatsLogProcessor::WriteDataToDisk(const DumpReportReason dumpReportReason) {
Yangster-macb0d06282018-01-05 15:44:07 -0800602 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac892f3d32018-05-02 14:16:48 -0700603 WriteDataToDiskLocked(dumpReportReason);
yro947fbce2017-11-15 22:50:23 -0800604}
605
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700606void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
Yangster6df5fcc2018-04-12 11:04:29 -0700607 std::lock_guard<std::mutex> lock(mMetricsMutex);
Chenjie Yue2219202018-06-08 10:07:51 -0700608 mPullerManager->OnAlarmFired(timestampNs);
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700609}
610
David Chend37bc232018-04-12 18:05:11 -0700611int64_t StatsLogProcessor::getLastReportTimeNs(const ConfigKey& key) {
612 auto it = mMetricsManagers.find(key);
613 if (it == mMetricsManagers.end()) {
614 return 0;
615 } else {
616 return it->second->getLastReportTimeNs();
617 }
618}
619
David Chen48944902018-05-03 10:29:11 -0700620void StatsLogProcessor::noteOnDiskData(const ConfigKey& key) {
621 std::lock_guard<std::mutex> lock(mMetricsMutex);
622 mOnDiskDataConfigs.insert(key);
623}
624
Yao Chenef99c4f2017-09-22 16:26:54 -0700625} // namespace statsd
626} // namespace os
627} // namespace android