1 /*
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 
17 #define DEBUG false  // STOPSHIP if true
18 #include "Log.h"
19 
20 #include "StatsLogProcessor.h"
21 
22 #include <android-base/file.h>
23 #include <cutils/multiuser.h>
24 #include <frameworks/base/cmds/statsd/src/active_config_list.pb.h>
25 #include <frameworks/base/cmds/statsd/src/experiment_ids.pb.h>
26 
27 #include "android-base/stringprintf.h"
28 #include "external/StatsPullerManager.h"
29 #include "guardrail/StatsdStats.h"
30 #include "logd/LogEvent.h"
31 #include "metrics/CountMetricProducer.h"
32 #include "StatsService.h"
33 #include "state/StateManager.h"
34 #include "stats_log_util.h"
35 #include "stats_util.h"
36 #include "statslog_statsd.h"
37 #include "storage/StorageManager.h"
38 
39 using namespace android;
40 using android::base::StringPrintf;
41 using android::util::FIELD_COUNT_REPEATED;
42 using android::util::FIELD_TYPE_BOOL;
43 using android::util::FIELD_TYPE_FLOAT;
44 using android::util::FIELD_TYPE_INT32;
45 using android::util::FIELD_TYPE_INT64;
46 using android::util::FIELD_TYPE_MESSAGE;
47 using android::util::FIELD_TYPE_STRING;
48 using android::util::ProtoOutputStream;
49 using std::vector;
50 
51 namespace android {
52 namespace os {
53 namespace statsd {
54 
55 // for ConfigMetricsReportList
56 const int FIELD_ID_CONFIG_KEY = 1;
57 const int FIELD_ID_REPORTS = 2;
58 // for ConfigKey
59 const int FIELD_ID_UID = 1;
60 const int FIELD_ID_ID = 2;
61 // for ConfigMetricsReport
62 // const int FIELD_ID_METRICS = 1; // written in MetricsManager.cpp
63 const int FIELD_ID_UID_MAP = 2;
64 const int FIELD_ID_LAST_REPORT_ELAPSED_NANOS = 3;
65 const int FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS = 4;
66 const int FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS = 5;
67 const int FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS = 6;
68 const int FIELD_ID_DUMP_REPORT_REASON = 8;
69 const int FIELD_ID_STRINGS = 9;
70 
71 // for ActiveConfigList
72 const int FIELD_ID_ACTIVE_CONFIG_LIST_CONFIG = 1;
73 
74 // for permissions checks
75 constexpr const char* kPermissionDump = "android.permission.DUMP";
76 constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
77 
78 #define NS_PER_HOUR 3600 * NS_PER_SEC
79 
80 #define STATS_ACTIVE_METRIC_DIR "/data/misc/stats-active-metric"
81 #define STATS_METADATA_DIR "/data/misc/stats-metadata"
82 
83 // Cool down period for writing data to disk to avoid overwriting files.
84 #define WRITE_DATA_COOL_DOWN_SEC 5
85 
StatsLogProcessor(const sp<UidMap> & uidMap,const sp<StatsPullerManager> & pullerManager,const sp<AlarmMonitor> & anomalyAlarmMonitor,const sp<AlarmMonitor> & periodicAlarmMonitor,const int64_t timeBaseNs,const std::function<bool (const ConfigKey &)> & sendBroadcast,const std::function<bool (const int &,const vector<int64_t> &)> & activateBroadcast)86 StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
87                                      const sp<StatsPullerManager>& pullerManager,
88                                      const sp<AlarmMonitor>& anomalyAlarmMonitor,
89                                      const sp<AlarmMonitor>& periodicAlarmMonitor,
90                                      const int64_t timeBaseNs,
91                                      const std::function<bool(const ConfigKey&)>& sendBroadcast,
92                                      const std::function<bool(
93                                             const int&, const vector<int64_t>&)>& activateBroadcast)
94     : mUidMap(uidMap),
95       mPullerManager(pullerManager),
96       mAnomalyAlarmMonitor(anomalyAlarmMonitor),
97       mPeriodicAlarmMonitor(periodicAlarmMonitor),
98       mSendBroadcast(sendBroadcast),
99       mSendActivationBroadcast(activateBroadcast),
100       mTimeBaseNs(timeBaseNs),
101       mLargestTimestampSeen(0),
102       mLastTimestampSeen(0) {
103     mPullerManager->ForceClearPullerCache();
104     StateManager::getInstance().updateLogSources(uidMap);
105 }
106 
~StatsLogProcessor()107 StatsLogProcessor::~StatsLogProcessor() {
108 }
109 
flushProtoToBuffer(ProtoOutputStream & proto,vector<uint8_t> * outData)110 static void flushProtoToBuffer(ProtoOutputStream& proto, vector<uint8_t>* outData) {
111     outData->clear();
112     outData->resize(proto.size());
113     size_t pos = 0;
114     sp<android::util::ProtoReader> reader = proto.data();
115     while (reader->readBuffer() != NULL) {
116         size_t toRead = reader->currentToRead();
117         std::memcpy(&((*outData)[pos]), reader->readBuffer(), toRead);
118         pos += toRead;
119         reader->move(toRead);
120     }
121 }
122 
onAnomalyAlarmFired(const int64_t & timestampNs,unordered_set<sp<const InternalAlarm>,SpHash<InternalAlarm>> alarmSet)123 void StatsLogProcessor::onAnomalyAlarmFired(
124         const int64_t& timestampNs,
125         unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
126     std::lock_guard<std::mutex> lock(mMetricsMutex);
127     for (const auto& itr : mMetricsManagers) {
128         itr.second->onAnomalyAlarmFired(timestampNs, alarmSet);
129     }
130 }
onPeriodicAlarmFired(const int64_t & timestampNs,unordered_set<sp<const InternalAlarm>,SpHash<InternalAlarm>> alarmSet)131 void StatsLogProcessor::onPeriodicAlarmFired(
132         const int64_t& timestampNs,
133         unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
134 
135     std::lock_guard<std::mutex> lock(mMetricsMutex);
136     for (const auto& itr : mMetricsManagers) {
137         itr.second->onPeriodicAlarmFired(timestampNs, alarmSet);
138     }
139 }
140 
mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent * event) const141 void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
142     if (std::pair<int, int> indexRange; event->hasAttributionChain(&indexRange)) {
143         vector<FieldValue>* const fieldValues = event->getMutableValues();
144         for (int i = indexRange.first; i <= indexRange.second; i++) {
145             FieldValue& fieldValue = fieldValues->at(i);
146             if (isAttributionUidField(fieldValue)) {
147                 const int hostUid = mUidMap->getHostUidOrSelf(fieldValue.mValue.int_value);
148                 fieldValue.mValue.setInt(hostUid);
149             }
150         }
151     } else {
152         int uidFieldIndex = event->getUidFieldIndex();
153         if (uidFieldIndex != -1) {
154            Value& value = (*event->getMutableValues())[uidFieldIndex].mValue;
155            const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
156            value.setInt(hostUid);
157         }
158     }
159 }
160 
onIsolatedUidChangedEventLocked(const LogEvent & event)161 void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
162     status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
163     bool is_create = event.GetBool(3, &err);
164     auto parent_uid = int(event.GetLong(1, &err2));
165     auto isolated_uid = int(event.GetLong(2, &err3));
166     if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
167         if (is_create) {
168             mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
169         } else {
170             mUidMap->removeIsolatedUid(isolated_uid);
171         }
172     } else {
173         ALOGE("Failed to parse uid in the isolated uid change event.");
174     }
175 }
176 
onBinaryPushStateChangedEventLocked(LogEvent * event)177 void StatsLogProcessor::onBinaryPushStateChangedEventLocked(LogEvent* event) {
178     pid_t pid = event->GetPid();
179     uid_t uid = event->GetUid();
180     if (!checkPermissionForIds(kPermissionDump, pid, uid) ||
181         !checkPermissionForIds(kPermissionUsage, pid, uid)) {
182         return;
183     }
184     // The Get* functions don't modify the status on success, they only write in
185     // failure statuses, so we can use one status variable for all calls then
186     // check if it is no longer NO_ERROR.
187     status_t err = NO_ERROR;
188     InstallTrainInfo trainInfo;
189     trainInfo.trainName = string(event->GetString(1 /*train name field id*/, &err));
190     trainInfo.trainVersionCode = event->GetLong(2 /*train version field id*/, &err);
191     trainInfo.requiresStaging = event->GetBool(3 /*requires staging field id*/, &err);
192     trainInfo.rollbackEnabled = event->GetBool(4 /*rollback enabled field id*/, &err);
193     trainInfo.requiresLowLatencyMonitor =
194             event->GetBool(5 /*requires low latency monitor field id*/, &err);
195     trainInfo.status = int32_t(event->GetLong(6 /*state field id*/, &err));
196     std::vector<uint8_t> trainExperimentIdBytes =
197             event->GetStorage(7 /*experiment ids field id*/, &err);
198     bool is_rollback = event->GetBool(10 /*is rollback field id*/, &err);
199 
200     if (err != NO_ERROR) {
201         ALOGE("Failed to parse fields in binary push state changed log event");
202         return;
203     }
204     ExperimentIds trainExperimentIds;
205     if (!trainExperimentIds.ParseFromArray(trainExperimentIdBytes.data(),
206                                            trainExperimentIdBytes.size())) {
207         ALOGE("Failed to parse experimentids in binary push state changed.");
208         return;
209     }
210     trainInfo.experimentIds = {trainExperimentIds.experiment_id().begin(),
211                                trainExperimentIds.experiment_id().end()};
212 
213     // Update the train info on disk and get any data the logevent is missing.
214     getAndUpdateTrainInfoOnDisk(is_rollback, &trainInfo);
215 
216     std::vector<uint8_t> trainExperimentIdProto;
217     writeExperimentIdsToProto(trainInfo.experimentIds, &trainExperimentIdProto);
218     int32_t userId = multiuser_get_user_id(uid);
219 
220     event->updateValue(2 /*train version field id*/, trainInfo.trainVersionCode, LONG);
221     event->updateValue(7 /*experiment ids field id*/, trainExperimentIdProto, STORAGE);
222     event->updateValue(8 /*user id field id*/, userId, INT);
223 
224     // If this event is a rollback event, then the following bits in the event
225     // are invalid and we will need to update them with the values we pulled
226     // from disk.
227     if (is_rollback) {
228         int bit = trainInfo.requiresStaging ? 1 : 0;
229         event->updateValue(3 /*requires staging field id*/, bit, INT);
230         bit = trainInfo.rollbackEnabled ? 1 : 0;
231         event->updateValue(4 /*rollback enabled field id*/, bit, INT);
232         bit = trainInfo.requiresLowLatencyMonitor ? 1 : 0;
233         event->updateValue(5 /*requires low latency monitor field id*/, bit, INT);
234     }
235 }
236 
getAndUpdateTrainInfoOnDisk(bool is_rollback,InstallTrainInfo * trainInfo)237 void StatsLogProcessor::getAndUpdateTrainInfoOnDisk(bool is_rollback,
238                                                     InstallTrainInfo* trainInfo) {
239     // If the train name is empty, we don't know which train to attribute the
240     // event to, so return early.
241     if (trainInfo->trainName.empty()) {
242         return;
243     }
244     bool readTrainInfoSuccess = false;
245     InstallTrainInfo trainInfoOnDisk;
246     readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfo->trainName, trainInfoOnDisk);
247 
248     bool resetExperimentIds = false;
249     if (readTrainInfoSuccess) {
250         // Keep the old train version if we received an empty version.
251         if (trainInfo->trainVersionCode == -1) {
252             trainInfo->trainVersionCode = trainInfoOnDisk.trainVersionCode;
253         } else if (trainInfo->trainVersionCode != trainInfoOnDisk.trainVersionCode) {
254             // Reset experiment ids if we receive a new non-empty train version.
255             resetExperimentIds = true;
256         }
257 
258         // Reset if we received a different experiment id.
259         if (!trainInfo->experimentIds.empty() &&
260             (trainInfoOnDisk.experimentIds.empty() ||
261              trainInfo->experimentIds.at(0) != trainInfoOnDisk.experimentIds[0])) {
262             resetExperimentIds = true;
263         }
264     }
265 
266     // Find the right experiment IDs
267     if ((!resetExperimentIds || is_rollback) && readTrainInfoSuccess) {
268         trainInfo->experimentIds = trainInfoOnDisk.experimentIds;
269     }
270 
271     if (!trainInfo->experimentIds.empty()) {
272         int64_t firstId = trainInfo->experimentIds.at(0);
273         auto& ids = trainInfo->experimentIds;
274         switch (trainInfo->status) {
275             case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
276                 if (find(ids.begin(), ids.end(), firstId + 1) == ids.end()) {
277                     ids.push_back(firstId + 1);
278                 }
279                 break;
280             case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
281                 if (find(ids.begin(), ids.end(), firstId + 2) == ids.end()) {
282                     ids.push_back(firstId + 2);
283                 }
284                 break;
285             case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
286                 if (find(ids.begin(), ids.end(), firstId + 3) == ids.end()) {
287                     ids.push_back(firstId + 3);
288                 }
289                 break;
290         }
291     }
292 
293     // If this event is a rollback event, the following fields are invalid and
294     // need to be replaced by the fields stored to disk.
295     if (is_rollback) {
296         trainInfo->requiresStaging = trainInfoOnDisk.requiresStaging;
297         trainInfo->rollbackEnabled = trainInfoOnDisk.rollbackEnabled;
298         trainInfo->requiresLowLatencyMonitor = trainInfoOnDisk.requiresLowLatencyMonitor;
299     }
300 
301     StorageManager::writeTrainInfo(*trainInfo);
302 }
303 
onWatchdogRollbackOccurredLocked(LogEvent * event)304 void StatsLogProcessor::onWatchdogRollbackOccurredLocked(LogEvent* event) {
305     pid_t pid = event->GetPid();
306     uid_t uid = event->GetUid();
307     if (!checkPermissionForIds(kPermissionDump, pid, uid) ||
308         !checkPermissionForIds(kPermissionUsage, pid, uid)) {
309         return;
310     }
311     // The Get* functions don't modify the status on success, they only write in
312     // failure statuses, so we can use one status variable for all calls then
313     // check if it is no longer NO_ERROR.
314     status_t err = NO_ERROR;
315     int32_t rollbackType = int32_t(event->GetInt(1 /*rollback type field id*/, &err));
316     string packageName = string(event->GetString(2 /*package name field id*/, &err));
317 
318     if (err != NO_ERROR) {
319         ALOGE("Failed to parse fields in watchdog rollback occurred log event");
320         return;
321     }
322 
323     vector<int64_t> experimentIds =
324         processWatchdogRollbackOccurred(rollbackType, packageName);
325     vector<uint8_t> experimentIdProto;
326     writeExperimentIdsToProto(experimentIds, &experimentIdProto);
327 
328     event->updateValue(6 /*experiment ids field id*/, experimentIdProto, STORAGE);
329 }
330 
processWatchdogRollbackOccurred(const int32_t rollbackTypeIn,const string & packageNameIn)331 vector<int64_t> StatsLogProcessor::processWatchdogRollbackOccurred(const int32_t rollbackTypeIn,
332                                                                     const string& packageNameIn) {
333     // If the package name is empty, we can't attribute it to any train, so
334     // return early.
335     if (packageNameIn.empty()) {
336       return vector<int64_t>();
337     }
338     bool readTrainInfoSuccess = false;
339     InstallTrainInfo trainInfoOnDisk;
340     // We use the package name of the event as the train name.
341     readTrainInfoSuccess = StorageManager::readTrainInfo(packageNameIn, trainInfoOnDisk);
342 
343     if (!readTrainInfoSuccess) {
344         return vector<int64_t>();
345     }
346 
347     if (trainInfoOnDisk.experimentIds.empty()) {
348         return vector<int64_t>();
349     }
350 
351     int64_t firstId = trainInfoOnDisk.experimentIds[0];
352     auto& ids = trainInfoOnDisk.experimentIds;
353     switch (rollbackTypeIn) {
354       case android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE:
355             if (find(ids.begin(), ids.end(), firstId + 4) == ids.end()) {
356                 ids.push_back(firstId + 4);
357             }
358             StorageManager::writeTrainInfo(trainInfoOnDisk);
359             break;
360       case android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS:
361             if (find(ids.begin(), ids.end(), firstId + 5) == ids.end()) {
362                 ids.push_back(firstId + 5);
363             }
364             StorageManager::writeTrainInfo(trainInfoOnDisk);
365             break;
366     }
367 
368     return trainInfoOnDisk.experimentIds;
369 }
370 
resetConfigs()371 void StatsLogProcessor::resetConfigs() {
372     std::lock_guard<std::mutex> lock(mMetricsMutex);
373     resetConfigsLocked(getElapsedRealtimeNs());
374 }
375 
resetConfigsLocked(const int64_t timestampNs)376 void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs) {
377     std::vector<ConfigKey> configKeys;
378     for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
379         configKeys.push_back(it->first);
380     }
381     resetConfigsLocked(timestampNs, configKeys);
382 }
383 
OnLogEvent(LogEvent * event)384 void StatsLogProcessor::OnLogEvent(LogEvent* event) {
385     OnLogEvent(event, getElapsedRealtimeNs());
386 }
387 
OnLogEvent(LogEvent * event,int64_t elapsedRealtimeNs)388 void StatsLogProcessor::OnLogEvent(LogEvent* event, int64_t elapsedRealtimeNs) {
389     std::lock_guard<std::mutex> lock(mMetricsMutex);
390 
391     // Tell StatsdStats about new event
392     const int64_t eventElapsedTimeNs = event->GetElapsedTimestampNs();
393     int atomId = event->GetTagId();
394     StatsdStats::getInstance().noteAtomLogged(atomId, eventElapsedTimeNs / NS_PER_SEC);
395     if (!event->isValid()) {
396         StatsdStats::getInstance().noteAtomError(atomId);
397         return;
398     }
399 
400     // Hard-coded logic to update train info on disk and fill in any information
401     // this log event may be missing.
402     if (atomId == android::os::statsd::util::BINARY_PUSH_STATE_CHANGED) {
403         onBinaryPushStateChangedEventLocked(event);
404     }
405 
406     // Hard-coded logic to update experiment ids on disk for certain rollback
407     // types and fill the rollback atom with experiment ids
408     if (atomId == android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED) {
409         onWatchdogRollbackOccurredLocked(event);
410     }
411 
412 #ifdef VERY_VERBOSE_PRINTING
413     if (mPrintAllLogs) {
414         ALOGI("%s", event->ToString().c_str());
415     }
416 #endif
417     resetIfConfigTtlExpiredLocked(eventElapsedTimeNs);
418 
419     // Hard-coded logic to update the isolated uid's in the uid-map.
420     // The field numbers need to be currently updated by hand with atoms.proto
421     if (atomId == android::os::statsd::util::ISOLATED_UID_CHANGED) {
422         onIsolatedUidChangedEventLocked(*event);
423     } else {
424         // Map the isolated uid to host uid if necessary.
425         mapIsolatedUidToHostUidIfNecessaryLocked(event);
426     }
427 
428     StateManager::getInstance().onLogEvent(*event);
429 
430     if (mMetricsManagers.empty()) {
431         return;
432     }
433 
434     int64_t curTimeSec = getElapsedRealtimeSec();
435     if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
436         mPullerManager->ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
437         mLastPullerCacheClearTimeSec = curTimeSec;
438     }
439 
440     std::unordered_set<int> uidsWithActiveConfigsChanged;
441     std::unordered_map<int, std::vector<int64_t>> activeConfigsPerUid;
442     // pass the event to metrics managers.
443     for (auto& pair : mMetricsManagers) {
444         int uid = pair.first.GetUid();
445         int64_t configId = pair.first.GetId();
446         bool isPrevActive = pair.second->isActive();
447         pair.second->onLogEvent(*event);
448         bool isCurActive = pair.second->isActive();
449         // Map all active configs by uid.
450         if (isCurActive) {
451             auto activeConfigs = activeConfigsPerUid.find(uid);
452             if (activeConfigs != activeConfigsPerUid.end()) {
453                 activeConfigs->second.push_back(configId);
454             } else {
455                 vector<int64_t> newActiveConfigs;
456                 newActiveConfigs.push_back(configId);
457                 activeConfigsPerUid[uid] = newActiveConfigs;
458             }
459         }
460         // The activation state of this config changed.
461         if (isPrevActive != isCurActive) {
462             VLOG("Active status changed for uid  %d", uid);
463             uidsWithActiveConfigsChanged.insert(uid);
464             StatsdStats::getInstance().noteActiveStatusChanged(pair.first, isCurActive);
465         }
466         flushIfNecessaryLocked(pair.first, *(pair.second));
467     }
468 
469     // Don't use the event timestamp for the guardrail.
470     for (int uid : uidsWithActiveConfigsChanged) {
471         // Send broadcast so that receivers can pull data.
472         auto lastBroadcastTime = mLastActivationBroadcastTimes.find(uid);
473         if (lastBroadcastTime != mLastActivationBroadcastTimes.end()) {
474             if (elapsedRealtimeNs - lastBroadcastTime->second <
475                 StatsdStats::kMinActivationBroadcastPeriodNs) {
476                 StatsdStats::getInstance().noteActivationBroadcastGuardrailHit(uid);
477                 VLOG("StatsD would've sent an activation broadcast but the rate limit stopped us.");
478                 return;
479             }
480         }
481         auto activeConfigs = activeConfigsPerUid.find(uid);
482         if (activeConfigs != activeConfigsPerUid.end()) {
483             if (mSendActivationBroadcast(uid, activeConfigs->second)) {
484                 VLOG("StatsD sent activation notice for uid %d", uid);
485                 mLastActivationBroadcastTimes[uid] = elapsedRealtimeNs;
486             }
487         } else {
488             std::vector<int64_t> emptyActiveConfigs;
489             if (mSendActivationBroadcast(uid, emptyActiveConfigs)) {
490                 VLOG("StatsD sent EMPTY activation notice for uid %d", uid);
491                 mLastActivationBroadcastTimes[uid] = elapsedRealtimeNs;
492             }
493         }
494     }
495 }
496 
GetActiveConfigs(const int uid,vector<int64_t> & outActiveConfigs)497 void StatsLogProcessor::GetActiveConfigs(const int uid, vector<int64_t>& outActiveConfigs) {
498     std::lock_guard<std::mutex> lock(mMetricsMutex);
499     GetActiveConfigsLocked(uid, outActiveConfigs);
500 }
501 
GetActiveConfigsLocked(const int uid,vector<int64_t> & outActiveConfigs)502 void StatsLogProcessor::GetActiveConfigsLocked(const int uid, vector<int64_t>& outActiveConfigs) {
503     outActiveConfigs.clear();
504     for (auto& pair : mMetricsManagers) {
505         if (pair.first.GetUid() == uid && pair.second->isActive()) {
506             outActiveConfigs.push_back(pair.first.GetId());
507         }
508     }
509 }
510 
OnConfigUpdated(const int64_t timestampNs,const ConfigKey & key,const StatsdConfig & config)511 void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
512                                         const StatsdConfig& config) {
513     std::lock_guard<std::mutex> lock(mMetricsMutex);
514     WriteDataToDiskLocked(key, timestampNs, CONFIG_UPDATED, NO_TIME_CONSTRAINTS);
515     OnConfigUpdatedLocked(timestampNs, key, config);
516 }
517 
OnConfigUpdatedLocked(const int64_t timestampNs,const ConfigKey & key,const StatsdConfig & config)518 void StatsLogProcessor::OnConfigUpdatedLocked(
519         const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
520     VLOG("Updated configuration for key %s", key.ToString().c_str());
521     sp<MetricsManager> newMetricsManager =
522             new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap, mPullerManager,
523                                mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
524     if (newMetricsManager->isConfigValid()) {
525         newMetricsManager->init();
526         mUidMap->OnConfigUpdated(key);
527         newMetricsManager->refreshTtl(timestampNs);
528         mMetricsManagers[key] = newMetricsManager;
529         VLOG("StatsdConfig valid");
530     } else {
531         // If there is any error in the config, don't use it.
532         // Remove any existing config with the same key.
533         ALOGE("StatsdConfig NOT valid");
534         mMetricsManagers.erase(key);
535     }
536 }
537 
GetMetricsSize(const ConfigKey & key) const538 size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
539     std::lock_guard<std::mutex> lock(mMetricsMutex);
540     auto it = mMetricsManagers.find(key);
541     if (it == mMetricsManagers.end()) {
542         ALOGW("Config source %s does not exist", key.ToString().c_str());
543         return 0;
544     }
545     return it->second->byteSize();
546 }
547 
dumpStates(int out,bool verbose)548 void StatsLogProcessor::dumpStates(int out, bool verbose) {
549     std::lock_guard<std::mutex> lock(mMetricsMutex);
550     FILE* fout = fdopen(out, "w");
551     if (fout == NULL) {
552         return;
553     }
554     fprintf(fout, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
555     for (auto metricsManager : mMetricsManagers) {
556         metricsManager.second->dumpStates(fout, verbose);
557     }
558 
559     fclose(fout);
560 }
561 
562 /*
563  * onDumpReport dumps serialized ConfigMetricsReportList into proto.
564  */
onDumpReport(const ConfigKey & key,const int64_t dumpTimeStampNs,const bool include_current_partial_bucket,const bool erase_data,const DumpReportReason dumpReportReason,const DumpLatency dumpLatency,ProtoOutputStream * proto)565 void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
566                                      const bool include_current_partial_bucket,
567                                      const bool erase_data,
568                                      const DumpReportReason dumpReportReason,
569                                      const DumpLatency dumpLatency,
570                                      ProtoOutputStream* proto) {
571     std::lock_guard<std::mutex> lock(mMetricsMutex);
572 
573     // Start of ConfigKey.
574     uint64_t configKeyToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
575     proto->write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
576     proto->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
577     proto->end(configKeyToken);
578     // End of ConfigKey.
579 
580     bool keepFile = false;
581     auto it = mMetricsManagers.find(key);
582     if (it != mMetricsManagers.end() && it->second->shouldPersistLocalHistory()) {
583         keepFile = true;
584     }
585 
586     // Then, check stats-data directory to see there's any file containing
587     // ConfigMetricsReport from previous shutdowns to concatenate to reports.
588     StorageManager::appendConfigMetricsReport(
589             key, proto, erase_data && !keepFile /* should remove file after appending it */,
590             dumpReportReason == ADB_DUMP /*if caller is adb*/);
591 
592     if (it != mMetricsManagers.end()) {
593         // This allows another broadcast to be sent within the rate-limit period if we get close to
594         // filling the buffer again soon.
595         mLastBroadcastTimes.erase(key);
596 
597         vector<uint8_t> buffer;
598         onConfigMetricsReportLocked(key, dumpTimeStampNs, include_current_partial_bucket,
599                                     erase_data, dumpReportReason, dumpLatency,
600                                     false /* is this data going to be saved on disk */, &buffer);
601         proto->write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS,
602                      reinterpret_cast<char*>(buffer.data()), buffer.size());
603     } else {
604         ALOGW("Config source %s does not exist", key.ToString().c_str());
605     }
606 }
607 
608 /*
609  * onDumpReport dumps serialized ConfigMetricsReportList into outData.
610  */
onDumpReport(const ConfigKey & key,const int64_t dumpTimeStampNs,const bool include_current_partial_bucket,const bool erase_data,const DumpReportReason dumpReportReason,const DumpLatency dumpLatency,vector<uint8_t> * outData)611 void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
612                                      const bool include_current_partial_bucket,
613                                      const bool erase_data,
614                                      const DumpReportReason dumpReportReason,
615                                      const DumpLatency dumpLatency,
616                                      vector<uint8_t>* outData) {
617     ProtoOutputStream proto;
618     onDumpReport(key, dumpTimeStampNs, include_current_partial_bucket, erase_data,
619                  dumpReportReason, dumpLatency, &proto);
620 
621     if (outData != nullptr) {
622         flushProtoToBuffer(proto, outData);
623         VLOG("output data size %zu", outData->size());
624     }
625 
626     StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
627 }
628 
629 /*
630  * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
631  */
onConfigMetricsReportLocked(const ConfigKey & key,const int64_t dumpTimeStampNs,const bool include_current_partial_bucket,const bool erase_data,const DumpReportReason dumpReportReason,const DumpLatency dumpLatency,const bool dataSavedOnDisk,vector<uint8_t> * buffer)632 void StatsLogProcessor::onConfigMetricsReportLocked(
633         const ConfigKey& key, const int64_t dumpTimeStampNs,
634         const bool include_current_partial_bucket, const bool erase_data,
635         const DumpReportReason dumpReportReason, const DumpLatency dumpLatency,
636         const bool dataSavedOnDisk, vector<uint8_t>* buffer) {
637     // We already checked whether key exists in mMetricsManagers in
638     // WriteDataToDisk.
639     auto it = mMetricsManagers.find(key);
640     if (it == mMetricsManagers.end()) {
641         return;
642     }
643     int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
644     int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
645 
646     std::set<string> str_set;
647 
648     ProtoOutputStream tempProto;
649     // First, fill in ConfigMetricsReport using current data on memory, which
650     // starts from filling in StatsLogReport's.
651     it->second->onDumpReport(dumpTimeStampNs, include_current_partial_bucket, erase_data,
652                              dumpLatency, &str_set, &tempProto);
653 
654     // Fill in UidMap if there is at least one metric to report.
655     // This skips the uid map if it's an empty config.
656     if (it->second->getNumMetrics() > 0) {
657         uint64_t uidMapToken = tempProto.start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
658         mUidMap->appendUidMap(
659                 dumpTimeStampNs, key, it->second->hashStringInReport() ? &str_set : nullptr,
660                 it->second->versionStringsInReport(), it->second->installerInReport(), &tempProto);
661         tempProto.end(uidMapToken);
662     }
663 
664     // Fill in the timestamps.
665     tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
666                     (long long)lastReportTimeNs);
667     tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
668                     (long long)dumpTimeStampNs);
669     tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
670                     (long long)lastReportWallClockNs);
671     tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
672                     (long long)getWallClockNs());
673     // Dump report reason
674     tempProto.write(FIELD_TYPE_INT32 | FIELD_ID_DUMP_REPORT_REASON, dumpReportReason);
675 
676     for (const auto& str : str_set) {
677         tempProto.write(FIELD_TYPE_STRING | FIELD_COUNT_REPEATED | FIELD_ID_STRINGS, str);
678     }
679 
680     flushProtoToBuffer(tempProto, buffer);
681 
682     // save buffer to disk if needed
683     if (erase_data && !dataSavedOnDisk && it->second->shouldPersistLocalHistory()) {
684         VLOG("save history to disk");
685         string file_name = StorageManager::getDataHistoryFileName((long)getWallClockSec(),
686                                                                   key.GetUid(), key.GetId());
687         StorageManager::writeFile(file_name.c_str(), buffer->data(), buffer->size());
688     }
689 }
690 
resetConfigsLocked(const int64_t timestampNs,const std::vector<ConfigKey> & configs)691 void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
692                                            const std::vector<ConfigKey>& configs) {
693     for (const auto& key : configs) {
694         StatsdConfig config;
695         if (StorageManager::readConfigFromDisk(key, &config)) {
696             OnConfigUpdatedLocked(timestampNs, key, config);
697             StatsdStats::getInstance().noteConfigReset(key);
698         } else {
699             ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
700             auto it = mMetricsManagers.find(key);
701             if (it != mMetricsManagers.end()) {
702                 it->second->refreshTtl(timestampNs);
703             }
704         }
705     }
706 }
707 
resetIfConfigTtlExpiredLocked(const int64_t timestampNs)708 void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
709     std::vector<ConfigKey> configKeysTtlExpired;
710     for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
711         if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
712             configKeysTtlExpired.push_back(it->first);
713         }
714     }
715     if (configKeysTtlExpired.size() > 0) {
716         WriteDataToDiskLocked(CONFIG_RESET, NO_TIME_CONSTRAINTS);
717         resetConfigsLocked(timestampNs, configKeysTtlExpired);
718     }
719 }
720 
OnConfigRemoved(const ConfigKey & key)721 void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
722     std::lock_guard<std::mutex> lock(mMetricsMutex);
723     auto it = mMetricsManagers.find(key);
724     if (it != mMetricsManagers.end()) {
725         WriteDataToDiskLocked(key, getElapsedRealtimeNs(), CONFIG_REMOVED,
726                               NO_TIME_CONSTRAINTS);
727         mMetricsManagers.erase(it);
728         mUidMap->OnConfigRemoved(key);
729     }
730     StatsdStats::getInstance().noteConfigRemoved(key);
731 
732     mLastBroadcastTimes.erase(key);
733 
734     int uid = key.GetUid();
735     bool lastConfigForUid = true;
736     for (auto it : mMetricsManagers) {
737         if (it.first.GetUid() == uid) {
738             lastConfigForUid = false;
739             break;
740         }
741     }
742     if (lastConfigForUid) {
743         mLastActivationBroadcastTimes.erase(uid);
744     }
745 
746     if (mMetricsManagers.empty()) {
747         mPullerManager->ForceClearPullerCache();
748     }
749 }
750 
flushIfNecessaryLocked(const ConfigKey & key,MetricsManager & metricsManager)751 void StatsLogProcessor::flushIfNecessaryLocked(const ConfigKey& key,
752                                                MetricsManager& metricsManager) {
753     int64_t elapsedRealtimeNs = getElapsedRealtimeNs();
754     auto lastCheckTime = mLastByteSizeTimes.find(key);
755     if (lastCheckTime != mLastByteSizeTimes.end()) {
756         if (elapsedRealtimeNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
757             return;
758         }
759     }
760 
761     // We suspect that the byteSize() computation is expensive, so we set a rate limit.
762     size_t totalBytes = metricsManager.byteSize();
763     mLastByteSizeTimes[key] = elapsedRealtimeNs;
764     bool requestDump = false;
765     if (totalBytes > StatsdStats::kMaxMetricsBytesPerConfig) {
766         // Too late. We need to start clearing data.
767         metricsManager.dropData(elapsedRealtimeNs);
768         StatsdStats::getInstance().noteDataDropped(key, totalBytes);
769         VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
770     } else if ((totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) ||
771                (mOnDiskDataConfigs.find(key) != mOnDiskDataConfigs.end())) {
772         // Request to send a broadcast if:
773         // 1. in memory data > threshold   OR
774         // 2. config has old data report on disk.
775         requestDump = true;
776     }
777 
778     if (requestDump) {
779         // Send broadcast so that receivers can pull data.
780         auto lastBroadcastTime = mLastBroadcastTimes.find(key);
781         if (lastBroadcastTime != mLastBroadcastTimes.end()) {
782             if (elapsedRealtimeNs - lastBroadcastTime->second <
783                     StatsdStats::kMinBroadcastPeriodNs) {
784                 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
785                 return;
786             }
787         }
788         if (mSendBroadcast(key)) {
789             mOnDiskDataConfigs.erase(key);
790             VLOG("StatsD triggered data fetch for %s", key.ToString().c_str());
791             mLastBroadcastTimes[key] = elapsedRealtimeNs;
792             StatsdStats::getInstance().noteBroadcastSent(key);
793         }
794     }
795 }
796 
WriteDataToDiskLocked(const ConfigKey & key,const int64_t timestampNs,const DumpReportReason dumpReportReason,const DumpLatency dumpLatency)797 void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key,
798                                               const int64_t timestampNs,
799                                               const DumpReportReason dumpReportReason,
800                                               const DumpLatency dumpLatency) {
801     if (mMetricsManagers.find(key) == mMetricsManagers.end() ||
802         !mMetricsManagers.find(key)->second->shouldWriteToDisk()) {
803         return;
804     }
805     vector<uint8_t> buffer;
806     onConfigMetricsReportLocked(key, timestampNs, true /* include_current_partial_bucket*/,
807                                 true /* erase_data */, dumpReportReason, dumpLatency, true,
808                                 &buffer);
809     string file_name =
810             StorageManager::getDataFileName((long)getWallClockSec(), key.GetUid(), key.GetId());
811     StorageManager::writeFile(file_name.c_str(), buffer.data(), buffer.size());
812 
813     // We were able to write the ConfigMetricsReport to disk, so we should trigger collection ASAP.
814     mOnDiskDataConfigs.insert(key);
815 }
816 
SaveActiveConfigsToDisk(int64_t currentTimeNs)817 void StatsLogProcessor::SaveActiveConfigsToDisk(int64_t currentTimeNs) {
818     std::lock_guard<std::mutex> lock(mMetricsMutex);
819     const int64_t timeNs = getElapsedRealtimeNs();
820     // Do not write to disk if we already have in the last few seconds.
821     if (static_cast<unsigned long long> (timeNs) <
822             mLastActiveMetricsWriteNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
823         ALOGI("Statsd skipping writing active metrics to disk. Already wrote data in last %d seconds",
824                 WRITE_DATA_COOL_DOWN_SEC);
825         return;
826     }
827     mLastActiveMetricsWriteNs = timeNs;
828 
829     ProtoOutputStream proto;
830     WriteActiveConfigsToProtoOutputStreamLocked(currentTimeNs, DEVICE_SHUTDOWN, &proto);
831 
832     string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
833     StorageManager::deleteFile(file_name.c_str());
834     android::base::unique_fd fd(
835             open(file_name.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
836     if (fd == -1) {
837         ALOGE("Attempt to write %s but failed", file_name.c_str());
838         return;
839     }
840     proto.flush(fd.get());
841 }
842 
SaveMetadataToDisk(int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs)843 void StatsLogProcessor::SaveMetadataToDisk(int64_t currentWallClockTimeNs,
844                                            int64_t systemElapsedTimeNs) {
845     std::lock_guard<std::mutex> lock(mMetricsMutex);
846     // Do not write to disk if we already have in the last few seconds.
847     if (static_cast<unsigned long long> (systemElapsedTimeNs) <
848             mLastMetadataWriteNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
849         ALOGI("Statsd skipping writing metadata to disk. Already wrote data in last %d seconds",
850                 WRITE_DATA_COOL_DOWN_SEC);
851         return;
852     }
853     mLastMetadataWriteNs = systemElapsedTimeNs;
854 
855     metadata::StatsMetadataList metadataList;
856     WriteMetadataToProtoLocked(
857             currentWallClockTimeNs, systemElapsedTimeNs, &metadataList);
858 
859     string file_name = StringPrintf("%s/metadata", STATS_METADATA_DIR);
860     StorageManager::deleteFile(file_name.c_str());
861 
862     if (metadataList.stats_metadata_size() == 0) {
863         // Skip the write if we have nothing to write.
864         return;
865     }
866 
867     std::string data;
868     metadataList.SerializeToString(&data);
869     StorageManager::writeFile(file_name.c_str(), data.c_str(), data.size());
870 }
871 
WriteMetadataToProto(int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs,metadata::StatsMetadataList * metadataList)872 void StatsLogProcessor::WriteMetadataToProto(int64_t currentWallClockTimeNs,
873                                              int64_t systemElapsedTimeNs,
874                                              metadata::StatsMetadataList* metadataList) {
875     std::lock_guard<std::mutex> lock(mMetricsMutex);
876     WriteMetadataToProtoLocked(currentWallClockTimeNs, systemElapsedTimeNs, metadataList);
877 }
878 
WriteMetadataToProtoLocked(int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs,metadata::StatsMetadataList * metadataList)879 void StatsLogProcessor::WriteMetadataToProtoLocked(int64_t currentWallClockTimeNs,
880                                                    int64_t systemElapsedTimeNs,
881                                                    metadata::StatsMetadataList* metadataList) {
882     for (const auto& pair : mMetricsManagers) {
883         const sp<MetricsManager>& metricsManager = pair.second;
884         metadata::StatsMetadata* statsMetadata = metadataList->add_stats_metadata();
885         bool metadataWritten = metricsManager->writeMetadataToProto(currentWallClockTimeNs,
886                 systemElapsedTimeNs, statsMetadata);
887         if (!metadataWritten) {
888             metadataList->mutable_stats_metadata()->RemoveLast();
889         }
890     }
891 }
892 
LoadMetadataFromDisk(int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs)893 void StatsLogProcessor::LoadMetadataFromDisk(int64_t currentWallClockTimeNs,
894                                              int64_t systemElapsedTimeNs) {
895     std::lock_guard<std::mutex> lock(mMetricsMutex);
896     string file_name = StringPrintf("%s/metadata", STATS_METADATA_DIR);
897     int fd = open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
898     if (-1 == fd) {
899         VLOG("Attempt to read %s but failed", file_name.c_str());
900         StorageManager::deleteFile(file_name.c_str());
901         return;
902     }
903     string content;
904     if (!android::base::ReadFdToString(fd, &content)) {
905         ALOGE("Attempt to read %s but failed", file_name.c_str());
906         close(fd);
907         StorageManager::deleteFile(file_name.c_str());
908         return;
909     }
910 
911     close(fd);
912 
913     metadata::StatsMetadataList statsMetadataList;
914     if (!statsMetadataList.ParseFromString(content)) {
915         ALOGE("Attempt to read %s but failed; failed to metadata", file_name.c_str());
916         StorageManager::deleteFile(file_name.c_str());
917         return;
918     }
919     SetMetadataStateLocked(statsMetadataList, currentWallClockTimeNs, systemElapsedTimeNs);
920     StorageManager::deleteFile(file_name.c_str());
921 }
922 
SetMetadataState(const metadata::StatsMetadataList & statsMetadataList,int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs)923 void StatsLogProcessor::SetMetadataState(const metadata::StatsMetadataList& statsMetadataList,
924                                          int64_t currentWallClockTimeNs,
925                                          int64_t systemElapsedTimeNs) {
926     std::lock_guard<std::mutex> lock(mMetricsMutex);
927     SetMetadataStateLocked(statsMetadataList, currentWallClockTimeNs, systemElapsedTimeNs);
928 }
929 
SetMetadataStateLocked(const metadata::StatsMetadataList & statsMetadataList,int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs)930 void StatsLogProcessor::SetMetadataStateLocked(
931         const metadata::StatsMetadataList& statsMetadataList,
932         int64_t currentWallClockTimeNs,
933         int64_t systemElapsedTimeNs) {
934     for (const metadata::StatsMetadata& metadata : statsMetadataList.stats_metadata()) {
935         ConfigKey key(metadata.config_key().uid(), metadata.config_key().config_id());
936         auto it = mMetricsManagers.find(key);
937         if (it == mMetricsManagers.end()) {
938             ALOGE("No config found for configKey %s", key.ToString().c_str());
939             continue;
940         }
941         VLOG("Setting metadata %s", key.ToString().c_str());
942         it->second->loadMetadata(metadata, currentWallClockTimeNs, systemElapsedTimeNs);
943     }
944     VLOG("Successfully loaded %d metadata.", statsMetadataList.stats_metadata_size());
945 }
946 
WriteActiveConfigsToProtoOutputStream(int64_t currentTimeNs,const DumpReportReason reason,ProtoOutputStream * proto)947 void StatsLogProcessor::WriteActiveConfigsToProtoOutputStream(
948         int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
949     std::lock_guard<std::mutex> lock(mMetricsMutex);
950     WriteActiveConfigsToProtoOutputStreamLocked(currentTimeNs, reason, proto);
951 }
952 
WriteActiveConfigsToProtoOutputStreamLocked(int64_t currentTimeNs,const DumpReportReason reason,ProtoOutputStream * proto)953 void StatsLogProcessor::WriteActiveConfigsToProtoOutputStreamLocked(
954         int64_t currentTimeNs,  const DumpReportReason reason, ProtoOutputStream* proto) {
955     for (const auto& pair : mMetricsManagers) {
956         const sp<MetricsManager>& metricsManager = pair.second;
957         uint64_t configToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
958                                                      FIELD_ID_ACTIVE_CONFIG_LIST_CONFIG);
959         metricsManager->writeActiveConfigToProtoOutputStream(currentTimeNs, reason, proto);
960         proto->end(configToken);
961     }
962 }
LoadActiveConfigsFromDisk()963 void StatsLogProcessor::LoadActiveConfigsFromDisk() {
964     std::lock_guard<std::mutex> lock(mMetricsMutex);
965     string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
966     int fd = open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
967     if (-1 == fd) {
968         VLOG("Attempt to read %s but failed", file_name.c_str());
969         StorageManager::deleteFile(file_name.c_str());
970         return;
971     }
972     string content;
973     if (!android::base::ReadFdToString(fd, &content)) {
974         ALOGE("Attempt to read %s but failed", file_name.c_str());
975         close(fd);
976         StorageManager::deleteFile(file_name.c_str());
977         return;
978     }
979 
980     close(fd);
981 
982     ActiveConfigList activeConfigList;
983     if (!activeConfigList.ParseFromString(content)) {
984         ALOGE("Attempt to read %s but failed; failed to load active configs", file_name.c_str());
985         StorageManager::deleteFile(file_name.c_str());
986         return;
987     }
988     // Passing in mTimeBaseNs only works as long as we only load from disk is when statsd starts.
989     SetConfigsActiveStateLocked(activeConfigList, mTimeBaseNs);
990     StorageManager::deleteFile(file_name.c_str());
991 }
992 
SetConfigsActiveState(const ActiveConfigList & activeConfigList,int64_t currentTimeNs)993 void StatsLogProcessor::SetConfigsActiveState(const ActiveConfigList& activeConfigList,
994                                                     int64_t currentTimeNs) {
995     std::lock_guard<std::mutex> lock(mMetricsMutex);
996     SetConfigsActiveStateLocked(activeConfigList, currentTimeNs);
997 }
998 
SetConfigsActiveStateLocked(const ActiveConfigList & activeConfigList,int64_t currentTimeNs)999 void StatsLogProcessor::SetConfigsActiveStateLocked(const ActiveConfigList& activeConfigList,
1000                                                     int64_t currentTimeNs) {
1001     for (int i = 0; i < activeConfigList.config_size(); i++) {
1002         const auto& config = activeConfigList.config(i);
1003         ConfigKey key(config.uid(), config.id());
1004         auto it = mMetricsManagers.find(key);
1005         if (it == mMetricsManagers.end()) {
1006             ALOGE("No config found for config %s", key.ToString().c_str());
1007             continue;
1008         }
1009         VLOG("Setting active config %s", key.ToString().c_str());
1010         it->second->loadActiveConfig(config, currentTimeNs);
1011     }
1012     VLOG("Successfully loaded %d active configs.", activeConfigList.config_size());
1013 }
1014 
WriteDataToDiskLocked(const DumpReportReason dumpReportReason,const DumpLatency dumpLatency)1015 void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason,
1016                                               const DumpLatency dumpLatency) {
1017     const int64_t timeNs = getElapsedRealtimeNs();
1018     // Do not write to disk if we already have in the last few seconds.
1019     // This is to avoid overwriting files that would have the same name if we
1020     //   write twice in the same second.
1021     if (static_cast<unsigned long long> (timeNs) <
1022             mLastWriteTimeNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
1023         ALOGI("Statsd skipping writing data to disk. Already wrote data in last %d seconds",
1024                 WRITE_DATA_COOL_DOWN_SEC);
1025         return;
1026     }
1027     mLastWriteTimeNs = timeNs;
1028     for (auto& pair : mMetricsManagers) {
1029         WriteDataToDiskLocked(pair.first, timeNs, dumpReportReason, dumpLatency);
1030     }
1031 }
1032 
WriteDataToDisk(const DumpReportReason dumpReportReason,const DumpLatency dumpLatency)1033 void StatsLogProcessor::WriteDataToDisk(const DumpReportReason dumpReportReason,
1034                                         const DumpLatency dumpLatency) {
1035     std::lock_guard<std::mutex> lock(mMetricsMutex);
1036     WriteDataToDiskLocked(dumpReportReason, dumpLatency);
1037 }
1038 
informPullAlarmFired(const int64_t timestampNs)1039 void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
1040     std::lock_guard<std::mutex> lock(mMetricsMutex);
1041     mPullerManager->OnAlarmFired(timestampNs);
1042 }
1043 
getLastReportTimeNs(const ConfigKey & key)1044 int64_t StatsLogProcessor::getLastReportTimeNs(const ConfigKey& key) {
1045     auto it = mMetricsManagers.find(key);
1046     if (it == mMetricsManagers.end()) {
1047         return 0;
1048     } else {
1049         return it->second->getLastReportTimeNs();
1050     }
1051 }
1052 
notifyAppUpgrade(const int64_t & eventTimeNs,const string & apk,const int uid,const int64_t version)1053 void StatsLogProcessor::notifyAppUpgrade(const int64_t& eventTimeNs, const string& apk,
1054                                          const int uid, const int64_t version) {
1055     std::lock_guard<std::mutex> lock(mMetricsMutex);
1056     VLOG("Received app upgrade");
1057     StateManager::getInstance().notifyAppChanged(apk, mUidMap);
1058     for (const auto& it : mMetricsManagers) {
1059         it.second->notifyAppUpgrade(eventTimeNs, apk, uid, version);
1060     }
1061 }
1062 
notifyAppRemoved(const int64_t & eventTimeNs,const string & apk,const int uid)1063 void StatsLogProcessor::notifyAppRemoved(const int64_t& eventTimeNs, const string& apk,
1064                                          const int uid) {
1065     std::lock_guard<std::mutex> lock(mMetricsMutex);
1066     VLOG("Received app removed");
1067     StateManager::getInstance().notifyAppChanged(apk, mUidMap);
1068     for (const auto& it : mMetricsManagers) {
1069         it.second->notifyAppRemoved(eventTimeNs, apk, uid);
1070     }
1071 }
1072 
onUidMapReceived(const int64_t & eventTimeNs)1073 void StatsLogProcessor::onUidMapReceived(const int64_t& eventTimeNs) {
1074     std::lock_guard<std::mutex> lock(mMetricsMutex);
1075     VLOG("Received uid map");
1076     StateManager::getInstance().updateLogSources(mUidMap);
1077     for (const auto& it : mMetricsManagers) {
1078         it.second->onUidMapReceived(eventTimeNs);
1079     }
1080 }
1081 
onStatsdInitCompleted(const int64_t & elapsedTimeNs)1082 void StatsLogProcessor::onStatsdInitCompleted(const int64_t& elapsedTimeNs) {
1083     std::lock_guard<std::mutex> lock(mMetricsMutex);
1084     VLOG("Received boot completed signal");
1085     for (const auto& it : mMetricsManagers) {
1086         it.second->onStatsdInitCompleted(elapsedTimeNs);
1087     }
1088 }
1089 
noteOnDiskData(const ConfigKey & key)1090 void StatsLogProcessor::noteOnDiskData(const ConfigKey& key) {
1091     std::lock_guard<std::mutex> lock(mMetricsMutex);
1092     mOnDiskDataConfigs.insert(key);
1093 }
1094 
1095 }  // namespace statsd
1096 }  // namespace os
1097 }  // namespace android
1098