blob: e0187b72456d86dec7ce76532a35f75394d47f4a [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
Yao Chenb3561512017-11-21 18:07:17 -080017#define DEBUG true // 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"
yro947fbce2017-11-15 22:50:23 -080024#include "android-base/stringprintf.h"
Yao Chenb3561512017-11-21 18:07:17 -080025#include "guardrail/StatsdStats.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070026#include "metrics/CountMetricProducer.h"
Chenjie Yu85ed8382017-12-14 16:48:54 -080027#include "external/StatsPullerManager.h"
Yangster-macd40053e2018-01-09 16:29:22 -080028#include "dimension.h"
29#include "field_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>
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
61const int FIELD_ID_METRICS = 1;
62const int FIELD_ID_UID_MAP = 2;
63
yro03faf092017-12-12 00:17:50 -080064#define STATS_DATA_DIR "/data/misc/stats-data"
yro17adac92017-11-08 23:16:29 -080065
yro31eb67b2017-10-24 13:33:21 -070066StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
Yangster-mace2cd6d52017-11-09 20:38:30 -080067 const sp<AnomalyMonitor>& anomalyMonitor,
Yangster-mac20877162017-12-22 17:19:39 -080068 const long timeBaseSec,
David Chen1d7b0cd2017-11-15 14:20:04 -080069 const std::function<void(const ConfigKey&)>& sendBroadcast)
Chenjie Yu85ed8382017-12-14 16:48:54 -080070 : mUidMap(uidMap),
71 mAnomalyMonitor(anomalyMonitor),
72 mSendBroadcast(sendBroadcast),
Yangster-mac20877162017-12-22 17:19:39 -080073 mTimeBaseSec(timeBaseSec) {
yro947fbce2017-11-15 22:50:23 -080074 // On each initialization of StatsLogProcessor, check stats-data directory to see if there is
75 // any left over data to be read.
76 StorageManager::sendBroadcast(STATS_DATA_DIR, mSendBroadcast);
Chenjie Yu85ed8382017-12-14 16:48:54 -080077 StatsPullerManager statsPullerManager;
78 statsPullerManager.SetTimeBaseSec(mTimeBaseSec);
Yao Chenab273e22017-09-06 12:53:50 -070079}
80
Yao Chenef99c4f2017-09-22 16:26:54 -070081StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -070082}
83
Yangster-mace2cd6d52017-11-09 20:38:30 -080084void StatsLogProcessor::onAnomalyAlarmFired(
85 const uint64_t timestampNs,
86 unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet) {
Yangster-macb0d06282018-01-05 15:44:07 -080087 std::lock_guard<std::mutex> lock(mMetricsMutex);
Bookatzcc5adef22017-11-21 14:36:23 -080088 for (const auto& itr : mMetricsManagers) {
89 itr.second->onAnomalyAlarmFired(timestampNs, anomalySet);
Yangster-mace2cd6d52017-11-09 20:38:30 -080090 }
91}
92
Yangster-macd40053e2018-01-09 16:29:22 -080093void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
94 std::vector<Field> uidFields;
95 findFields(
96 event->getFieldValueMap(),
97 buildAttributionUidFieldMatcher(event->GetTagId(), Position::ANY),
98 &uidFields);
99 for (size_t i = 0; i < uidFields.size(); ++i) {
100 DimensionsValue* value = event->findFieldValueOrNull(uidFields[i]);
101 if (value != nullptr && value->value_case() == DimensionsValue::ValueCase::kValueInt) {
102 const int uid = mUidMap->getHostUidOrSelf(value->value_int());
103 value->set_value_int(uid);
104 }
Yao Chen312e8982017-12-05 15:29:03 -0800105 }
Yangster-macd40053e2018-01-09 16:29:22 -0800106}
107
108void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
109 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
110 bool is_create = event.GetBool(3, &err);
111 auto parent_uid = int(event.GetLong(1, &err2));
112 auto isolated_uid = int(event.GetLong(2, &err3));
113 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
114 if (is_create) {
115 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
116 } else {
117 mUidMap->removeIsolatedUid(isolated_uid, parent_uid);
118 }
119 } else {
120 ALOGE("Failed to parse uid in the isolated uid change event.");
121 }
122}
123
124// TODO: what if statsd service restarts? How do we know what logs are already processed before?
125void StatsLogProcessor::OnLogEvent(LogEvent* event) {
126 std::lock_guard<std::mutex> lock(mMetricsMutex);
127 StatsdStats::getInstance().noteAtomLogged(
128 event->GetTagId(), event->GetTimestampNs() / NS_PER_SEC);
129
David Chen21582962017-11-01 17:32:46 -0700130 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800131 // The field numbers need to be currently updated by hand with atoms.proto
Yangster-macd40053e2018-01-09 16:29:22 -0800132 if (event->GetTagId() == android::util::ISOLATED_UID_CHANGED) {
133 onIsolatedUidChangedEventLocked(*event);
134 } else {
135 // Map the isolated uid to host uid if necessary.
136 mapIsolatedUidToHostUidIfNecessaryLocked(event);
137 }
138
139 // pass the event to metrics managers.
140 for (auto& pair : mMetricsManagers) {
141 pair.second->onLogEvent(*event);
142 flushIfNecessaryLocked(event->GetTimestampNs(), pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700143 }
Yao Chenab273e22017-09-06 12:53:50 -0700144}
145
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700146void StatsLogProcessor::OnConfigUpdated(const ConfigKey& key, const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800147 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chenb3561512017-11-21 18:07:17 -0800148 ALOGD("Updated configuration for key %s", key.ToString().c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800149 sp<MetricsManager> newMetricsManager = new MetricsManager(key, config, mTimeBaseSec, mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700150 auto it = mMetricsManagers.find(key);
Yao Chen288c6002017-12-12 13:43:18 -0800151 if (it == mMetricsManagers.end() && mMetricsManagers.size() > StatsdStats::kMaxConfigCount) {
Yao Chenb3561512017-11-21 18:07:17 -0800152 ALOGE("Can't accept more configs!");
153 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700154 }
155
Yao Chencaf339d2017-10-06 16:01:10 -0700156 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700157 mUidMap->OnConfigUpdated(key);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800158 newMetricsManager->setAnomalyMonitor(mAnomalyMonitor);
Yao Chen147ce602017-12-22 14:35:34 -0800159 if (newMetricsManager->shouldAddUidMapListener()) {
Yao Chend10f7b12017-12-18 12:53:50 -0800160 // We have to add listener after the MetricsManager is constructed because it's
161 // not safe to create wp or sp from this pointer inside its constructor.
162 mUidMap->addListener(newMetricsManager.get());
163 }
164 mMetricsManagers[key] = newMetricsManager;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700165 // Why doesn't this work? mMetricsManagers.insert({key, std::move(newMetricsManager)});
Yao Chenb3561512017-11-21 18:07:17 -0800166 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700167 } else {
168 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800169 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700170 }
yro00698da2017-09-15 10:06:40 -0700171}
Bookatz906a35c2017-09-20 15:26:44 -0700172
Yangster7c334a12017-11-22 14:24:24 -0800173size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800174 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700175 auto it = mMetricsManagers.find(key);
176 if (it == mMetricsManagers.end()) {
177 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800178 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700179 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800180 return it->second->byteSize();
181}
182
Yao Chen147ce602017-12-22 14:35:34 -0800183void StatsLogProcessor::onDumpReport(const ConfigKey& key, const uint64_t& dumpTimeStampNs,
184 ConfigMetricsReportList* report) {
Yangster-macb0d06282018-01-05 15:44:07 -0800185 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800186 auto it = mMetricsManagers.find(key);
187 if (it == mMetricsManagers.end()) {
188 ALOGW("Config source %s does not exist", key.ToString().c_str());
189 return;
190 }
191 report->mutable_config_key()->set_uid(key.GetUid());
Yangster-mac94e197c2018-01-02 16:03:03 -0800192 report->mutable_config_key()->set_id(key.GetId());
Yangster-mac20877162017-12-22 17:19:39 -0800193 ConfigMetricsReport* configMetricsReport = report->add_reports();
194 it->second->onDumpReport(dumpTimeStampNs, configMetricsReport);
195 // TODO: dump uid mapping.
196}
197
David Chen1d7b0cd2017-11-15 14:20:04 -0800198void StatsLogProcessor::onDumpReport(const ConfigKey& key, vector<uint8_t>* outData) {
Yangster-macb0d06282018-01-05 15:44:07 -0800199 std::lock_guard<std::mutex> lock(mMetricsMutex);
David Chen1d7b0cd2017-11-15 14:20:04 -0800200 auto it = mMetricsManagers.find(key);
201 if (it == mMetricsManagers.end()) {
202 ALOGW("Config source %s does not exist", key.ToString().c_str());
203 return;
204 }
205
206 // This allows another broadcast to be sent within the rate-limit period if we get close to
207 // filling the buffer again soon.
David Chen1d7b0cd2017-11-15 14:20:04 -0800208 mLastBroadcastTimes.erase(key);
Yao Chen729093d2017-10-16 10:33:26 -0700209
yro17adac92017-11-08 23:16:29 -0800210 ProtoOutputStream proto;
211
yro947fbce2017-11-15 22:50:23 -0800212 // Start of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800213 long long configKeyToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
214 proto.write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
Yangster-mac94e197c2018-01-02 16:03:03 -0800215 proto.write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
yro17adac92017-11-08 23:16:29 -0800216 proto.end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800217 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800218
yro947fbce2017-11-15 22:50:23 -0800219 // Start of ConfigMetricsReport (reports).
220 long long reportsToken =
221 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
222
223 // First, fill in ConfigMetricsReport using current data on memory, which
224 // starts from filling in StatsLogReport's.
Yao Chen288c6002017-12-12 13:43:18 -0800225 it->second->onDumpReport(&proto);
yro17adac92017-11-08 23:16:29 -0800226
227 // Fill in UidMap.
228 auto uidMap = mUidMap->getOutput(key);
229 const int uidMapSize = uidMap.ByteSize();
230 char uidMapBuffer[uidMapSize];
231 uidMap.SerializeToArray(&uidMapBuffer[0], uidMapSize);
232 proto.write(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP, uidMapBuffer, uidMapSize);
233
yro947fbce2017-11-15 22:50:23 -0800234 // End of ConfigMetricsReport (reports).
235 proto.end(reportsToken);
236
237 // Then, check stats-data directory to see there's any file containing
238 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
yro98a28502018-01-18 17:00:14 -0800239 StorageManager::appendConfigMetricsReport(proto);
yro947fbce2017-11-15 22:50:23 -0800240
David Chen1d7b0cd2017-11-15 14:20:04 -0800241 if (outData != nullptr) {
242 outData->clear();
243 outData->resize(proto.size());
244 size_t pos = 0;
245 auto iter = proto.data();
246 while (iter.readBuffer() != NULL) {
247 size_t toRead = iter.currentToRead();
248 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
249 pos += toRead;
250 iter.rp()->move(toRead);
251 }
yro17adac92017-11-08 23:16:29 -0800252 }
Yao Chen69f1baf2017-11-27 17:25:36 -0800253 StatsdStats::getInstance().noteMetricsReportSent(key);
Yao Chen729093d2017-10-16 10:33:26 -0700254}
255
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700256void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800257 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700258 auto it = mMetricsManagers.find(key);
259 if (it != mMetricsManagers.end()) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700260 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700261 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700262 }
Yao Chenb3561512017-11-21 18:07:17 -0800263 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800264
David Chen1d7b0cd2017-11-15 14:20:04 -0800265 mLastBroadcastTimes.erase(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700266}
267
Yangster-macb0d06282018-01-05 15:44:07 -0800268void StatsLogProcessor::flushIfNecessaryLocked(
269 uint64_t timestampNs, const ConfigKey& key, MetricsManager& metricsManager) {
David Chend9269e22017-12-05 13:43:51 -0800270 auto lastCheckTime = mLastByteSizeTimes.find(key);
271 if (lastCheckTime != mLastByteSizeTimes.end()) {
272 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
273 return;
274 }
275 }
276
277 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
278 size_t totalBytes = metricsManager.byteSize();
279 mLastByteSizeTimes[key] = timestampNs;
280 if (totalBytes >
281 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen288c6002017-12-12 13:43:18 -0800282 // TODO(b/70571383): By 12/15/2017 add API to drop data directly
283 ProtoOutputStream proto;
284 metricsManager.onDumpReport(&proto);
David Chen12942952017-12-04 14:28:43 -0800285 StatsdStats::getInstance().noteDataDropped(key);
286 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chend9269e22017-12-05 13:43:51 -0800287 } else if (totalBytes > .9 * StatsdStats::kMaxMetricsBytesPerConfig) {
288 // Send broadcast so that receivers can pull data.
289 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
290 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
291 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
292 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800293 return;
294 }
295 }
296 mLastBroadcastTimes[key] = timestampNs;
Yao Chenb3561512017-11-21 18:07:17 -0800297 VLOG("StatsD requesting broadcast for %s", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800298 mSendBroadcast(key);
Yao Chenb3561512017-11-21 18:07:17 -0800299 StatsdStats::getInstance().noteBroadcastSent(key);
yro31eb67b2017-10-24 13:33:21 -0700300 }
301}
302
yro947fbce2017-11-15 22:50:23 -0800303void StatsLogProcessor::WriteDataToDisk() {
Yangster-macb0d06282018-01-05 15:44:07 -0800304 std::lock_guard<std::mutex> lock(mMetricsMutex);
yro947fbce2017-11-15 22:50:23 -0800305 for (auto& pair : mMetricsManagers) {
306 const ConfigKey& key = pair.first;
307 vector<uint8_t> data;
308 onDumpReport(key, &data);
309 // TODO: Add a guardrail to prevent accumulation of file on disk.
yro98a28502018-01-18 17:00:14 -0800310 string file_name = StringPrintf("%s/%ld_%d_%lld", STATS_DATA_DIR, time(nullptr),
311 key.GetUid(), (long long)key.GetId());
yro947fbce2017-11-15 22:50:23 -0800312 StorageManager::writeFile(file_name.c_str(), &data[0], data.size());
313 }
314}
315
Yao Chenef99c4f2017-09-22 16:26:54 -0700316} // namespace statsd
317} // namespace os
318} // namespace android