blob: a9e0f233d0dd5ca6f61cc554973d43d5e1366f5a [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"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070028#include "stats_util.h"
yro947fbce2017-11-15 22:50:23 -080029#include "storage/StorageManager.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070030
yro00698da2017-09-15 10:06:40 -070031#include <log/log_event_list.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070032#include <utils/Errors.h>
Yao Chenab273e22017-09-06 12:53:50 -070033
34using namespace android;
yro947fbce2017-11-15 22:50:23 -080035using android::base::StringPrintf;
yrob0378b02017-11-09 20:36:25 -080036using android::util::FIELD_COUNT_REPEATED;
yro17adac92017-11-08 23:16:29 -080037using android::util::FIELD_TYPE_BOOL;
38using android::util::FIELD_TYPE_FLOAT;
39using android::util::FIELD_TYPE_INT32;
40using android::util::FIELD_TYPE_INT64;
41using android::util::FIELD_TYPE_MESSAGE;
42using android::util::FIELD_TYPE_STRING;
43using android::util::ProtoOutputStream;
Yao Chen44cf27c2017-09-14 22:32:50 -070044using std::make_unique;
45using std::unique_ptr;
46using std::vector;
Bookatz906a35c2017-09-20 15:26:44 -070047
48namespace android {
49namespace os {
50namespace statsd {
Yao Chenab273e22017-09-06 12:53:50 -070051
yro947fbce2017-11-15 22:50:23 -080052// for ConfigMetricsReportList
yro17adac92017-11-08 23:16:29 -080053const int FIELD_ID_CONFIG_KEY = 1;
yro947fbce2017-11-15 22:50:23 -080054const int FIELD_ID_REPORTS = 2;
yro17adac92017-11-08 23:16:29 -080055// for ConfigKey
56const int FIELD_ID_UID = 1;
Yangster-mac94e197c2018-01-02 16:03:03 -080057const int FIELD_ID_ID = 2;
yro947fbce2017-11-15 22:50:23 -080058// for ConfigMetricsReport
59const int FIELD_ID_METRICS = 1;
60const int FIELD_ID_UID_MAP = 2;
61
yro03faf092017-12-12 00:17:50 -080062#define STATS_DATA_DIR "/data/misc/stats-data"
yro17adac92017-11-08 23:16:29 -080063
yro31eb67b2017-10-24 13:33:21 -070064StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
Yangster-mace2cd6d52017-11-09 20:38:30 -080065 const sp<AnomalyMonitor>& anomalyMonitor,
Yangster-mac20877162017-12-22 17:19:39 -080066 const long timeBaseSec,
David Chen1d7b0cd2017-11-15 14:20:04 -080067 const std::function<void(const ConfigKey&)>& sendBroadcast)
Chenjie Yu85ed8382017-12-14 16:48:54 -080068 : mUidMap(uidMap),
69 mAnomalyMonitor(anomalyMonitor),
70 mSendBroadcast(sendBroadcast),
Yangster-mac20877162017-12-22 17:19:39 -080071 mTimeBaseSec(timeBaseSec) {
yro947fbce2017-11-15 22:50:23 -080072 // On each initialization of StatsLogProcessor, check stats-data directory to see if there is
73 // any left over data to be read.
74 StorageManager::sendBroadcast(STATS_DATA_DIR, mSendBroadcast);
Chenjie Yu85ed8382017-12-14 16:48:54 -080075 StatsPullerManager statsPullerManager;
76 statsPullerManager.SetTimeBaseSec(mTimeBaseSec);
Yao Chenab273e22017-09-06 12:53:50 -070077}
78
Yao Chenef99c4f2017-09-22 16:26:54 -070079StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -070080}
81
Yangster-mace2cd6d52017-11-09 20:38:30 -080082void StatsLogProcessor::onAnomalyAlarmFired(
83 const uint64_t timestampNs,
84 unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet) {
Yangster-macb0d06282018-01-05 15:44:07 -080085 std::lock_guard<std::mutex> lock(mMetricsMutex);
Bookatzcc5adef2017-11-21 14:36:23 -080086 for (const auto& itr : mMetricsManagers) {
87 itr.second->onAnomalyAlarmFired(timestampNs, anomalySet);
Yangster-mace2cd6d52017-11-09 20:38:30 -080088 }
89}
90
Yao Chen44cf27c2017-09-14 22:32:50 -070091// TODO: what if statsd service restarts? How do we know what logs are already processed before?
Joe Onoratoc4dfae52017-10-17 23:38:21 -070092void StatsLogProcessor::OnLogEvent(const LogEvent& msg) {
Yangster-macb0d06282018-01-05 15:44:07 -080093 std::lock_guard<std::mutex> lock(mMetricsMutex);
94
Yao Chenb3561512017-11-21 18:07:17 -080095 StatsdStats::getInstance().noteAtomLogged(msg.GetTagId(), msg.GetTimestampNs() / NS_PER_SEC);
Yao Chen44cf27c2017-09-14 22:32:50 -070096 // pass the event to metrics managers.
Yao Chen312e8982017-12-05 15:29:03 -080097 for (auto& pair : mMetricsManagers) {
98 pair.second->onLogEvent(msg);
Yangster-macb0d06282018-01-05 15:44:07 -080099 flushIfNecessaryLocked(msg.GetTimestampNs(), pair.first, *(pair.second));
Yao Chen312e8982017-12-05 15:29:03 -0800100 }
David Chen21582962017-11-01 17:32:46 -0700101 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800102 // The field numbers need to be currently updated by hand with atoms.proto
David Chen21582962017-11-01 17:32:46 -0700103 if (msg.GetTagId() == android::util::ISOLATED_UID_CHANGED) {
104 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
105 bool is_create = msg.GetBool(3, &err);
106 auto parent_uid = int(msg.GetLong(1, &err2));
107 auto isolated_uid = int(msg.GetLong(2, &err3));
108 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
109 if (is_create) {
110 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
111 } else {
112 mUidMap->removeIsolatedUid(isolated_uid, parent_uid);
113 }
114 }
115 }
Yao Chenab273e22017-09-06 12:53:50 -0700116}
117
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700118void StatsLogProcessor::OnConfigUpdated(const ConfigKey& key, const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800119 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chenb3561512017-11-21 18:07:17 -0800120 ALOGD("Updated configuration for key %s", key.ToString().c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800121 sp<MetricsManager> newMetricsManager = new MetricsManager(key, config, mTimeBaseSec, mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700122 auto it = mMetricsManagers.find(key);
Yao Chen288c6002017-12-12 13:43:18 -0800123 if (it == mMetricsManagers.end() && mMetricsManagers.size() > StatsdStats::kMaxConfigCount) {
Yao Chenb3561512017-11-21 18:07:17 -0800124 ALOGE("Can't accept more configs!");
125 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700126 }
127
Yao Chencaf339d2017-10-06 16:01:10 -0700128 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700129 mUidMap->OnConfigUpdated(key);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800130 newMetricsManager->setAnomalyMonitor(mAnomalyMonitor);
Yao Chen147ce602017-12-22 14:35:34 -0800131 if (newMetricsManager->shouldAddUidMapListener()) {
Yao Chend10f7b12017-12-18 12:53:50 -0800132 // We have to add listener after the MetricsManager is constructed because it's
133 // not safe to create wp or sp from this pointer inside its constructor.
134 mUidMap->addListener(newMetricsManager.get());
135 }
136 mMetricsManagers[key] = newMetricsManager;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700137 // Why doesn't this work? mMetricsManagers.insert({key, std::move(newMetricsManager)});
Yao Chenb3561512017-11-21 18:07:17 -0800138 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700139 } else {
140 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800141 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700142 }
yro00698da2017-09-15 10:06:40 -0700143}
Bookatz906a35c2017-09-20 15:26:44 -0700144
Yangster7c334a12017-11-22 14:24:24 -0800145size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800146 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700147 auto it = mMetricsManagers.find(key);
148 if (it == mMetricsManagers.end()) {
149 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800150 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700151 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800152 return it->second->byteSize();
153}
154
Yao Chen147ce602017-12-22 14:35:34 -0800155void StatsLogProcessor::onDumpReport(const ConfigKey& key, const uint64_t& dumpTimeStampNs,
156 ConfigMetricsReportList* report) {
Yangster-macb0d06282018-01-05 15:44:07 -0800157 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800158 auto it = mMetricsManagers.find(key);
159 if (it == mMetricsManagers.end()) {
160 ALOGW("Config source %s does not exist", key.ToString().c_str());
161 return;
162 }
163 report->mutable_config_key()->set_uid(key.GetUid());
Yangster-mac94e197c2018-01-02 16:03:03 -0800164 report->mutable_config_key()->set_id(key.GetId());
Yangster-mac20877162017-12-22 17:19:39 -0800165 ConfigMetricsReport* configMetricsReport = report->add_reports();
166 it->second->onDumpReport(dumpTimeStampNs, configMetricsReport);
167 // TODO: dump uid mapping.
168}
169
David Chen1d7b0cd2017-11-15 14:20:04 -0800170void StatsLogProcessor::onDumpReport(const ConfigKey& key, vector<uint8_t>* outData) {
Yangster-macb0d06282018-01-05 15:44:07 -0800171 std::lock_guard<std::mutex> lock(mMetricsMutex);
David Chen1d7b0cd2017-11-15 14:20:04 -0800172 auto it = mMetricsManagers.find(key);
173 if (it == mMetricsManagers.end()) {
174 ALOGW("Config source %s does not exist", key.ToString().c_str());
175 return;
176 }
177
178 // This allows another broadcast to be sent within the rate-limit period if we get close to
179 // filling the buffer again soon.
David Chen1d7b0cd2017-11-15 14:20:04 -0800180 mLastBroadcastTimes.erase(key);
Yao Chen729093d2017-10-16 10:33:26 -0700181
yro17adac92017-11-08 23:16:29 -0800182 ProtoOutputStream proto;
183
yro947fbce2017-11-15 22:50:23 -0800184 // Start of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800185 long long configKeyToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
186 proto.write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
Yangster-mac94e197c2018-01-02 16:03:03 -0800187 proto.write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
yro17adac92017-11-08 23:16:29 -0800188 proto.end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800189 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800190
yro947fbce2017-11-15 22:50:23 -0800191 // Start of ConfigMetricsReport (reports).
192 long long reportsToken =
193 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
194
195 // First, fill in ConfigMetricsReport using current data on memory, which
196 // starts from filling in StatsLogReport's.
Yao Chen288c6002017-12-12 13:43:18 -0800197 it->second->onDumpReport(&proto);
yro17adac92017-11-08 23:16:29 -0800198
199 // Fill in UidMap.
200 auto uidMap = mUidMap->getOutput(key);
201 const int uidMapSize = uidMap.ByteSize();
202 char uidMapBuffer[uidMapSize];
203 uidMap.SerializeToArray(&uidMapBuffer[0], uidMapSize);
204 proto.write(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP, uidMapBuffer, uidMapSize);
205
yro947fbce2017-11-15 22:50:23 -0800206 // End of ConfigMetricsReport (reports).
207 proto.end(reportsToken);
208
209 // Then, check stats-data directory to see there's any file containing
210 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
211 StorageManager::appendConfigMetricsReport(STATS_DATA_DIR, proto);
212
David Chen1d7b0cd2017-11-15 14:20:04 -0800213 if (outData != nullptr) {
214 outData->clear();
215 outData->resize(proto.size());
216 size_t pos = 0;
217 auto iter = proto.data();
218 while (iter.readBuffer() != NULL) {
219 size_t toRead = iter.currentToRead();
220 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
221 pos += toRead;
222 iter.rp()->move(toRead);
223 }
yro17adac92017-11-08 23:16:29 -0800224 }
Yao Chen69f1baf2017-11-27 17:25:36 -0800225 StatsdStats::getInstance().noteMetricsReportSent(key);
Yao Chen729093d2017-10-16 10:33:26 -0700226}
227
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700228void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800229 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700230 auto it = mMetricsManagers.find(key);
231 if (it != mMetricsManagers.end()) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700232 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700233 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700234 }
Yao Chenb3561512017-11-21 18:07:17 -0800235 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800236
David Chen1d7b0cd2017-11-15 14:20:04 -0800237 mLastBroadcastTimes.erase(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700238}
239
Yangster-macb0d06282018-01-05 15:44:07 -0800240void StatsLogProcessor::flushIfNecessaryLocked(
241 uint64_t timestampNs, const ConfigKey& key, MetricsManager& metricsManager) {
David Chend9269e22017-12-05 13:43:51 -0800242 auto lastCheckTime = mLastByteSizeTimes.find(key);
243 if (lastCheckTime != mLastByteSizeTimes.end()) {
244 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
245 return;
246 }
247 }
248
249 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
250 size_t totalBytes = metricsManager.byteSize();
251 mLastByteSizeTimes[key] = timestampNs;
252 if (totalBytes >
253 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen288c6002017-12-12 13:43:18 -0800254 // TODO(b/70571383): By 12/15/2017 add API to drop data directly
255 ProtoOutputStream proto;
256 metricsManager.onDumpReport(&proto);
David Chen12942952017-12-04 14:28:43 -0800257 StatsdStats::getInstance().noteDataDropped(key);
258 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chend9269e22017-12-05 13:43:51 -0800259 } else if (totalBytes > .9 * StatsdStats::kMaxMetricsBytesPerConfig) {
260 // Send broadcast so that receivers can pull data.
261 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
262 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
263 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
264 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800265 return;
266 }
267 }
268 mLastBroadcastTimes[key] = timestampNs;
Yao Chenb3561512017-11-21 18:07:17 -0800269 VLOG("StatsD requesting broadcast for %s", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800270 mSendBroadcast(key);
Yao Chenb3561512017-11-21 18:07:17 -0800271 StatsdStats::getInstance().noteBroadcastSent(key);
yro31eb67b2017-10-24 13:33:21 -0700272 }
273}
274
yro947fbce2017-11-15 22:50:23 -0800275void StatsLogProcessor::WriteDataToDisk() {
276 mkdir(STATS_DATA_DIR, S_IRWXU);
Yangster-macb0d06282018-01-05 15:44:07 -0800277 std::lock_guard<std::mutex> lock(mMetricsMutex);
yro947fbce2017-11-15 22:50:23 -0800278 for (auto& pair : mMetricsManagers) {
279 const ConfigKey& key = pair.first;
280 vector<uint8_t> data;
281 onDumpReport(key, &data);
282 // TODO: Add a guardrail to prevent accumulation of file on disk.
Yangster-mac94e197c2018-01-02 16:03:03 -0800283 string file_name = StringPrintf("%s/%d-%lld-%ld", STATS_DATA_DIR, key.GetUid(),
284 (long long)key.GetId(), time(nullptr));
yro947fbce2017-11-15 22:50:23 -0800285 StorageManager::writeFile(file_name.c_str(), &data[0], data.size());
286 }
287}
288
Yao Chenef99c4f2017-09-22 16:26:54 -0700289} // namespace statsd
290} // namespace os
291} // namespace android