blob: 0c078d5db83ccbdb17dbb841c58010644000781d [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());
Yao Chend10f7b12017-12-18 12:53:50 -0800117
118 sp<MetricsManager> newMetricsManager = new MetricsManager(key, config, mTimeBaseSec, mUidMap);
Yao Chenb3561512017-11-21 18:07:17 -0800119
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700120 auto it = mMetricsManagers.find(key);
Yao Chen288c6002017-12-12 13:43:18 -0800121 if (it == mMetricsManagers.end() && mMetricsManagers.size() > StatsdStats::kMaxConfigCount) {
Yao Chenb3561512017-11-21 18:07:17 -0800122 ALOGE("Can't accept more configs!");
123 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700124 }
125
Yao Chencaf339d2017-10-06 16:01:10 -0700126 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700127 mUidMap->OnConfigUpdated(key);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800128 newMetricsManager->setAnomalyMonitor(mAnomalyMonitor);
Yao Chend10f7b12017-12-18 12:53:50 -0800129 if (config.log_source().package().size() > 0) {
130 // We have to add listener after the MetricsManager is constructed because it's
131 // not safe to create wp or sp from this pointer inside its constructor.
132 mUidMap->addListener(newMetricsManager.get());
133 }
134 mMetricsManagers[key] = newMetricsManager;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700135 // Why doesn't this work? mMetricsManagers.insert({key, std::move(newMetricsManager)});
Yao Chenb3561512017-11-21 18:07:17 -0800136 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700137 } else {
138 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800139 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700140 }
yro00698da2017-09-15 10:06:40 -0700141}
Bookatz906a35c2017-09-20 15:26:44 -0700142
Yangster7c334a12017-11-22 14:24:24 -0800143size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yao Chen729093d2017-10-16 10:33:26 -0700144 auto it = mMetricsManagers.find(key);
145 if (it == mMetricsManagers.end()) {
146 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800147 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700148 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800149 return it->second->byteSize();
150}
151
152void StatsLogProcessor::onDumpReport(const ConfigKey& key, vector<uint8_t>* outData) {
153 auto it = mMetricsManagers.find(key);
154 if (it == mMetricsManagers.end()) {
155 ALOGW("Config source %s does not exist", key.ToString().c_str());
156 return;
157 }
158
159 // This allows another broadcast to be sent within the rate-limit period if we get close to
160 // filling the buffer again soon.
161 mBroadcastTimesMutex.lock();
162 mLastBroadcastTimes.erase(key);
163 mBroadcastTimesMutex.unlock();
Yao Chen729093d2017-10-16 10:33:26 -0700164
yro17adac92017-11-08 23:16:29 -0800165 ProtoOutputStream proto;
166
yro947fbce2017-11-15 22:50:23 -0800167 // Start of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800168 long long configKeyToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
169 proto.write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
170 proto.write(FIELD_TYPE_STRING | FIELD_ID_NAME, key.GetName());
171 proto.end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800172 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800173
yro947fbce2017-11-15 22:50:23 -0800174 // Start of ConfigMetricsReport (reports).
175 long long reportsToken =
176 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
177
178 // First, fill in ConfigMetricsReport using current data on memory, which
179 // starts from filling in StatsLogReport's.
Yao Chen288c6002017-12-12 13:43:18 -0800180 it->second->onDumpReport(&proto);
yro17adac92017-11-08 23:16:29 -0800181
182 // Fill in UidMap.
183 auto uidMap = mUidMap->getOutput(key);
184 const int uidMapSize = uidMap.ByteSize();
185 char uidMapBuffer[uidMapSize];
186 uidMap.SerializeToArray(&uidMapBuffer[0], uidMapSize);
187 proto.write(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP, uidMapBuffer, uidMapSize);
188
yro947fbce2017-11-15 22:50:23 -0800189 // End of ConfigMetricsReport (reports).
190 proto.end(reportsToken);
191
192 // Then, check stats-data directory to see there's any file containing
193 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
194 StorageManager::appendConfigMetricsReport(STATS_DATA_DIR, proto);
195
David Chen1d7b0cd2017-11-15 14:20:04 -0800196 if (outData != nullptr) {
197 outData->clear();
198 outData->resize(proto.size());
199 size_t pos = 0;
200 auto iter = proto.data();
201 while (iter.readBuffer() != NULL) {
202 size_t toRead = iter.currentToRead();
203 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
204 pos += toRead;
205 iter.rp()->move(toRead);
206 }
yro17adac92017-11-08 23:16:29 -0800207 }
Yao Chen69f1baf2017-11-27 17:25:36 -0800208 StatsdStats::getInstance().noteMetricsReportSent(key);
Yao Chen729093d2017-10-16 10:33:26 -0700209}
210
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700211void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
212 auto it = mMetricsManagers.find(key);
213 if (it != mMetricsManagers.end()) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700214 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700215 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700216 }
Yao Chenb3561512017-11-21 18:07:17 -0800217 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800218
219 std::lock_guard<std::mutex> lock(mBroadcastTimesMutex);
220 mLastBroadcastTimes.erase(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700221}
222
David Chend9269e22017-12-05 13:43:51 -0800223void StatsLogProcessor::flushIfNecessary(uint64_t timestampNs, const ConfigKey& key,
224 MetricsManager& metricsManager) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800225 std::lock_guard<std::mutex> lock(mBroadcastTimesMutex);
yro31eb67b2017-10-24 13:33:21 -0700226
David Chend9269e22017-12-05 13:43:51 -0800227 auto lastCheckTime = mLastByteSizeTimes.find(key);
228 if (lastCheckTime != mLastByteSizeTimes.end()) {
229 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
230 return;
231 }
232 }
233
234 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
235 size_t totalBytes = metricsManager.byteSize();
236 mLastByteSizeTimes[key] = timestampNs;
237 if (totalBytes >
238 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen288c6002017-12-12 13:43:18 -0800239 // TODO(b/70571383): By 12/15/2017 add API to drop data directly
240 ProtoOutputStream proto;
241 metricsManager.onDumpReport(&proto);
David Chen12942952017-12-04 14:28:43 -0800242 StatsdStats::getInstance().noteDataDropped(key);
243 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chend9269e22017-12-05 13:43:51 -0800244 } else if (totalBytes > .9 * StatsdStats::kMaxMetricsBytesPerConfig) {
245 // Send broadcast so that receivers can pull data.
246 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
247 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
248 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
249 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800250 return;
251 }
252 }
253 mLastBroadcastTimes[key] = timestampNs;
Yao Chenb3561512017-11-21 18:07:17 -0800254 VLOG("StatsD requesting broadcast for %s", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800255 mSendBroadcast(key);
Yao Chenb3561512017-11-21 18:07:17 -0800256 StatsdStats::getInstance().noteBroadcastSent(key);
yro31eb67b2017-10-24 13:33:21 -0700257 }
258}
259
yro947fbce2017-11-15 22:50:23 -0800260void StatsLogProcessor::WriteDataToDisk() {
261 mkdir(STATS_DATA_DIR, S_IRWXU);
262 for (auto& pair : mMetricsManagers) {
263 const ConfigKey& key = pair.first;
264 vector<uint8_t> data;
265 onDumpReport(key, &data);
266 // TODO: Add a guardrail to prevent accumulation of file on disk.
267 string file_name = StringPrintf("%s/%d-%s-%ld", STATS_DATA_DIR, key.GetUid(),
268 key.GetName().c_str(), time(nullptr));
269 StorageManager::writeFile(file_name.c_str(), &data[0], data.size());
270 }
271}
272
Yao Chenef99c4f2017-09-22 16:26:54 -0700273} // namespace statsd
274} // namespace os
275} // namespace android