blob: f6caca88eb647118b11e91f62a30d3350cfc6e39 [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;
yrob0378b02017-11-09 20:36:25 -080057const int FIELD_ID_NAME = 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,
David Chen1d7b0cd2017-11-15 14:20:04 -080066 const std::function<void(const ConfigKey&)>& sendBroadcast)
Chenjie Yu85ed8382017-12-14 16:48:54 -080067 : mUidMap(uidMap),
68 mAnomalyMonitor(anomalyMonitor),
69 mSendBroadcast(sendBroadcast),
70 mTimeBaseSec(time(nullptr)) {
yro947fbce2017-11-15 22:50:23 -080071 // On each initialization of StatsLogProcessor, check stats-data directory to see if there is
72 // any left over data to be read.
73 StorageManager::sendBroadcast(STATS_DATA_DIR, mSendBroadcast);
Chenjie Yu85ed8382017-12-14 16:48:54 -080074 StatsPullerManager statsPullerManager;
75 statsPullerManager.SetTimeBaseSec(mTimeBaseSec);
Yao Chenab273e22017-09-06 12:53:50 -070076}
77
Yao Chenef99c4f2017-09-22 16:26:54 -070078StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -070079}
80
Yangster-mace2cd6d52017-11-09 20:38:30 -080081void StatsLogProcessor::onAnomalyAlarmFired(
82 const uint64_t timestampNs,
83 unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet) {
Bookatzcc5adef22017-11-21 14:36:23 -080084 for (const auto& itr : mMetricsManagers) {
85 itr.second->onAnomalyAlarmFired(timestampNs, anomalySet);
Yangster-mace2cd6d52017-11-09 20:38:30 -080086 }
87}
88
Yao Chen44cf27c2017-09-14 22:32:50 -070089// TODO: what if statsd service restarts? How do we know what logs are already processed before?
Joe Onoratoc4dfae52017-10-17 23:38:21 -070090void StatsLogProcessor::OnLogEvent(const LogEvent& msg) {
Yao Chenb3561512017-11-21 18:07:17 -080091 StatsdStats::getInstance().noteAtomLogged(msg.GetTagId(), msg.GetTimestampNs() / NS_PER_SEC);
Yao Chen44cf27c2017-09-14 22:32:50 -070092 // pass the event to metrics managers.
Yao Chen312e8982017-12-05 15:29:03 -080093 for (auto& pair : mMetricsManagers) {
94 pair.second->onLogEvent(msg);
David Chend9269e22017-12-05 13:43:51 -080095 flushIfNecessary(msg.GetTimestampNs(), pair.first, *(pair.second));
Yao Chen312e8982017-12-05 15:29:03 -080096 }
David Chen21582962017-11-01 17:32:46 -070097
98 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -080099 // The field numbers need to be currently updated by hand with atoms.proto
David Chen21582962017-11-01 17:32:46 -0700100 if (msg.GetTagId() == android::util::ISOLATED_UID_CHANGED) {
101 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
102 bool is_create = msg.GetBool(3, &err);
103 auto parent_uid = int(msg.GetLong(1, &err2));
104 auto isolated_uid = int(msg.GetLong(2, &err3));
105 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
106 if (is_create) {
107 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
108 } else {
109 mUidMap->removeIsolatedUid(isolated_uid, parent_uid);
110 }
111 }
112 }
Yao Chenab273e22017-09-06 12:53:50 -0700113}
114
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700115void StatsLogProcessor::OnConfigUpdated(const ConfigKey& key, const StatsdConfig& config) {
Yao Chenb3561512017-11-21 18:07:17 -0800116 ALOGD("Updated configuration for key %s", key.ToString().c_str());
Chenjie Yu85ed8382017-12-14 16:48:54 -0800117 unique_ptr<MetricsManager> newMetricsManager = std::make_unique<MetricsManager>(key, config, mTimeBaseSec);
Yao Chenb3561512017-11-21 18:07:17 -0800118
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700119 auto it = mMetricsManagers.find(key);
Yao Chen288c6002017-12-12 13:43:18 -0800120 if (it == mMetricsManagers.end() && mMetricsManagers.size() > StatsdStats::kMaxConfigCount) {
Yao Chenb3561512017-11-21 18:07:17 -0800121 ALOGE("Can't accept more configs!");
122 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700123 }
124
Yao Chencaf339d2017-10-06 16:01:10 -0700125 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700126 mUidMap->OnConfigUpdated(key);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800127 newMetricsManager->setAnomalyMonitor(mAnomalyMonitor);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700128 mMetricsManagers[key] = std::move(newMetricsManager);
129 // Why doesn't this work? mMetricsManagers.insert({key, std::move(newMetricsManager)});
Yao Chenb3561512017-11-21 18:07:17 -0800130 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700131 } else {
132 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800133 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700134 }
yro00698da2017-09-15 10:06:40 -0700135}
Bookatz906a35c2017-09-20 15:26:44 -0700136
Yangster7c334a12017-11-22 14:24:24 -0800137size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yao Chen729093d2017-10-16 10:33:26 -0700138 auto it = mMetricsManagers.find(key);
139 if (it == mMetricsManagers.end()) {
140 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800141 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700142 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800143 return it->second->byteSize();
144}
145
146void StatsLogProcessor::onDumpReport(const ConfigKey& key, vector<uint8_t>* outData) {
147 auto it = mMetricsManagers.find(key);
148 if (it == mMetricsManagers.end()) {
149 ALOGW("Config source %s does not exist", key.ToString().c_str());
150 return;
151 }
152
153 // This allows another broadcast to be sent within the rate-limit period if we get close to
154 // filling the buffer again soon.
155 mBroadcastTimesMutex.lock();
156 mLastBroadcastTimes.erase(key);
157 mBroadcastTimesMutex.unlock();
Yao Chen729093d2017-10-16 10:33:26 -0700158
yro17adac92017-11-08 23:16:29 -0800159 ProtoOutputStream proto;
160
yro947fbce2017-11-15 22:50:23 -0800161 // Start of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800162 long long configKeyToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
163 proto.write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
164 proto.write(FIELD_TYPE_STRING | FIELD_ID_NAME, key.GetName());
165 proto.end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800166 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800167
yro947fbce2017-11-15 22:50:23 -0800168 // Start of ConfigMetricsReport (reports).
169 long long reportsToken =
170 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
171
172 // First, fill in ConfigMetricsReport using current data on memory, which
173 // starts from filling in StatsLogReport's.
Yao Chen288c6002017-12-12 13:43:18 -0800174 it->second->onDumpReport(&proto);
yro17adac92017-11-08 23:16:29 -0800175
176 // Fill in UidMap.
177 auto uidMap = mUidMap->getOutput(key);
178 const int uidMapSize = uidMap.ByteSize();
179 char uidMapBuffer[uidMapSize];
180 uidMap.SerializeToArray(&uidMapBuffer[0], uidMapSize);
181 proto.write(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP, uidMapBuffer, uidMapSize);
182
yro947fbce2017-11-15 22:50:23 -0800183 // End of ConfigMetricsReport (reports).
184 proto.end(reportsToken);
185
186 // Then, check stats-data directory to see there's any file containing
187 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
188 StorageManager::appendConfigMetricsReport(STATS_DATA_DIR, proto);
189
David Chen1d7b0cd2017-11-15 14:20:04 -0800190 if (outData != nullptr) {
191 outData->clear();
192 outData->resize(proto.size());
193 size_t pos = 0;
194 auto iter = proto.data();
195 while (iter.readBuffer() != NULL) {
196 size_t toRead = iter.currentToRead();
197 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
198 pos += toRead;
199 iter.rp()->move(toRead);
200 }
yro17adac92017-11-08 23:16:29 -0800201 }
Yao Chen69f1baf2017-11-27 17:25:36 -0800202 StatsdStats::getInstance().noteMetricsReportSent(key);
Yao Chen729093d2017-10-16 10:33:26 -0700203}
204
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700205void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
206 auto it = mMetricsManagers.find(key);
207 if (it != mMetricsManagers.end()) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700208 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700209 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700210 }
Yao Chenb3561512017-11-21 18:07:17 -0800211 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800212
213 std::lock_guard<std::mutex> lock(mBroadcastTimesMutex);
214 mLastBroadcastTimes.erase(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700215}
216
David Chend9269e22017-12-05 13:43:51 -0800217void StatsLogProcessor::flushIfNecessary(uint64_t timestampNs, const ConfigKey& key,
218 MetricsManager& metricsManager) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800219 std::lock_guard<std::mutex> lock(mBroadcastTimesMutex);
yro31eb67b2017-10-24 13:33:21 -0700220
David Chend9269e22017-12-05 13:43:51 -0800221 auto lastCheckTime = mLastByteSizeTimes.find(key);
222 if (lastCheckTime != mLastByteSizeTimes.end()) {
223 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
224 return;
225 }
226 }
227
228 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
229 size_t totalBytes = metricsManager.byteSize();
230 mLastByteSizeTimes[key] = timestampNs;
231 if (totalBytes >
232 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen288c6002017-12-12 13:43:18 -0800233 // TODO(b/70571383): By 12/15/2017 add API to drop data directly
234 ProtoOutputStream proto;
235 metricsManager.onDumpReport(&proto);
David Chen12942952017-12-04 14:28:43 -0800236 StatsdStats::getInstance().noteDataDropped(key);
237 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chend9269e22017-12-05 13:43:51 -0800238 } else if (totalBytes > .9 * StatsdStats::kMaxMetricsBytesPerConfig) {
239 // Send broadcast so that receivers can pull data.
240 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
241 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
242 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
243 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800244 return;
245 }
246 }
247 mLastBroadcastTimes[key] = timestampNs;
Yao Chenb3561512017-11-21 18:07:17 -0800248 VLOG("StatsD requesting broadcast for %s", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800249 mSendBroadcast(key);
Yao Chenb3561512017-11-21 18:07:17 -0800250 StatsdStats::getInstance().noteBroadcastSent(key);
yro31eb67b2017-10-24 13:33:21 -0700251 }
252}
253
yro947fbce2017-11-15 22:50:23 -0800254void StatsLogProcessor::WriteDataToDisk() {
255 mkdir(STATS_DATA_DIR, S_IRWXU);
256 for (auto& pair : mMetricsManagers) {
257 const ConfigKey& key = pair.first;
258 vector<uint8_t> data;
259 onDumpReport(key, &data);
260 // TODO: Add a guardrail to prevent accumulation of file on disk.
261 string file_name = StringPrintf("%s/%d-%s-%ld", STATS_DATA_DIR, key.GetUid(),
262 key.GetName().c_str(), time(nullptr));
263 StorageManager::writeFile(file_name.c_str(), &data[0], data.size());
264 }
265}
266
Yao Chenef99c4f2017-09-22 16:26:54 -0700267} // namespace statsd
268} // namespace os
269} // namespace android