blob: b5cb20c274ea7c327247de3f8bea54887954997b [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
Joe Onorato9fc9edf2017-10-15 20:08:52 -070017#include "Log.h"
David Chen21582962017-11-01 17:32:46 -070018#include "statslog.h"
Yao Chenab273e22017-09-06 12:53:50 -070019
yro947fbce2017-11-15 22:50:23 -080020#include <android-base/file.h>
21#include <dirent.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070022#include "StatsLogProcessor.h"
yro947fbce2017-11-15 22:50:23 -080023#include "android-base/stringprintf.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070024#include "metrics/CountMetricProducer.h"
25#include "stats_util.h"
yro947fbce2017-11-15 22:50:23 -080026#include "storage/StorageManager.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070027
yro00698da2017-09-15 10:06:40 -070028#include <log/log_event_list.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070029#include <utils/Errors.h>
Yao Chenab273e22017-09-06 12:53:50 -070030
31using namespace android;
yro947fbce2017-11-15 22:50:23 -080032using android::base::StringPrintf;
yrob0378b02017-11-09 20:36:25 -080033using android::util::FIELD_COUNT_REPEATED;
yro17adac92017-11-08 23:16:29 -080034using android::util::FIELD_TYPE_BOOL;
35using android::util::FIELD_TYPE_FLOAT;
36using android::util::FIELD_TYPE_INT32;
37using android::util::FIELD_TYPE_INT64;
38using android::util::FIELD_TYPE_MESSAGE;
39using android::util::FIELD_TYPE_STRING;
40using android::util::ProtoOutputStream;
Yao Chen44cf27c2017-09-14 22:32:50 -070041using std::make_unique;
42using std::unique_ptr;
43using std::vector;
Bookatz906a35c2017-09-20 15:26:44 -070044
45namespace android {
46namespace os {
47namespace statsd {
Yao Chenab273e22017-09-06 12:53:50 -070048
yro947fbce2017-11-15 22:50:23 -080049// for ConfigMetricsReportList
yro17adac92017-11-08 23:16:29 -080050const int FIELD_ID_CONFIG_KEY = 1;
yro947fbce2017-11-15 22:50:23 -080051const int FIELD_ID_REPORTS = 2;
yro17adac92017-11-08 23:16:29 -080052// for ConfigKey
53const int FIELD_ID_UID = 1;
yrob0378b02017-11-09 20:36:25 -080054const int FIELD_ID_NAME = 2;
yro947fbce2017-11-15 22:50:23 -080055// for ConfigMetricsReport
56const int FIELD_ID_METRICS = 1;
57const int FIELD_ID_UID_MAP = 2;
58
59#define STATS_DATA_DIR "/data/system/stats-data"
yro17adac92017-11-08 23:16:29 -080060
yro31eb67b2017-10-24 13:33:21 -070061StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
Yangster-mace2cd6d52017-11-09 20:38:30 -080062 const sp<AnomalyMonitor>& anomalyMonitor,
David Chen1d7b0cd2017-11-15 14:20:04 -080063 const std::function<void(const ConfigKey&)>& sendBroadcast)
Yangster-mace2cd6d52017-11-09 20:38:30 -080064 : mUidMap(uidMap), mAnomalyMonitor(anomalyMonitor), mSendBroadcast(sendBroadcast) {
yro947fbce2017-11-15 22:50:23 -080065 // On each initialization of StatsLogProcessor, check stats-data directory to see if there is
66 // any left over data to be read.
67 StorageManager::sendBroadcast(STATS_DATA_DIR, mSendBroadcast);
Yao Chenab273e22017-09-06 12:53:50 -070068}
69
Yao Chenef99c4f2017-09-22 16:26:54 -070070StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -070071}
72
Yangster-mace2cd6d52017-11-09 20:38:30 -080073void StatsLogProcessor::onAnomalyAlarmFired(
74 const uint64_t timestampNs,
75 unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet) {
76 for (const auto& anomaly : anomalySet) {
77 for (const auto& itr : mMetricsManagers) {
78 itr.second->onAnomalyAlarmFired(timestampNs, anomaly);
79 }
80 }
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 Chen44cf27c2017-09-14 22:32:50 -070085 // pass the event to metrics managers.
86 for (auto& pair : mMetricsManagers) {
87 pair.second->onLogEvent(msg);
yro69007c82017-10-26 20:42:57 -070088 flushIfNecessary(msg.GetTimestampNs(), pair.first, pair.second);
Yao Chenab273e22017-09-06 12:53:50 -070089 }
David Chen21582962017-11-01 17:32:46 -070090
91 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -080092 // The field numbers need to be currently updated by hand with atoms.proto
David Chen21582962017-11-01 17:32:46 -070093 if (msg.GetTagId() == android::util::ISOLATED_UID_CHANGED) {
94 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
95 bool is_create = msg.GetBool(3, &err);
96 auto parent_uid = int(msg.GetLong(1, &err2));
97 auto isolated_uid = int(msg.GetLong(2, &err3));
98 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
99 if (is_create) {
100 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
101 } else {
102 mUidMap->removeIsolatedUid(isolated_uid, parent_uid);
103 }
104 }
105 }
Yao Chenab273e22017-09-06 12:53:50 -0700106}
107
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700108void StatsLogProcessor::OnConfigUpdated(const ConfigKey& key, const StatsdConfig& config) {
109 auto it = mMetricsManagers.find(key);
Yao Chen44cf27c2017-09-14 22:32:50 -0700110 if (it != mMetricsManagers.end()) {
111 it->second->finish();
112 }
113
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700114 ALOGD("Updated configuration for key %s", key.ToString().c_str());
Yao Chen44cf27c2017-09-14 22:32:50 -0700115
Yao Chencaf339d2017-10-06 16:01:10 -0700116 unique_ptr<MetricsManager> newMetricsManager = std::make_unique<MetricsManager>(config);
117 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700118 mUidMap->OnConfigUpdated(key);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800119 newMetricsManager->setAnomalyMonitor(mAnomalyMonitor);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700120 mMetricsManagers[key] = std::move(newMetricsManager);
121 // Why doesn't this work? mMetricsManagers.insert({key, std::move(newMetricsManager)});
Yao Chencaf339d2017-10-06 16:01:10 -0700122 ALOGD("StatsdConfig valid");
123 } else {
124 // If there is any error in the config, don't use it.
125 ALOGD("StatsdConfig NOT valid");
126 }
yro00698da2017-09-15 10:06:40 -0700127}
Bookatz906a35c2017-09-20 15:26:44 -0700128
Yangster7c334a12017-11-22 14:24:24 -0800129size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yao Chen729093d2017-10-16 10:33:26 -0700130 auto it = mMetricsManagers.find(key);
131 if (it == mMetricsManagers.end()) {
132 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800133 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700134 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800135 return it->second->byteSize();
136}
137
138void StatsLogProcessor::onDumpReport(const ConfigKey& key, vector<uint8_t>* outData) {
139 auto it = mMetricsManagers.find(key);
140 if (it == mMetricsManagers.end()) {
141 ALOGW("Config source %s does not exist", key.ToString().c_str());
142 return;
143 }
144
145 // This allows another broadcast to be sent within the rate-limit period if we get close to
146 // filling the buffer again soon.
147 mBroadcastTimesMutex.lock();
148 mLastBroadcastTimes.erase(key);
149 mBroadcastTimesMutex.unlock();
Yao Chen729093d2017-10-16 10:33:26 -0700150
yro17adac92017-11-08 23:16:29 -0800151 ProtoOutputStream proto;
152
yro947fbce2017-11-15 22:50:23 -0800153 // Start of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800154 long long configKeyToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
155 proto.write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
156 proto.write(FIELD_TYPE_STRING | FIELD_ID_NAME, key.GetName());
157 proto.end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800158 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800159
yro947fbce2017-11-15 22:50:23 -0800160 // Start of ConfigMetricsReport (reports).
161 long long reportsToken =
162 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
163
164 // First, fill in ConfigMetricsReport using current data on memory, which
165 // starts from filling in StatsLogReport's.
yro17adac92017-11-08 23:16:29 -0800166 for (auto& m : it->second->onDumpReport()) {
167 // Add each vector of StatsLogReport into a repeated field.
yrob0378b02017-11-09 20:36:25 -0800168 proto.write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_METRICS,
169 reinterpret_cast<char*>(m.get()->data()), m.get()->size());
David Chend6896892017-10-25 11:49:03 -0700170 }
yro17adac92017-11-08 23:16:29 -0800171
172 // Fill in UidMap.
173 auto uidMap = mUidMap->getOutput(key);
174 const int uidMapSize = uidMap.ByteSize();
175 char uidMapBuffer[uidMapSize];
176 uidMap.SerializeToArray(&uidMapBuffer[0], uidMapSize);
177 proto.write(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP, uidMapBuffer, uidMapSize);
178
yro947fbce2017-11-15 22:50:23 -0800179 // End of ConfigMetricsReport (reports).
180 proto.end(reportsToken);
181
182 // Then, check stats-data directory to see there's any file containing
183 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
184 StorageManager::appendConfigMetricsReport(STATS_DATA_DIR, proto);
185
David Chen1d7b0cd2017-11-15 14:20:04 -0800186 if (outData != nullptr) {
187 outData->clear();
188 outData->resize(proto.size());
189 size_t pos = 0;
190 auto iter = proto.data();
191 while (iter.readBuffer() != NULL) {
192 size_t toRead = iter.currentToRead();
193 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
194 pos += toRead;
195 iter.rp()->move(toRead);
196 }
yro17adac92017-11-08 23:16:29 -0800197 }
Yao Chen729093d2017-10-16 10:33:26 -0700198}
199
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700200void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
201 auto it = mMetricsManagers.find(key);
202 if (it != mMetricsManagers.end()) {
203 it->second->finish();
204 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700205 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700206 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800207
208 std::lock_guard<std::mutex> lock(mBroadcastTimesMutex);
209 mLastBroadcastTimes.erase(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700210}
211
yro69007c82017-10-26 20:42:57 -0700212void StatsLogProcessor::flushIfNecessary(uint64_t timestampNs,
213 const ConfigKey& key,
214 const unique_ptr<MetricsManager>& metricsManager) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800215 std::lock_guard<std::mutex> lock(mBroadcastTimesMutex);
yro31eb67b2017-10-24 13:33:21 -0700216
yro69007c82017-10-26 20:42:57 -0700217 size_t totalBytes = metricsManager->byteSize();
David Chen1d7b0cd2017-11-15 14:20:04 -0800218 if (totalBytes > .9 * kMaxSerializedBytes) { // Send broadcast so that receivers can pull data.
219 auto lastFlushNs = mLastBroadcastTimes.find(key);
220 if (lastFlushNs != mLastBroadcastTimes.end()) {
221 if (timestampNs - lastFlushNs->second < kMinBroadcastPeriod) {
222 return;
223 }
224 }
225 mLastBroadcastTimes[key] = timestampNs;
226 ALOGD("StatsD requesting broadcast for %s", key.ToString().c_str());
227 mSendBroadcast(key);
228 } else if (totalBytes > kMaxSerializedBytes) { // Too late. We need to start clearing data.
229 // We ignore the return value so we force each metric producer to clear its contents.
230 metricsManager->onDumpReport();
231 ALOGD("StatsD had to toss out metrics for %s", key.ToString().c_str());
yro31eb67b2017-10-24 13:33:21 -0700232 }
233}
234
yro947fbce2017-11-15 22:50:23 -0800235void StatsLogProcessor::WriteDataToDisk() {
236 mkdir(STATS_DATA_DIR, S_IRWXU);
237 for (auto& pair : mMetricsManagers) {
238 const ConfigKey& key = pair.first;
239 vector<uint8_t> data;
240 onDumpReport(key, &data);
241 // TODO: Add a guardrail to prevent accumulation of file on disk.
242 string file_name = StringPrintf("%s/%d-%s-%ld", STATS_DATA_DIR, key.GetUid(),
243 key.GetName().c_str(), time(nullptr));
244 StorageManager::writeFile(file_name.c_str(), &data[0], data.size());
245 }
246}
247
Yao Chenef99c4f2017-09-22 16:26:54 -0700248} // namespace statsd
249} // namespace os
250} // namespace android