• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #pragma once
18 
19 #include "anomaly/AlarmMonitor.h"
20 #include "anomaly/AlarmTracker.h"
21 #include "anomaly/AnomalyTracker.h"
22 #include "condition/ConditionTracker.h"
23 #include "config/ConfigKey.h"
24 #include "external/StatsPullerManager.h"
25 #include "src/statsd_config.pb.h"
26 #include "src/statsd_metadata.pb.h"
27 #include "logd/LogEvent.h"
28 #include "matchers/AtomMatchingTracker.h"
29 #include "metrics/MetricProducer.h"
30 #include "packages/UidMap.h"
31 
32 #include <unordered_map>
33 
34 namespace android {
35 namespace os {
36 namespace statsd {
37 
38 // A MetricsManager is responsible for managing metrics from one single config source.
39 class MetricsManager : public virtual android::RefBase, public virtual PullUidProvider {
40 public:
41     MetricsManager(const ConfigKey& configKey, const StatsdConfig& config, const int64_t timeBaseNs,
42                    const int64_t currentTimeNs, const sp<UidMap>& uidMap,
43                    const sp<StatsPullerManager>& pullerManager,
44                    const sp<AlarmMonitor>& anomalyAlarmMonitor,
45                    const sp<AlarmMonitor>& periodicAlarmMonitor);
46 
47     virtual ~MetricsManager();
48 
49     bool updateConfig(const StatsdConfig& config, const int64_t timeBaseNs,
50                       const int64_t currentTimeNs, const sp<AlarmMonitor>& anomalyAlarmMonitor,
51                       const sp<AlarmMonitor>& periodicAlarmMonitor);
52 
53     // Return whether the configuration is valid.
54     bool isConfigValid() const;
55 
56     bool checkLogCredentials(const LogEvent& event);
57 
58     bool eventSanityCheck(const LogEvent& event);
59 
60     void onLogEvent(const LogEvent& event);
61 
62     void onAnomalyAlarmFired(
63         const int64_t& timestampNs,
64         unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& alarmSet);
65 
66     void onPeriodicAlarmFired(
67         const int64_t& timestampNs,
68         unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& alarmSet);
69 
70     void notifyAppUpgrade(const int64_t& eventTimeNs, const string& apk, const int uid,
71                           const int64_t version);
72 
73     void notifyAppRemoved(const int64_t& eventTimeNs, const string& apk, const int uid);
74 
75     void onUidMapReceived(const int64_t& eventTimeNs);
76 
77     void onStatsdInitCompleted(const int64_t& elapsedTimeNs);
78 
79     void init();
80 
81     vector<int32_t> getPullAtomUids(int32_t atomId) override;
82 
shouldWriteToDisk()83     bool shouldWriteToDisk() const {
84         return mNoReportMetricIds.size() != mAllMetricProducers.size();
85     }
86 
shouldPersistLocalHistory()87     bool shouldPersistLocalHistory() const {
88         return mShouldPersistHistory;
89     }
90 
91     void dumpStates(FILE* out, bool verbose);
92 
isInTtl(const int64_t timestampNs)93     inline bool isInTtl(const int64_t timestampNs) const {
94         return mTtlNs <= 0 || timestampNs < mTtlEndNs;
95     };
96 
hashStringInReport()97     inline bool hashStringInReport() const {
98         return mHashStringsInReport;
99     };
100 
versionStringsInReport()101     inline bool versionStringsInReport() const {
102         return mVersionStringsInReport;
103     };
104 
installerInReport()105     inline bool installerInReport() const {
106         return mInstallerInReport;
107     };
108 
refreshTtl(const int64_t currentTimestampNs)109     void refreshTtl(const int64_t currentTimestampNs) {
110         if (mTtlNs > 0) {
111             mTtlEndNs = currentTimestampNs + mTtlNs;
112         }
113     };
114 
115     // Returns the elapsed realtime when this metric manager last reported metrics. If this config
116     // has not yet dumped any reports, this is the time the metricsmanager was initialized.
getLastReportTimeNs()117     inline int64_t getLastReportTimeNs() const {
118         return mLastReportTimeNs;
119     };
120 
getLastReportWallClockNs()121     inline int64_t getLastReportWallClockNs() const {
122         return mLastReportWallClockNs;
123     };
124 
getNumMetrics()125     inline size_t getNumMetrics() const {
126         return mAllMetricProducers.size();
127     }
128 
129     virtual void dropData(const int64_t dropTimeNs);
130 
131     virtual void onDumpReport(const int64_t dumpTimeNs,
132                               const bool include_current_partial_bucket,
133                               const bool erase_data,
134                               const DumpLatency dumpLatency,
135                               std::set<string> *str_set,
136                               android::util::ProtoOutputStream* protoOutput);
137 
138     // Computes the total byte size of all metrics managed by a single config source.
139     // Does not change the state.
140     virtual size_t byteSize();
141 
142     // Returns whether or not this config is active.
143     // The config is active if any metric in the config is active.
isActive()144     inline bool isActive() const {
145         return mIsActive;
146     }
147 
148     void loadActiveConfig(const ActiveConfig& config, int64_t currentTimeNs);
149 
150     void writeActiveConfigToProtoOutputStream(
151             int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto);
152 
153     // Returns true if at least one piece of metadata is written.
154     bool writeMetadataToProto(int64_t currentWallClockTimeNs,
155                               int64_t systemElapsedTimeNs,
156                               metadata::StatsMetadata* statsMetadata);
157 
158     void loadMetadata(const metadata::StatsMetadata& metadata,
159                       int64_t currentWallClockTimeNs,
160                       int64_t systemElapsedTimeNs);
161 private:
162     // For test only.
getTtlEndNs()163     inline int64_t getTtlEndNs() const { return mTtlEndNs; }
164 
165     const ConfigKey mConfigKey;
166 
167     sp<UidMap> mUidMap;
168 
169     bool mConfigValid = false;
170 
171     bool mHashStringsInReport = false;
172     bool mVersionStringsInReport = false;
173     bool mInstallerInReport = false;
174 
175     int64_t mTtlNs;
176     int64_t mTtlEndNs;
177 
178     int64_t mLastReportTimeNs;
179     int64_t mLastReportWallClockNs;
180 
181     sp<StatsPullerManager> mPullerManager;
182 
183     // The uid log sources from StatsdConfig.
184     std::vector<int32_t> mAllowedUid;
185 
186     // The pkg log sources from StatsdConfig.
187     std::vector<std::string> mAllowedPkg;
188 
189     // The combined uid sources (after translating pkg name to uid).
190     // Logs from uids that are not in the list will be ignored to avoid spamming.
191     std::set<int32_t> mAllowedLogSources;
192 
193     // To guard access to mAllowedLogSources
194     mutable std::mutex mAllowedLogSourcesMutex;
195 
196     std::set<int32_t> mWhitelistedAtomIds;
197 
198     // We can pull any atom from these uids.
199     std::set<int32_t> mDefaultPullUids;
200 
201     // Uids that specific atoms can pull from.
202     // This is a map<atom id, set<uids>>
203     std::map<int32_t, std::set<int32_t>> mPullAtomUids;
204 
205     // Packages that specific atoms can be pulled from.
206     std::map<int32_t, std::set<std::string>> mPullAtomPackages;
207 
208     // All uids to pull for this atom. NOTE: Does not include the default uids for memory.
209     std::map<int32_t, std::set<int32_t>> mCombinedPullAtomUids;
210 
211     // Contains the annotations passed in with StatsdConfig.
212     std::list<std::pair<const int64_t, const int32_t>> mAnnotations;
213 
214     bool mShouldPersistHistory;
215 
216     // All event tags that are interesting to my metrics.
217     std::set<int> mTagIds;
218 
219     // We only store the sp of AtomMatchingTracker, MetricProducer, and ConditionTracker in
220     // MetricsManager. There are relationships between them, and the relationships are denoted by
221     // index instead of pointers. The reasons for this are: (1) the relationship between them are
222     // complicated, so storing index instead of pointers reduces the risk that A holds B's sp, and B
223     // holds A's sp. (2) When we evaluate matcher results, or condition results, we can quickly get
224     // the related results from a cache using the index.
225 
226     // Hold all the atom matchers from the config.
227     std::vector<sp<AtomMatchingTracker>> mAllAtomMatchingTrackers;
228 
229     // Hold all the conditions from the config.
230     std::vector<sp<ConditionTracker>> mAllConditionTrackers;
231 
232     // Hold all metrics from the config.
233     std::vector<sp<MetricProducer>> mAllMetricProducers;
234 
235     // Hold all alert trackers.
236     std::vector<sp<AnomalyTracker>> mAllAnomalyTrackers;
237 
238     // Hold all periodic alarm trackers.
239     std::vector<sp<AlarmTracker>> mAllPeriodicAlarmTrackers;
240 
241     // To make updating configs faster, we map the id of a AtomMatchingTracker, MetricProducer, and
242     // ConditionTracker to its index in the corresponding vector.
243 
244     // Maps the id of an atom matching tracker to its index in mAllAtomMatchingTrackers.
245     std::unordered_map<int64_t, int> mAtomMatchingTrackerMap;
246 
247     // Maps the id of a condition tracker to its index in mAllConditionTrackers.
248     std::unordered_map<int64_t, int> mConditionTrackerMap;
249 
250     // Maps the id of a metric producer to its index in mAllMetricProducers.
251     std::unordered_map<int64_t, int> mMetricProducerMap;
252 
253     // To make the log processing more efficient, we want to do as much filtering as possible
254     // before we go into individual trackers and conditions to match.
255 
256     // 1st filter: check if the event tag id is in mTagIds.
257     // 2nd filter: if it is, we parse the event because there is at least one member is interested.
258     //             then pass to all AtomMatchingTrackers (itself also filter events by ids).
259     // 3nd filter: for AtomMatchingTrackers that matched this event, we pass this event to the
260     //             ConditionTrackers and MetricProducers that use this matcher.
261     // 4th filter: for ConditionTrackers that changed value due to this event, we pass
262     //             new conditions to  metrics that use this condition.
263 
264     // The following map is initialized from the statsd_config.
265 
266     // Maps from the index of the AtomMatchingTracker to index of MetricProducer.
267     std::unordered_map<int, std::vector<int>> mTrackerToMetricMap;
268 
269     // Maps from AtomMatchingTracker to ConditionTracker
270     std::unordered_map<int, std::vector<int>> mTrackerToConditionMap;
271 
272     // Maps from ConditionTracker to MetricProducer
273     std::unordered_map<int, std::vector<int>> mConditionToMetricMap;
274 
275     // Maps from life span triggering event to MetricProducers.
276     std::unordered_map<int, std::vector<int>> mActivationAtomTrackerToMetricMap;
277 
278     // Maps deactivation triggering event to MetricProducers.
279     std::unordered_map<int, std::vector<int>> mDeactivationAtomTrackerToMetricMap;
280 
281     // Maps AlertIds to the index of the corresponding AnomalyTracker stored in mAllAnomalyTrackers.
282     // The map is used in LoadMetadata to more efficiently lookup AnomalyTrackers from an AlertId.
283     std::unordered_map<int64_t, int> mAlertTrackerMap;
284 
285     std::vector<int> mMetricIndexesWithActivation;
286 
287     void initAllowedLogSources();
288 
289     void initPullAtomSources();
290 
291     // Only called on config creation/update to initialize log sources from the config.
292     // Calls initAllowedLogSources and initPullAtomSources. Sets mConfigValid to false on error.
293     void createAllLogSourcesFromConfig(const StatsdConfig& config);
294 
295     // Verifies the config meets guardrails and updates statsdStats.
296     // Sets mConfigValid to false on error. Should be called on config creation/update
297     void verifyGuardrailsAndUpdateStatsdStats();
298 
299     // Initializes mIsAlwaysActive and mIsActive.
300     // Should be called on config creation/update.
301     void initializeConfigActiveStatus();
302 
303     // The metrics that don't need to be uploaded or even reported.
304     std::set<int64_t> mNoReportMetricIds;
305 
306    // The config is active if any metric in the config is active.
307     bool mIsActive;
308 
309     // The config is always active if any metric in the config does not have an activation signal.
310     bool mIsAlwaysActive;
311 
312     // Hashes of the States used in this config, keyed by the state id, used in config updates.
313     std::map<int64_t, uint64_t> mStateProtoHashes;
314 
315     FRIEND_TEST(WakelockDurationE2eTest, TestAggregatedPredicateDimensions);
316     FRIEND_TEST(MetricConditionLinkE2eTest, TestMultiplePredicatesAndLinks);
317     FRIEND_TEST(AttributionE2eTest, TestAttributionMatchAndSliceByFirstUid);
318     FRIEND_TEST(AttributionE2eTest, TestAttributionMatchAndSliceByChain);
319     FRIEND_TEST(GaugeMetricE2eTest, TestMultipleFieldsForPushedEvent);
320     FRIEND_TEST(GaugeMetricE2eTest, TestRandomSamplePulledEvents);
321     FRIEND_TEST(GaugeMetricE2eTest, TestRandomSamplePulledEvent_LateAlarm);
322     FRIEND_TEST(GaugeMetricE2eTest, TestRandomSamplePulledEventsWithActivation);
323     FRIEND_TEST(GaugeMetricE2eTest, TestRandomSamplePulledEventsNoCondition);
324     FRIEND_TEST(GaugeMetricE2eTest, TestConditionChangeToTrueSamplePulledEvents);
325 
326     FRIEND_TEST(AnomalyDetectionE2eTest, TestSlicedCountMetric_single_bucket);
327     FRIEND_TEST(AnomalyDetectionE2eTest, TestSlicedCountMetric_multiple_buckets);
328     FRIEND_TEST(AnomalyDetectionE2eTest, TestCountMetric_save_refractory_to_disk_no_data_written);
329     FRIEND_TEST(AnomalyDetectionE2eTest, TestCountMetric_save_refractory_to_disk);
330     FRIEND_TEST(AnomalyDetectionE2eTest, TestCountMetric_load_refractory_from_disk);
331     FRIEND_TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_single_bucket);
332     FRIEND_TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_partial_bucket);
333     FRIEND_TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_multiple_buckets);
334     FRIEND_TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_long_refractory_period);
335 
336     FRIEND_TEST(AlarmE2eTest, TestMultipleAlarms);
337     FRIEND_TEST(ConfigTtlE2eTest, TestCountMetric);
338     FRIEND_TEST(ConfigUpdateE2eAbTest, TestConfigTtl);
339     FRIEND_TEST(MetricActivationE2eTest, TestCountMetric);
340     FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithOneDeactivation);
341     FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithTwoDeactivations);
342     FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithSameDeactivation);
343     FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithTwoMetricsTwoDeactivations);
344 
345     FRIEND_TEST(MetricsManagerTest, TestLogSources);
346     FRIEND_TEST(MetricsManagerTest, TestLogSourcesOnConfigUpdate);
347 
348     FRIEND_TEST(StatsLogProcessorTest, TestActiveConfigMetricDiskWriteRead);
349     FRIEND_TEST(StatsLogProcessorTest, TestActivationOnBoot);
350     FRIEND_TEST(StatsLogProcessorTest, TestActivationOnBootMultipleActivations);
351     FRIEND_TEST(StatsLogProcessorTest,
352             TestActivationOnBootMultipleActivationsDifferentActivationTypes);
353     FRIEND_TEST(StatsLogProcessorTest, TestActivationsPersistAcrossSystemServerRestart);
354 
355     FRIEND_TEST(CountMetricE2eTest, TestInitialConditionChanges);
356     FRIEND_TEST(CountMetricE2eTest, TestSlicedState);
357     FRIEND_TEST(CountMetricE2eTest, TestSlicedStateWithMap);
358     FRIEND_TEST(CountMetricE2eTest, TestMultipleSlicedStates);
359     FRIEND_TEST(CountMetricE2eTest, TestSlicedStateWithPrimaryFields);
360 
361     FRIEND_TEST(DurationMetricE2eTest, TestOneBucket);
362     FRIEND_TEST(DurationMetricE2eTest, TestTwoBuckets);
363     FRIEND_TEST(DurationMetricE2eTest, TestWithActivation);
364     FRIEND_TEST(DurationMetricE2eTest, TestWithCondition);
365     FRIEND_TEST(DurationMetricE2eTest, TestWithSlicedCondition);
366     FRIEND_TEST(DurationMetricE2eTest, TestWithActivationAndSlicedCondition);
367     FRIEND_TEST(DurationMetricE2eTest, TestWithSlicedState);
368     FRIEND_TEST(DurationMetricE2eTest, TestWithConditionAndSlicedState);
369     FRIEND_TEST(DurationMetricE2eTest, TestWithSlicedStateMapped);
370     FRIEND_TEST(DurationMetricE2eTest, TestWithSlicedStatePrimaryFieldsSuperset);
371     FRIEND_TEST(DurationMetricE2eTest, TestWithSlicedStatePrimaryFieldsSubset);
372     FRIEND_TEST(DurationMetricE2eTest, TestUploadThreshold);
373 
374     FRIEND_TEST(ValueMetricE2eTest, TestInitialConditionChanges);
375     FRIEND_TEST(ValueMetricE2eTest, TestPulledEvents);
376     FRIEND_TEST(ValueMetricE2eTest, TestPulledEvents_LateAlarm);
377     FRIEND_TEST(ValueMetricE2eTest, TestPulledEvents_WithActivation);
378     FRIEND_TEST(ValueMetricE2eTest, TestInitWithSlicedState);
379     FRIEND_TEST(ValueMetricE2eTest, TestInitWithSlicedState_WithDimensions);
380     FRIEND_TEST(ValueMetricE2eTest, TestInitWithSlicedState_WithIncorrectDimensions);
381 };
382 
383 }  // namespace statsd
384 }  // namespace os
385 }  // namespace android
386