blob: 7a7a2f617e6a5346f36567089cd81d64d7ff494b [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
Yangster-mac8282d5b2018-01-19 09:47:39 -0800130 if (mMetricsManagers.empty()) {
131 return;
132 }
133
David Chen21582962017-11-01 17:32:46 -0700134 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800135 // The field numbers need to be currently updated by hand with atoms.proto
Yangster-macd40053e2018-01-09 16:29:22 -0800136 if (event->GetTagId() == android::util::ISOLATED_UID_CHANGED) {
137 onIsolatedUidChangedEventLocked(*event);
138 } else {
139 // Map the isolated uid to host uid if necessary.
140 mapIsolatedUidToHostUidIfNecessaryLocked(event);
141 }
142
143 // pass the event to metrics managers.
144 for (auto& pair : mMetricsManagers) {
145 pair.second->onLogEvent(*event);
146 flushIfNecessaryLocked(event->GetTimestampNs(), pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700147 }
Yao Chenab273e22017-09-06 12:53:50 -0700148}
149
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700150void StatsLogProcessor::OnConfigUpdated(const ConfigKey& key, const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800151 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chenb3561512017-11-21 18:07:17 -0800152 ALOGD("Updated configuration for key %s", key.ToString().c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800153 sp<MetricsManager> newMetricsManager = new MetricsManager(key, config, mTimeBaseSec, mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700154 auto it = mMetricsManagers.find(key);
Yao Chen288c6002017-12-12 13:43:18 -0800155 if (it == mMetricsManagers.end() && mMetricsManagers.size() > StatsdStats::kMaxConfigCount) {
Yao Chenb3561512017-11-21 18:07:17 -0800156 ALOGE("Can't accept more configs!");
157 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700158 }
159
Yao Chencaf339d2017-10-06 16:01:10 -0700160 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700161 mUidMap->OnConfigUpdated(key);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800162 newMetricsManager->setAnomalyMonitor(mAnomalyMonitor);
Yao Chen147ce602017-12-22 14:35:34 -0800163 if (newMetricsManager->shouldAddUidMapListener()) {
Yao Chend10f7b12017-12-18 12:53:50 -0800164 // We have to add listener after the MetricsManager is constructed because it's
165 // not safe to create wp or sp from this pointer inside its constructor.
166 mUidMap->addListener(newMetricsManager.get());
167 }
168 mMetricsManagers[key] = newMetricsManager;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700169 // Why doesn't this work? mMetricsManagers.insert({key, std::move(newMetricsManager)});
Yao Chenb3561512017-11-21 18:07:17 -0800170 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700171 } else {
172 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800173 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700174 }
yro00698da2017-09-15 10:06:40 -0700175}
Bookatz906a35c2017-09-20 15:26:44 -0700176
Yangster7c334a12017-11-22 14:24:24 -0800177size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800178 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700179 auto it = mMetricsManagers.find(key);
180 if (it == mMetricsManagers.end()) {
181 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800182 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700183 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800184 return it->second->byteSize();
185}
186
Yao Chen147ce602017-12-22 14:35:34 -0800187void StatsLogProcessor::onDumpReport(const ConfigKey& key, const uint64_t& dumpTimeStampNs,
188 ConfigMetricsReportList* report) {
Yangster-macb0d06282018-01-05 15:44:07 -0800189 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800190 auto it = mMetricsManagers.find(key);
191 if (it == mMetricsManagers.end()) {
192 ALOGW("Config source %s does not exist", key.ToString().c_str());
193 return;
194 }
195 report->mutable_config_key()->set_uid(key.GetUid());
Yangster-mac94e197c2018-01-02 16:03:03 -0800196 report->mutable_config_key()->set_id(key.GetId());
Yangster-mac20877162017-12-22 17:19:39 -0800197 ConfigMetricsReport* configMetricsReport = report->add_reports();
198 it->second->onDumpReport(dumpTimeStampNs, configMetricsReport);
199 // TODO: dump uid mapping.
200}
201
David Chen1d7b0cd2017-11-15 14:20:04 -0800202void StatsLogProcessor::onDumpReport(const ConfigKey& key, vector<uint8_t>* outData) {
Yangster-macb0d06282018-01-05 15:44:07 -0800203 std::lock_guard<std::mutex> lock(mMetricsMutex);
David Chen1d7b0cd2017-11-15 14:20:04 -0800204 auto it = mMetricsManagers.find(key);
205 if (it == mMetricsManagers.end()) {
206 ALOGW("Config source %s does not exist", key.ToString().c_str());
207 return;
208 }
209
210 // This allows another broadcast to be sent within the rate-limit period if we get close to
211 // filling the buffer again soon.
David Chen1d7b0cd2017-11-15 14:20:04 -0800212 mLastBroadcastTimes.erase(key);
Yao Chen729093d2017-10-16 10:33:26 -0700213
yro17adac92017-11-08 23:16:29 -0800214 ProtoOutputStream proto;
215
yro947fbce2017-11-15 22:50:23 -0800216 // Start of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800217 long long configKeyToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
218 proto.write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
Yangster-mac94e197c2018-01-02 16:03:03 -0800219 proto.write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
yro17adac92017-11-08 23:16:29 -0800220 proto.end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800221 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800222
yro947fbce2017-11-15 22:50:23 -0800223 // Start of ConfigMetricsReport (reports).
224 long long reportsToken =
225 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
226
227 // First, fill in ConfigMetricsReport using current data on memory, which
228 // starts from filling in StatsLogReport's.
Yao Chen288c6002017-12-12 13:43:18 -0800229 it->second->onDumpReport(&proto);
yro17adac92017-11-08 23:16:29 -0800230
231 // Fill in UidMap.
232 auto uidMap = mUidMap->getOutput(key);
233 const int uidMapSize = uidMap.ByteSize();
234 char uidMapBuffer[uidMapSize];
235 uidMap.SerializeToArray(&uidMapBuffer[0], uidMapSize);
236 proto.write(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP, uidMapBuffer, uidMapSize);
237
yro947fbce2017-11-15 22:50:23 -0800238 // End of ConfigMetricsReport (reports).
239 proto.end(reportsToken);
240
241 // Then, check stats-data directory to see there's any file containing
242 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
243 StorageManager::appendConfigMetricsReport(STATS_DATA_DIR, proto);
244
David Chen1d7b0cd2017-11-15 14:20:04 -0800245 if (outData != nullptr) {
246 outData->clear();
247 outData->resize(proto.size());
248 size_t pos = 0;
249 auto iter = proto.data();
250 while (iter.readBuffer() != NULL) {
251 size_t toRead = iter.currentToRead();
252 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
253 pos += toRead;
254 iter.rp()->move(toRead);
255 }
yro17adac92017-11-08 23:16:29 -0800256 }
Yao Chen69f1baf2017-11-27 17:25:36 -0800257 StatsdStats::getInstance().noteMetricsReportSent(key);
Yao Chen729093d2017-10-16 10:33:26 -0700258}
259
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700260void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800261 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700262 auto it = mMetricsManagers.find(key);
263 if (it != mMetricsManagers.end()) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700264 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700265 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700266 }
Yao Chenb3561512017-11-21 18:07:17 -0800267 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800268
David Chen1d7b0cd2017-11-15 14:20:04 -0800269 mLastBroadcastTimes.erase(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700270}
271
Yangster-macb0d06282018-01-05 15:44:07 -0800272void StatsLogProcessor::flushIfNecessaryLocked(
273 uint64_t timestampNs, const ConfigKey& key, MetricsManager& metricsManager) {
David Chend9269e22017-12-05 13:43:51 -0800274 auto lastCheckTime = mLastByteSizeTimes.find(key);
275 if (lastCheckTime != mLastByteSizeTimes.end()) {
276 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
277 return;
278 }
279 }
280
281 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
282 size_t totalBytes = metricsManager.byteSize();
283 mLastByteSizeTimes[key] = timestampNs;
284 if (totalBytes >
285 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen288c6002017-12-12 13:43:18 -0800286 // TODO(b/70571383): By 12/15/2017 add API to drop data directly
287 ProtoOutputStream proto;
288 metricsManager.onDumpReport(&proto);
David Chen12942952017-12-04 14:28:43 -0800289 StatsdStats::getInstance().noteDataDropped(key);
290 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chend9269e22017-12-05 13:43:51 -0800291 } else if (totalBytes > .9 * StatsdStats::kMaxMetricsBytesPerConfig) {
292 // Send broadcast so that receivers can pull data.
293 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
294 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
295 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
296 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800297 return;
298 }
299 }
300 mLastBroadcastTimes[key] = timestampNs;
Yao Chenb3561512017-11-21 18:07:17 -0800301 VLOG("StatsD requesting broadcast for %s", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800302 mSendBroadcast(key);
Yao Chenb3561512017-11-21 18:07:17 -0800303 StatsdStats::getInstance().noteBroadcastSent(key);
yro31eb67b2017-10-24 13:33:21 -0700304 }
305}
306
yro947fbce2017-11-15 22:50:23 -0800307void StatsLogProcessor::WriteDataToDisk() {
Yangster-macb0d06282018-01-05 15:44:07 -0800308 std::lock_guard<std::mutex> lock(mMetricsMutex);
yro947fbce2017-11-15 22:50:23 -0800309 for (auto& pair : mMetricsManagers) {
310 const ConfigKey& key = pair.first;
311 vector<uint8_t> data;
312 onDumpReport(key, &data);
313 // TODO: Add a guardrail to prevent accumulation of file on disk.
Yangster-mac94e197c2018-01-02 16:03:03 -0800314 string file_name = StringPrintf("%s/%d-%lld-%ld", STATS_DATA_DIR, key.GetUid(),
315 (long long)key.GetId(), time(nullptr));
yro947fbce2017-11-15 22:50:23 -0800316 StorageManager::writeFile(file_name.c_str(), &data[0], data.size());
317 }
318}
319
Yao Chenef99c4f2017-09-22 16:26:54 -0700320} // namespace statsd
321} // namespace os
322} // namespace android