blob: 2fd794777cb6233a63c59cfb577450d046a5bd51 [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"
27#include "stats_util.h"
yro947fbce2017-11-15 22:50:23 -080028#include "storage/StorageManager.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070029
yro00698da2017-09-15 10:06:40 -070030#include <log/log_event_list.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070031#include <utils/Errors.h>
Yao Chenab273e22017-09-06 12:53:50 -070032
33using namespace android;
yro947fbce2017-11-15 22:50:23 -080034using android::base::StringPrintf;
yrob0378b02017-11-09 20:36:25 -080035using android::util::FIELD_COUNT_REPEATED;
yro17adac92017-11-08 23:16:29 -080036using android::util::FIELD_TYPE_BOOL;
37using android::util::FIELD_TYPE_FLOAT;
38using android::util::FIELD_TYPE_INT32;
39using android::util::FIELD_TYPE_INT64;
40using android::util::FIELD_TYPE_MESSAGE;
41using android::util::FIELD_TYPE_STRING;
42using android::util::ProtoOutputStream;
Yao Chen44cf27c2017-09-14 22:32:50 -070043using std::make_unique;
44using std::unique_ptr;
45using std::vector;
Bookatz906a35c2017-09-20 15:26:44 -070046
47namespace android {
48namespace os {
49namespace statsd {
Yao Chenab273e22017-09-06 12:53:50 -070050
yro947fbce2017-11-15 22:50:23 -080051// for ConfigMetricsReportList
yro17adac92017-11-08 23:16:29 -080052const int FIELD_ID_CONFIG_KEY = 1;
yro947fbce2017-11-15 22:50:23 -080053const int FIELD_ID_REPORTS = 2;
yro17adac92017-11-08 23:16:29 -080054// for ConfigKey
55const int FIELD_ID_UID = 1;
yrob0378b02017-11-09 20:36:25 -080056const int FIELD_ID_NAME = 2;
yro947fbce2017-11-15 22:50:23 -080057// for ConfigMetricsReport
58const int FIELD_ID_METRICS = 1;
59const int FIELD_ID_UID_MAP = 2;
60
61#define STATS_DATA_DIR "/data/system/stats-data"
yro17adac92017-11-08 23:16:29 -080062
yro31eb67b2017-10-24 13:33:21 -070063StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
Yangster-mace2cd6d52017-11-09 20:38:30 -080064 const sp<AnomalyMonitor>& anomalyMonitor,
David Chen1d7b0cd2017-11-15 14:20:04 -080065 const std::function<void(const ConfigKey&)>& sendBroadcast)
Yangster-mace2cd6d52017-11-09 20:38:30 -080066 : mUidMap(uidMap), mAnomalyMonitor(anomalyMonitor), mSendBroadcast(sendBroadcast) {
yro947fbce2017-11-15 22:50:23 -080067 // On each initialization of StatsLogProcessor, check stats-data directory to see if there is
68 // any left over data to be read.
69 StorageManager::sendBroadcast(STATS_DATA_DIR, mSendBroadcast);
Yao Chenab273e22017-09-06 12:53:50 -070070}
71
Yao Chenef99c4f2017-09-22 16:26:54 -070072StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -070073}
74
Yangster-mace2cd6d52017-11-09 20:38:30 -080075void StatsLogProcessor::onAnomalyAlarmFired(
76 const uint64_t timestampNs,
77 unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet) {
Bookatzcc5adef22017-11-21 14:36:23 -080078 for (const auto& itr : mMetricsManagers) {
79 itr.second->onAnomalyAlarmFired(timestampNs, anomalySet);
Yangster-mace2cd6d52017-11-09 20:38:30 -080080 }
81}
82
Yao Chen44cf27c2017-09-14 22:32:50 -070083// TODO: what if statsd service restarts? How do we know what logs are already processed before?
Joe Onoratoc4dfae52017-10-17 23:38:21 -070084void StatsLogProcessor::OnLogEvent(const LogEvent& msg) {
Yao Chenb3561512017-11-21 18:07:17 -080085 StatsdStats::getInstance().noteAtomLogged(msg.GetTagId(), msg.GetTimestampNs() / NS_PER_SEC);
Yao Chen44cf27c2017-09-14 22:32:50 -070086 // pass the event to metrics managers.
87 for (auto& pair : mMetricsManagers) {
88 pair.second->onLogEvent(msg);
yro69007c82017-10-26 20:42:57 -070089 flushIfNecessary(msg.GetTimestampNs(), pair.first, pair.second);
Yao Chenab273e22017-09-06 12:53:50 -070090 }
David Chen21582962017-11-01 17:32:46 -070091
92 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -080093 // The field numbers need to be currently updated by hand with atoms.proto
David Chen21582962017-11-01 17:32:46 -070094 if (msg.GetTagId() == android::util::ISOLATED_UID_CHANGED) {
95 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
96 bool is_create = msg.GetBool(3, &err);
97 auto parent_uid = int(msg.GetLong(1, &err2));
98 auto isolated_uid = int(msg.GetLong(2, &err3));
99 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
100 if (is_create) {
101 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
102 } else {
103 mUidMap->removeIsolatedUid(isolated_uid, parent_uid);
104 }
105 }
106 }
Yao Chenab273e22017-09-06 12:53:50 -0700107}
108
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700109void StatsLogProcessor::OnConfigUpdated(const ConfigKey& key, const StatsdConfig& config) {
Yao Chenb3561512017-11-21 18:07:17 -0800110 ALOGD("Updated configuration for key %s", key.ToString().c_str());
111 unique_ptr<MetricsManager> newMetricsManager = std::make_unique<MetricsManager>(key, config);
112
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700113 auto it = mMetricsManagers.find(key);
Yao Chen44cf27c2017-09-14 22:32:50 -0700114 if (it != mMetricsManagers.end()) {
115 it->second->finish();
Yao Chenb3561512017-11-21 18:07:17 -0800116 } else if (mMetricsManagers.size() > StatsdStats::kMaxConfigCount) {
117 ALOGE("Can't accept more configs!");
118 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700119 }
120
Yao Chencaf339d2017-10-06 16:01:10 -0700121 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700122 mUidMap->OnConfigUpdated(key);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800123 newMetricsManager->setAnomalyMonitor(mAnomalyMonitor);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700124 mMetricsManagers[key] = std::move(newMetricsManager);
125 // Why doesn't this work? mMetricsManagers.insert({key, std::move(newMetricsManager)});
Yao Chenb3561512017-11-21 18:07:17 -0800126 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700127 } else {
128 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800129 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700130 }
yro00698da2017-09-15 10:06:40 -0700131}
Bookatz906a35c2017-09-20 15:26:44 -0700132
Yangster7c334a12017-11-22 14:24:24 -0800133size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yao Chen729093d2017-10-16 10:33:26 -0700134 auto it = mMetricsManagers.find(key);
135 if (it == mMetricsManagers.end()) {
136 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800137 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700138 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800139 return it->second->byteSize();
140}
141
142void StatsLogProcessor::onDumpReport(const ConfigKey& key, vector<uint8_t>* outData) {
143 auto it = mMetricsManagers.find(key);
144 if (it == mMetricsManagers.end()) {
145 ALOGW("Config source %s does not exist", key.ToString().c_str());
146 return;
147 }
148
149 // This allows another broadcast to be sent within the rate-limit period if we get close to
150 // filling the buffer again soon.
151 mBroadcastTimesMutex.lock();
152 mLastBroadcastTimes.erase(key);
153 mBroadcastTimesMutex.unlock();
Yao Chen729093d2017-10-16 10:33:26 -0700154
yro17adac92017-11-08 23:16:29 -0800155 ProtoOutputStream proto;
156
yro947fbce2017-11-15 22:50:23 -0800157 // Start of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800158 long long configKeyToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
159 proto.write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
160 proto.write(FIELD_TYPE_STRING | FIELD_ID_NAME, key.GetName());
161 proto.end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800162 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800163
yro947fbce2017-11-15 22:50:23 -0800164 // Start of ConfigMetricsReport (reports).
165 long long reportsToken =
166 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
167
168 // First, fill in ConfigMetricsReport using current data on memory, which
169 // starts from filling in StatsLogReport's.
yro17adac92017-11-08 23:16:29 -0800170 for (auto& m : it->second->onDumpReport()) {
171 // Add each vector of StatsLogReport into a repeated field.
yrob0378b02017-11-09 20:36:25 -0800172 proto.write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_METRICS,
173 reinterpret_cast<char*>(m.get()->data()), m.get()->size());
David Chend6896892017-10-25 11:49:03 -0700174 }
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()) {
208 it->second->finish();
209 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700210 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700211 }
Yao Chenb3561512017-11-21 18:07:17 -0800212 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800213
214 std::lock_guard<std::mutex> lock(mBroadcastTimesMutex);
215 mLastBroadcastTimes.erase(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700216}
217
yro69007c82017-10-26 20:42:57 -0700218void StatsLogProcessor::flushIfNecessary(uint64_t timestampNs,
219 const ConfigKey& key,
220 const unique_ptr<MetricsManager>& metricsManager) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800221 std::lock_guard<std::mutex> lock(mBroadcastTimesMutex);
yro31eb67b2017-10-24 13:33:21 -0700222
David Chenc136f45a2017-11-27 11:52:26 -0800223 size_t totalBytes = metricsManager->byteSize() + mUidMap->getBytesUsed();
David Chen1d7b0cd2017-11-15 14:20:04 -0800224 if (totalBytes > .9 * kMaxSerializedBytes) { // Send broadcast so that receivers can pull data.
225 auto lastFlushNs = mLastBroadcastTimes.find(key);
226 if (lastFlushNs != mLastBroadcastTimes.end()) {
227 if (timestampNs - lastFlushNs->second < kMinBroadcastPeriod) {
228 return;
229 }
230 }
231 mLastBroadcastTimes[key] = timestampNs;
Yao Chenb3561512017-11-21 18:07:17 -0800232 VLOG("StatsD requesting broadcast for %s", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800233 mSendBroadcast(key);
Yao Chenb3561512017-11-21 18:07:17 -0800234 StatsdStats::getInstance().noteBroadcastSent(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800235 } else if (totalBytes > kMaxSerializedBytes) { // Too late. We need to start clearing data.
236 // We ignore the return value so we force each metric producer to clear its contents.
237 metricsManager->onDumpReport();
Yao Chen69f1baf2017-11-27 17:25:36 -0800238 StatsdStats::getInstance().noteDataDropped(key);
Yao Chenb3561512017-11-21 18:07:17 -0800239 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
yro31eb67b2017-10-24 13:33:21 -0700240 }
241}
242
yro947fbce2017-11-15 22:50:23 -0800243void StatsLogProcessor::WriteDataToDisk() {
244 mkdir(STATS_DATA_DIR, S_IRWXU);
245 for (auto& pair : mMetricsManagers) {
246 const ConfigKey& key = pair.first;
247 vector<uint8_t> data;
248 onDumpReport(key, &data);
249 // TODO: Add a guardrail to prevent accumulation of file on disk.
250 string file_name = StringPrintf("%s/%d-%s-%ld", STATS_DATA_DIR, key.GetUid(),
251 key.GetName().c_str(), time(nullptr));
252 StorageManager::writeFile(file_name.c_str(), &data[0], data.size());
253 }
254}
255
Yao Chenef99c4f2017-09-22 16:26:54 -0700256} // namespace statsd
257} // namespace os
258} // namespace android