1 // Copyright (C) 2017 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "StatsLogProcessor.h"
16 
17 #include <android-base/stringprintf.h>
18 #include <gmock/gmock.h>
19 #include <gtest/gtest.h>
20 #include <stdio.h>
21 
22 #include "StatsService.h"
23 #include "config/ConfigKey.h"
24 #include "guardrail/StatsdStats.h"
25 #include "logd/LogEvent.h"
26 #include "packages/UidMap.h"
27 #include "src/stats_log.pb.h"
28 #include "src/statsd_config.pb.h"
29 #include "state/StateManager.h"
30 #include "statslog_statsdtest.h"
31 #include "storage/StorageManager.h"
32 #include "tests/statsd_test_util.h"
33 #include "utils/DbUtils.h"
34 
35 using namespace android;
36 using namespace testing;
37 using ::ndk::SharedRefBase;
38 using std::shared_ptr;
39 
40 namespace android {
41 namespace os {
42 namespace statsd {
43 
44 using android::base::StringPrintf;
45 using android::util::ProtoOutputStream;
46 
47 using ::testing::Expectation;
48 
49 #ifdef __ANDROID__
50 #define STATS_DATA_DIR "/data/misc/stats-data"
51 
52 /**
53  * Mock MetricsManager (ByteSize() is called).
54  */
55 class MockMetricsManager : public MetricsManager {
56 public:
MockMetricsManager(ConfigKey configKey=ConfigKey (1,12345))57     MockMetricsManager(ConfigKey configKey = ConfigKey(1, 12345))
58         : MetricsManager(configKey, StatsdConfig(), 1000, 1000, new UidMap(),
59                          new StatsPullerManager(),
60                          new AlarmMonitor(
61                                  10, [](const shared_ptr<IStatsCompanionService>&, int64_t) {},
__anone3cbb59c0202(const shared_ptr<IStatsCompanionService>&) 62                                  [](const shared_ptr<IStatsCompanionService>&) {}),
63                          new AlarmMonitor(
__anone3cbb59c0302(const shared_ptr<IStatsCompanionService>&, int64_t) 64                                  10, [](const shared_ptr<IStatsCompanionService>&, int64_t) {},
__anone3cbb59c0402(const shared_ptr<IStatsCompanionService>&) 65                                  [](const shared_ptr<IStatsCompanionService>&) {})) {
66     }
67 
68     MOCK_METHOD0(byteSize, size_t());
69 
70     MOCK_METHOD1(dropData, void(const int64_t dropTimeNs));
71 
72     MOCK_METHOD(void, onLogEvent, (const LogEvent& event), (override));
73 
74     MOCK_METHOD(void, onDumpReport,
75                 (const int64_t dumpTimeNs, const int64_t wallClockNs,
76                  const bool include_current_partial_bucket, const bool erase_data,
77                  const DumpLatency dumpLatency, std::set<string>* str_set,
78                  android::util::ProtoOutputStream* protoOutput),
79                 (override));
80 };
81 
TEST(StatsLogProcessorTest,TestRateLimitByteSize)82 TEST(StatsLogProcessorTest, TestRateLimitByteSize) {
83     sp<UidMap> m = new UidMap();
84     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
85     sp<AlarmMonitor> anomalyAlarmMonitor;
86     sp<AlarmMonitor> periodicAlarmMonitor;
87     // Construct the processor with a no-op sendBroadcast function that does nothing.
88     StatsLogProcessor p(
89             m, pullerManager, anomalyAlarmMonitor, periodicAlarmMonitor, 0,
90             [](const ConfigKey& key) { return true; },
91             [](const int&, const vector<int64_t>&) { return true; },
92             [](const ConfigKey&, const string&, const vector<int64_t>&) {},
93             std::make_shared<LogEventFilter>());
94 
95     MockMetricsManager mockMetricsManager;
96 
97     ConfigKey key(100, 12345);
98     // Expect only the first flush to trigger a check for byte size since the last two are
99     // rate-limited.
100     EXPECT_CALL(mockMetricsManager, byteSize()).Times(1);
101     p.flushIfNecessaryLocked(key, mockMetricsManager);
102     p.flushIfNecessaryLocked(key, mockMetricsManager);
103     p.flushIfNecessaryLocked(key, mockMetricsManager);
104 }
105 
TEST(StatsLogProcessorTest,TestRateLimitBroadcast)106 TEST(StatsLogProcessorTest, TestRateLimitBroadcast) {
107     sp<UidMap> m = new UidMap();
108     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
109     sp<AlarmMonitor> anomalyAlarmMonitor;
110     sp<AlarmMonitor> subscriberAlarmMonitor;
111     int broadcastCount = 0;
112     StatsLogProcessor p(
113             m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
114             [&broadcastCount](const ConfigKey& key) {
115                 broadcastCount++;
116                 return true;
117             },
118             [](const int&, const vector<int64_t>&) { return true; },
119             [](const ConfigKey&, const string&, const vector<int64_t>&) {},
120             std::make_shared<LogEventFilter>());
121 
122     MockMetricsManager mockMetricsManager;
123 
124     ConfigKey key(100, 12345);
125     EXPECT_CALL(mockMetricsManager, byteSize())
126             .Times(1)
127             .WillRepeatedly(
128                     ::testing::Return(int(StatsdStats::kDefaultMaxMetricsBytesPerConfig * .95)));
129 
130     // Expect only one broadcast despite always returning a size that should trigger broadcast.
131     p.flushIfNecessaryLocked(key, mockMetricsManager);
132     EXPECT_EQ(1, broadcastCount);
133 
134     // b/73089712
135     // This next call to flush should not trigger a broadcast.
136     // p.mLastByteSizeTimes.clear();  // Force another check for byte size.
137     // p.flushIfNecessaryLocked(2, key, mockMetricsManager);
138     // EXPECT_EQ(1, broadcastCount);
139 }
140 
TEST(StatsLogProcessorTest,TestDropWhenByteSizeTooLarge)141 TEST(StatsLogProcessorTest, TestDropWhenByteSizeTooLarge) {
142     sp<UidMap> m = new UidMap();
143     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
144     sp<AlarmMonitor> anomalyAlarmMonitor;
145     sp<AlarmMonitor> subscriberAlarmMonitor;
146     int broadcastCount = 0;
147     StatsLogProcessor p(
148             m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
149             [&broadcastCount](const ConfigKey& key) {
150                 broadcastCount++;
151                 return true;
152             },
153             [](const int&, const vector<int64_t>&) { return true; },
154             [](const ConfigKey&, const string&, const vector<int64_t>&) {},
155             std::make_shared<LogEventFilter>());
156 
157     MockMetricsManager mockMetricsManager;
158 
159     ConfigKey key(100, 12345);
160     EXPECT_CALL(mockMetricsManager, byteSize())
161             .Times(1)
162             .WillRepeatedly(
163                     ::testing::Return(int(StatsdStats::kDefaultMaxMetricsBytesPerConfig * 1.2)));
164 
165     EXPECT_CALL(mockMetricsManager, dropData(_)).Times(1);
166 
167     // Expect to call the onDumpReport and skip the broadcast.
168     p.flushIfNecessaryLocked(key, mockMetricsManager);
169     EXPECT_EQ(0, broadcastCount);
170 }
171 
MakeConfig(bool includeMetric)172 StatsdConfig MakeConfig(bool includeMetric) {
173     StatsdConfig config;
174 
175     if (includeMetric) {
176         auto appCrashMatcher = CreateProcessCrashAtomMatcher();
177         *config.add_atom_matcher() = appCrashMatcher;
178         auto countMetric = config.add_count_metric();
179         countMetric->set_id(StringToId("AppCrashes"));
180         countMetric->set_what(appCrashMatcher.id());
181         countMetric->set_bucket(FIVE_MINUTES);
182     }
183     return config;
184 }
185 
makeRestrictedConfig(bool includeMetric=false)186 StatsdConfig makeRestrictedConfig(bool includeMetric = false) {
187     StatsdConfig config;
188     config.set_restricted_metrics_delegate_package_name("delegate");
189 
190     if (includeMetric) {
191         auto appCrashMatcher = CreateProcessCrashAtomMatcher();
192         *config.add_atom_matcher() = appCrashMatcher;
193         auto eventMetric = config.add_event_metric();
194         eventMetric->set_id(StringToId("EventAppCrashes"));
195         eventMetric->set_what(appCrashMatcher.id());
196     }
197     return config;
198 }
199 
200 class MockRestrictedMetricsManager : public MetricsManager {
201 public:
MockRestrictedMetricsManager(ConfigKey configKey=ConfigKey (1,12345))202     MockRestrictedMetricsManager(ConfigKey configKey = ConfigKey(1, 12345))
203         : MetricsManager(configKey, makeRestrictedConfig(), 1000, 1000, new UidMap(),
204                          new StatsPullerManager(),
205                          new AlarmMonitor(
206                                  10, [](const shared_ptr<IStatsCompanionService>&, int64_t) {},
__anone3cbb59c0f02(const shared_ptr<IStatsCompanionService>&) 207                                  [](const shared_ptr<IStatsCompanionService>&) {}),
208                          new AlarmMonitor(
__anone3cbb59c1002(const shared_ptr<IStatsCompanionService>&, int64_t) 209                                  10, [](const shared_ptr<IStatsCompanionService>&, int64_t) {},
__anone3cbb59c1102(const shared_ptr<IStatsCompanionService>&) 210                                  [](const shared_ptr<IStatsCompanionService>&) {})) {
211     }
212 
213     MOCK_METHOD(void, onLogEvent, (const LogEvent& event), (override));
214     MOCK_METHOD(void, onDumpReport,
215                 (const int64_t dumpTimeNs, const int64_t wallClockNs,
216                  const bool include_current_partial_bucket, const bool erase_data,
217                  const DumpLatency dumpLatency, std::set<string>* str_set,
218                  android::util::ProtoOutputStream* protoOutput),
219                 (override));
220     MOCK_METHOD(size_t, byteSize, (), (override));
221     MOCK_METHOD(void, flushRestrictedData, (), (override));
222 };
223 
TEST(StatsLogProcessorTest,TestUidMapHasSnapshot)224 TEST(StatsLogProcessorTest, TestUidMapHasSnapshot) {
225     ConfigKey key(3, 4);
226     StatsdConfig config = MakeConfig(true);
227 
228     sp<UidMap> m = new UidMap();
229     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
230     UidData uidData;
231     *uidData.add_app_info() = createApplicationInfo(/*uid*/ 1, /*version*/ 1, "v1", "p1");
232     *uidData.add_app_info() = createApplicationInfo(/*uid*/ 2, /*version*/ 2, "v2", "p2");
233     m->updateMap(1, uidData);
234     sp<AlarmMonitor> anomalyAlarmMonitor;
235     sp<AlarmMonitor> subscriberAlarmMonitor;
236     int broadcastCount = 0;
237     std::shared_ptr<MockLogEventFilter> mockLogEventFilter = std::make_shared<MockLogEventFilter>();
238     EXPECT_CALL(*mockLogEventFilter, setAtomIds(StatsLogProcessor::getDefaultAtomIdSet(), _))
239             .Times(1);
240     StatsLogProcessor p(
241             m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
242             [&broadcastCount](const ConfigKey& key) {
243                 broadcastCount++;
244                 return true;
245             },
246             [](const int&, const vector<int64_t>&) { return true; },
247             [](const ConfigKey&, const string&, const vector<int64_t>&) {}, mockLogEventFilter);
248 
249     const LogEventFilter::AtomIdSet atomIdsList = CreateAtomIdSetFromConfig(config);
250     EXPECT_CALL(*mockLogEventFilter, setAtomIds(atomIdsList, &p)).Times(1);
251 
252     p.OnConfigUpdated(0, key, config);
253 
254     // Expect to get no metrics, but snapshot specified above in uidmap.
255     vector<uint8_t> bytes;
256     p.onDumpReport(key, 1, false, true, ADB_DUMP, FAST, &bytes);
257 
258     ConfigMetricsReportList output;
259     output.ParseFromArray(bytes.data(), bytes.size());
260     EXPECT_TRUE(output.reports_size() > 0);
261     auto uidmap = output.reports(0).uid_map();
262     EXPECT_TRUE(uidmap.snapshots_size() > 0);
263     ASSERT_EQ(2, uidmap.snapshots(0).package_info_size());
264 }
265 
TEST(StatsLogProcessorTest,TestEmptyConfigHasNoUidMap)266 TEST(StatsLogProcessorTest, TestEmptyConfigHasNoUidMap) {
267     // Setup simple config key corresponding to empty config.
268     ConfigKey key(3, 4);
269     StatsdConfig config = MakeConfig(false);
270 
271     sp<UidMap> m = new UidMap();
272     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
273     UidData uidData;
274     *uidData.add_app_info() = createApplicationInfo(/*uid*/ 1, /*version*/ 1, "v1", "p1");
275     *uidData.add_app_info() = createApplicationInfo(/*uid*/ 2, /*version*/ 2, "v2", "p2");
276     m->updateMap(1, uidData);
277     sp<AlarmMonitor> anomalyAlarmMonitor;
278     sp<AlarmMonitor> subscriberAlarmMonitor;
279     int broadcastCount = 0;
280     std::shared_ptr<MockLogEventFilter> mockLogEventFilter = std::make_shared<MockLogEventFilter>();
281     EXPECT_CALL(*mockLogEventFilter, setAtomIds(StatsLogProcessor::getDefaultAtomIdSet(), _))
282             .Times(1);
283     StatsLogProcessor p(
284             m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
285             [&broadcastCount](const ConfigKey& key) {
286                 broadcastCount++;
287                 return true;
288             },
289             [](const int&, const vector<int64_t>&) { return true; },
290             [](const ConfigKey&, const string&, const vector<int64_t>&) {}, mockLogEventFilter);
291 
292     const LogEventFilter::AtomIdSet atomIdsList = CreateAtomIdSetFromConfig(config);
293     EXPECT_CALL(*mockLogEventFilter, setAtomIds(atomIdsList, &p)).Times(1);
294 
295     p.OnConfigUpdated(0, key, config);
296 
297     // Expect to get no metrics, but snapshot specified above in uidmap.
298     vector<uint8_t> bytes;
299     p.onDumpReport(key, 1, false, true, ADB_DUMP, FAST, &bytes);
300 
301     ConfigMetricsReportList output;
302     output.ParseFromArray(bytes.data(), bytes.size());
303     EXPECT_TRUE(output.reports_size() > 0);
304     EXPECT_FALSE(output.reports(0).has_uid_map());
305 }
306 
TEST(StatsLogProcessorTest,TestReportIncludesSubConfig)307 TEST(StatsLogProcessorTest, TestReportIncludesSubConfig) {
308     // Setup simple config key corresponding to empty config.
309     ConfigKey key(3, 4);
310     StatsdConfig config;
311     auto annotation = config.add_annotation();
312     annotation->set_field_int64(1);
313     annotation->set_field_int32(2);
314 
315     sp<UidMap> m = new UidMap();
316     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
317     sp<AlarmMonitor> anomalyAlarmMonitor;
318     sp<AlarmMonitor> subscriberAlarmMonitor;
319     int broadcastCount = 0;
320     std::shared_ptr<MockLogEventFilter> mockLogEventFilter = std::make_shared<MockLogEventFilter>();
321     EXPECT_CALL(*mockLogEventFilter, setAtomIds(StatsLogProcessor::getDefaultAtomIdSet(), _))
322             .Times(1);
323     StatsLogProcessor p(
324             m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
325             [&broadcastCount](const ConfigKey& key) {
326                 broadcastCount++;
327                 return true;
328             },
329             [](const int&, const vector<int64_t>&) { return true; },
330             [](const ConfigKey&, const string&, const vector<int64_t>&) {}, mockLogEventFilter);
331 
332     const LogEventFilter::AtomIdSet atomIdsList = CreateAtomIdSetFromConfig(config);
333     EXPECT_CALL(*mockLogEventFilter, setAtomIds(atomIdsList, &p)).Times(1);
334 
335     p.OnConfigUpdated(1, key, config);
336 
337     // Expect to get no metrics, but snapshot specified above in uidmap.
338     vector<uint8_t> bytes;
339     p.onDumpReport(key, 1, false, true, ADB_DUMP, FAST, &bytes);
340 
341     ConfigMetricsReportList output;
342     output.ParseFromArray(bytes.data(), bytes.size());
343     EXPECT_TRUE(output.reports_size() > 0);
344     auto report = output.reports(0);
345     ASSERT_EQ(1, report.annotation_size());
346     EXPECT_EQ(1, report.annotation(0).field_int64());
347     EXPECT_EQ(2, report.annotation(0).field_int32());
348 }
349 
TEST(StatsLogProcessorTest,TestOnDumpReportEraseData)350 TEST(StatsLogProcessorTest, TestOnDumpReportEraseData) {
351     // Setup a simple config.
352     StatsdConfig config;
353     auto wakelockAcquireMatcher = CreateAcquireWakelockAtomMatcher();
354     *config.add_atom_matcher() = wakelockAcquireMatcher;
355 
356     auto countMetric = config.add_count_metric();
357     countMetric->set_id(123456);
358     countMetric->set_what(wakelockAcquireMatcher.id());
359     countMetric->set_bucket(FIVE_MINUTES);
360 
361     ConfigKey cfgKey;
362     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(1, 1, config, cfgKey);
363 
364     std::vector<int> attributionUids = {111};
365     std::vector<string> attributionTags = {"App1"};
366     std::unique_ptr<LogEvent> event =
367             CreateAcquireWakelockEvent(2 /*timestamp*/, attributionUids, attributionTags, "wl1");
368     processor->OnLogEvent(event.get());
369 
370     vector<uint8_t> bytes;
371     ConfigMetricsReportList output;
372 
373     // Dump report WITHOUT erasing data.
374     processor->onDumpReport(cfgKey, 3, true, false /* Do NOT erase data. */, ADB_DUMP, FAST,
375                             &bytes);
376     output.ParseFromArray(bytes.data(), bytes.size());
377     ASSERT_EQ(output.reports_size(), 1);
378     ASSERT_EQ(output.reports(0).metrics_size(), 1);
379     ASSERT_EQ(output.reports(0).metrics(0).count_metrics().data_size(), 1);
380 
381     // Dump report WITH erasing data. There should be data since we didn't previously erase it.
382     processor->onDumpReport(cfgKey, 4, true, true /* DO erase data. */, ADB_DUMP, FAST, &bytes);
383     output.ParseFromArray(bytes.data(), bytes.size());
384     ASSERT_EQ(output.reports_size(), 1);
385     ASSERT_EQ(output.reports(0).metrics_size(), 1);
386     ASSERT_EQ(output.reports(0).metrics(0).count_metrics().data_size(), 1);
387 
388     // Dump report again. There should be no data since we erased it.
389     processor->onDumpReport(cfgKey, 5, true, true /* DO erase data. */, ADB_DUMP, FAST, &bytes);
390     output.ParseFromArray(bytes.data(), bytes.size());
391     // We don't care whether statsd has a report, as long as it has no count metrics in it.
392     bool noData = output.reports_size() == 0 || output.reports(0).metrics_size() == 0 ||
393                   output.reports(0).metrics(0).count_metrics().data_size() == 0;
394     EXPECT_TRUE(noData);
395 }
396 
TEST(StatsLogProcessorTest,TestPullUidProviderSetOnConfigUpdate)397 TEST(StatsLogProcessorTest, TestPullUidProviderSetOnConfigUpdate) {
398     // Setup simple config key corresponding to empty config.
399     ConfigKey key(3, 4);
400     StatsdConfig config = MakeConfig(false);
401 
402     sp<UidMap> m = new UidMap();
403     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
404     sp<AlarmMonitor> anomalyAlarmMonitor;
405     sp<AlarmMonitor> subscriberAlarmMonitor;
406     std::shared_ptr<MockLogEventFilter> mockLogEventFilter = std::make_shared<MockLogEventFilter>();
407     EXPECT_CALL(*mockLogEventFilter, setAtomIds(StatsLogProcessor::getDefaultAtomIdSet(), _))
408             .Times(1);
409     StatsLogProcessor p(
410             m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
411             [](const ConfigKey& key) { return true; },
412             [](const int&, const vector<int64_t>&) { return true; },
413             [](const ConfigKey&, const string&, const vector<int64_t>&) {}, mockLogEventFilter);
414 
415     const LogEventFilter::AtomIdSet atomIdsList = CreateAtomIdSetFromConfig(config);
416     EXPECT_CALL(*mockLogEventFilter, setAtomIds(atomIdsList, &p)).Times(3);
417 
418     p.OnConfigUpdated(0, key, config);
419     EXPECT_NE(pullerManager->mPullUidProviders.find(key), pullerManager->mPullUidProviders.end());
420 
421     config.add_default_pull_packages("AID_STATSD");
422     p.OnConfigUpdated(5, key, config);
423     EXPECT_NE(pullerManager->mPullUidProviders.find(key), pullerManager->mPullUidProviders.end());
424 
425     p.OnConfigRemoved(key);
426     EXPECT_EQ(pullerManager->mPullUidProviders.find(key), pullerManager->mPullUidProviders.end());
427 }
428 
TEST(StatsLogProcessorTest,InvalidConfigRemoved)429 TEST(StatsLogProcessorTest, InvalidConfigRemoved) {
430     ConfigKey key(3, 4);
431     StatsdConfig config = MakeConfig(true);
432 
433     sp<UidMap> m = new UidMap();
434     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
435     UidData uidData;
436     *uidData.add_app_info() = createApplicationInfo(/*uid*/ 1, /*version*/ 1, "v1", "p1");
437     *uidData.add_app_info() = createApplicationInfo(/*uid*/ 2, /*version*/ 2, "v2", "p2");
438     m->updateMap(1, uidData);
439     sp<AlarmMonitor> anomalyAlarmMonitor;
440     sp<AlarmMonitor> subscriberAlarmMonitor;
441     std::shared_ptr<MockLogEventFilter> mockLogEventFilter = std::make_shared<MockLogEventFilter>();
442     EXPECT_CALL(*mockLogEventFilter, setAtomIds(StatsLogProcessor::getDefaultAtomIdSet(), _))
443             .Times(1);
444     StatsLogProcessor p(
445             m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
446             [](const ConfigKey& key) { return true; },
447             [](const int&, const vector<int64_t>&) { return true; },
448             [](const ConfigKey&, const string&, const vector<int64_t>&) {}, mockLogEventFilter);
449 
450     EXPECT_CALL(*mockLogEventFilter, setAtomIds(CreateAtomIdSetDefault(), &p)).Times(1);
451     // atom used by matcher defined in MakeConfig() API
452     Expectation exp =
453             EXPECT_CALL(*mockLogEventFilter, setAtomIds(CreateAtomIdSetFromConfig(config), &p))
454                     .Times(1);
455     EXPECT_CALL(*mockLogEventFilter, setAtomIds(CreateAtomIdSetDefault(), &p)).Times(1).After(exp);
456 
457     // Remove the config mConfigStats so that the Icebox starts at 0 configs.
458     p.OnConfigRemoved(key);
459     StatsdStats::getInstance().reset();
460     p.OnConfigUpdated(0, key, config);
461     EXPECT_EQ(1, p.mMetricsManagers.size());
462     EXPECT_NE(p.mMetricsManagers.find(key), p.mMetricsManagers.end());
463     // Cannot assert the size of mConfigStats since it is static and does not get cleared on reset.
464     EXPECT_NE(StatsdStats::getInstance().mConfigStats.end(),
465               StatsdStats::getInstance().mConfigStats.find(key));
466     EXPECT_EQ(0, StatsdStats::getInstance().mIceBox.size());
467 
468     StatsdConfig invalidConfig = MakeConfig(true);
469     auto invalidCountMetric = invalidConfig.add_count_metric();
470     invalidCountMetric->set_what(0);
471     p.OnConfigUpdated(0, key, invalidConfig);
472     EXPECT_EQ(0, p.mMetricsManagers.size());
473     // The current configs should not contain the invalid config.
474     EXPECT_EQ(StatsdStats::getInstance().mConfigStats.end(),
475               StatsdStats::getInstance().mConfigStats.find(key));
476     // Both "config" and "invalidConfig" should be in the icebox.
477     EXPECT_EQ(2, StatsdStats::getInstance().mIceBox.size());
478     string suffix = StringPrintf("%d_%lld", key.GetUid(), (long long)key.GetId());
479     StorageManager::deleteSuffixedFiles(STATS_DATA_DIR, suffix.c_str());
480 }
481 
TEST(StatsLogProcessorTest,TestActiveConfigMetricDiskWriteRead)482 TEST(StatsLogProcessorTest, TestActiveConfigMetricDiskWriteRead) {
483     int uid = 1111;
484 
485     // Setup a simple config, no activation
486     StatsdConfig config1;
487     int64_t cfgId1 = 12341;
488     config1.set_id(cfgId1);
489     auto wakelockAcquireMatcher = CreateAcquireWakelockAtomMatcher();
490     *config1.add_atom_matcher() = wakelockAcquireMatcher;
491 
492     long metricId1 = 1234561;
493     long metricId2 = 1234562;
494     auto countMetric1 = config1.add_count_metric();
495     countMetric1->set_id(metricId1);
496     countMetric1->set_what(wakelockAcquireMatcher.id());
497     countMetric1->set_bucket(FIVE_MINUTES);
498 
499     auto countMetric2 = config1.add_count_metric();
500     countMetric2->set_id(metricId2);
501     countMetric2->set_what(wakelockAcquireMatcher.id());
502     countMetric2->set_bucket(FIVE_MINUTES);
503 
504     ConfigKey cfgKey1(uid, cfgId1);
505 
506     // Add another config, with two metrics, one with activation
507     StatsdConfig config2;
508     int64_t cfgId2 = 12342;
509     config2.set_id(cfgId2);
510     *config2.add_atom_matcher() = wakelockAcquireMatcher;
511 
512     long metricId3 = 1234561;
513     long metricId4 = 1234562;
514 
515     auto countMetric3 = config2.add_count_metric();
516     countMetric3->set_id(metricId3);
517     countMetric3->set_what(wakelockAcquireMatcher.id());
518     countMetric3->set_bucket(FIVE_MINUTES);
519 
520     auto countMetric4 = config2.add_count_metric();
521     countMetric4->set_id(metricId4);
522     countMetric4->set_what(wakelockAcquireMatcher.id());
523     countMetric4->set_bucket(FIVE_MINUTES);
524 
525     auto metric3Activation = config2.add_metric_activation();
526     metric3Activation->set_metric_id(metricId3);
527     metric3Activation->set_activation_type(ACTIVATE_IMMEDIATELY);
528     auto metric3ActivationTrigger = metric3Activation->add_event_activation();
529     metric3ActivationTrigger->set_atom_matcher_id(wakelockAcquireMatcher.id());
530     metric3ActivationTrigger->set_ttl_seconds(100);
531 
532     ConfigKey cfgKey2(uid, cfgId2);
533 
534     // Add another config, with two metrics, both with activations
535     StatsdConfig config3;
536     int64_t cfgId3 = 12343;
537     config3.set_id(cfgId3);
538     *config3.add_atom_matcher() = wakelockAcquireMatcher;
539 
540     long metricId5 = 1234565;
541     long metricId6 = 1234566;
542     auto countMetric5 = config3.add_count_metric();
543     countMetric5->set_id(metricId5);
544     countMetric5->set_what(wakelockAcquireMatcher.id());
545     countMetric5->set_bucket(FIVE_MINUTES);
546 
547     auto countMetric6 = config3.add_count_metric();
548     countMetric6->set_id(metricId6);
549     countMetric6->set_what(wakelockAcquireMatcher.id());
550     countMetric6->set_bucket(FIVE_MINUTES);
551 
552     auto metric5Activation = config3.add_metric_activation();
553     metric5Activation->set_metric_id(metricId5);
554     metric5Activation->set_activation_type(ACTIVATE_IMMEDIATELY);
555     auto metric5ActivationTrigger = metric5Activation->add_event_activation();
556     metric5ActivationTrigger->set_atom_matcher_id(wakelockAcquireMatcher.id());
557     metric5ActivationTrigger->set_ttl_seconds(100);
558 
559     auto metric6Activation = config3.add_metric_activation();
560     metric6Activation->set_metric_id(metricId6);
561     metric6Activation->set_activation_type(ACTIVATE_IMMEDIATELY);
562     auto metric6ActivationTrigger = metric6Activation->add_event_activation();
563     metric6ActivationTrigger->set_atom_matcher_id(wakelockAcquireMatcher.id());
564     metric6ActivationTrigger->set_ttl_seconds(200);
565 
566     ConfigKey cfgKey3(uid, cfgId3);
567 
568     sp<UidMap> m = new UidMap();
569     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
570     sp<AlarmMonitor> anomalyAlarmMonitor;
571     sp<AlarmMonitor> subscriberAlarmMonitor;
572     vector<int64_t> activeConfigsBroadcast;
573 
574     long timeBase1 = 1;
575     int broadcastCount = 0;
576     std::shared_ptr<MockLogEventFilter> mockLogEventFilter = std::make_shared<MockLogEventFilter>();
577     EXPECT_CALL(*mockLogEventFilter, setAtomIds(StatsLogProcessor::getDefaultAtomIdSet(), _))
578             .Times(1);
579     StatsLogProcessor processor(
580             m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, timeBase1,
581             [](const ConfigKey& key) { return true; },
582             [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
583                                                              const vector<int64_t>& activeConfigs) {
584                 broadcastCount++;
585                 EXPECT_EQ(broadcastUid, uid);
586                 activeConfigsBroadcast.clear();
587                 activeConfigsBroadcast.insert(activeConfigsBroadcast.end(), activeConfigs.begin(),
588                                               activeConfigs.end());
589                 return true;
590             },
591             [](const ConfigKey&, const string&, const vector<int64_t>&) {}, mockLogEventFilter);
592 
593     // config1,config2,config3 use the same atom
594     const LogEventFilter::AtomIdSet atomIdsList = CreateAtomIdSetFromConfig(config1);
595     EXPECT_CALL(*mockLogEventFilter, setAtomIds(atomIdsList, &processor)).Times(3);
596 
597     processor.OnConfigUpdated(1, cfgKey1, config1);
598     processor.OnConfigUpdated(2, cfgKey2, config2);
599     processor.OnConfigUpdated(3, cfgKey3, config3);
600 
601     ASSERT_EQ(3, processor.mMetricsManagers.size());
602 
603     // Expect the first config and both metrics in it to be active.
604     auto it = processor.mMetricsManagers.find(cfgKey1);
605     EXPECT_TRUE(it != processor.mMetricsManagers.end());
606     auto& metricsManager1 = it->second;
607     EXPECT_TRUE(metricsManager1->isActive());
608 
609     auto metricIt = metricsManager1->mAllMetricProducers.begin();
610     for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
611         if ((*metricIt)->getMetricId() == metricId1) {
612             break;
613         }
614     }
615     EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
616     auto& metricProducer1 = *metricIt;
617     EXPECT_TRUE(metricProducer1->isActive());
618 
619     metricIt = metricsManager1->mAllMetricProducers.begin();
620     for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
621         if ((*metricIt)->getMetricId() == metricId2) {
622             break;
623         }
624     }
625     EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
626     auto& metricProducer2 = *metricIt;
627     EXPECT_TRUE(metricProducer2->isActive());
628 
629     // Expect config 2 to be active. Metric 3 shouldn't be active, metric 4 should be active.
630     it = processor.mMetricsManagers.find(cfgKey2);
631     EXPECT_TRUE(it != processor.mMetricsManagers.end());
632     auto& metricsManager2 = it->second;
633     EXPECT_TRUE(metricsManager2->isActive());
634 
635     metricIt = metricsManager2->mAllMetricProducers.begin();
636     for (; metricIt != metricsManager2->mAllMetricProducers.end(); metricIt++) {
637         if ((*metricIt)->getMetricId() == metricId3) {
638             break;
639         }
640     }
641     EXPECT_TRUE(metricIt != metricsManager2->mAllMetricProducers.end());
642     auto& metricProducer3 = *metricIt;
643     EXPECT_FALSE(metricProducer3->isActive());
644 
645     metricIt = metricsManager2->mAllMetricProducers.begin();
646     for (; metricIt != metricsManager2->mAllMetricProducers.end(); metricIt++) {
647         if ((*metricIt)->getMetricId() == metricId4) {
648             break;
649         }
650     }
651     EXPECT_TRUE(metricIt != metricsManager2->mAllMetricProducers.end());
652     auto& metricProducer4 = *metricIt;
653     EXPECT_TRUE(metricProducer4->isActive());
654 
655     // Expect the third config and both metrics in it to be inactive.
656     it = processor.mMetricsManagers.find(cfgKey3);
657     EXPECT_TRUE(it != processor.mMetricsManagers.end());
658     auto& metricsManager3 = it->second;
659     EXPECT_FALSE(metricsManager3->isActive());
660 
661     metricIt = metricsManager3->mAllMetricProducers.begin();
662     for (; metricIt != metricsManager2->mAllMetricProducers.end(); metricIt++) {
663         if ((*metricIt)->getMetricId() == metricId5) {
664             break;
665         }
666     }
667     EXPECT_TRUE(metricIt != metricsManager3->mAllMetricProducers.end());
668     auto& metricProducer5 = *metricIt;
669     EXPECT_FALSE(metricProducer5->isActive());
670 
671     metricIt = metricsManager3->mAllMetricProducers.begin();
672     for (; metricIt != metricsManager3->mAllMetricProducers.end(); metricIt++) {
673         if ((*metricIt)->getMetricId() == metricId6) {
674             break;
675         }
676     }
677     EXPECT_TRUE(metricIt != metricsManager3->mAllMetricProducers.end());
678     auto& metricProducer6 = *metricIt;
679     EXPECT_FALSE(metricProducer6->isActive());
680 
681     // No broadcast for active configs should have happened yet.
682     EXPECT_EQ(broadcastCount, 0);
683 
684     // Activate all 3 metrics that were not active.
685     std::vector<int> attributionUids = {111};
686     std::vector<string> attributionTags = {"App1"};
687     std::unique_ptr<LogEvent> event =
688             CreateAcquireWakelockEvent(timeBase1 + 100, attributionUids, attributionTags, "wl1");
689     processor.OnLogEvent(event.get());
690 
691     // Assert that all 3 configs are active.
692     EXPECT_TRUE(metricsManager1->isActive());
693     EXPECT_TRUE(metricsManager2->isActive());
694     EXPECT_TRUE(metricsManager3->isActive());
695 
696     // A broadcast should have happened, and all 3 configs should be active in the broadcast.
697     EXPECT_EQ(broadcastCount, 1);
698     ASSERT_EQ(activeConfigsBroadcast.size(), 3);
699     EXPECT_TRUE(std::find(activeConfigsBroadcast.begin(), activeConfigsBroadcast.end(), cfgId1) !=
700                 activeConfigsBroadcast.end());
701     EXPECT_TRUE(std::find(activeConfigsBroadcast.begin(), activeConfigsBroadcast.end(), cfgId2) !=
702                 activeConfigsBroadcast.end());
703     EXPECT_TRUE(std::find(activeConfigsBroadcast.begin(), activeConfigsBroadcast.end(), cfgId3) !=
704                 activeConfigsBroadcast.end());
705 
706     // When we shut down, metrics 3 & 5 have 100ns remaining, metric 6 has 100s + 100ns.
707     int64_t shutDownTime = timeBase1 + 100 * NS_PER_SEC;
708     processor.SaveActiveConfigsToDisk(shutDownTime);
709     const int64_t ttl3 = event->GetElapsedTimestampNs() +
710                          metric3ActivationTrigger->ttl_seconds() * NS_PER_SEC - shutDownTime;
711     const int64_t ttl5 = event->GetElapsedTimestampNs() +
712                          metric5ActivationTrigger->ttl_seconds() * NS_PER_SEC - shutDownTime;
713     const int64_t ttl6 = event->GetElapsedTimestampNs() +
714                          metric6ActivationTrigger->ttl_seconds() * NS_PER_SEC - shutDownTime;
715 
716     // Create a second StatsLogProcessor and push the same 3 configs.
717     long timeBase2 = 1000;
718     sp<StatsLogProcessor> processor2 =
719             CreateStatsLogProcessor(timeBase2, timeBase2, config1, cfgKey1);
720     processor2->OnConfigUpdated(timeBase2, cfgKey2, config2);
721     processor2->OnConfigUpdated(timeBase2, cfgKey3, config3);
722 
723     ASSERT_EQ(3, processor2->mMetricsManagers.size());
724 
725     // First config and both metrics are active.
726     it = processor2->mMetricsManagers.find(cfgKey1);
727     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
728     auto& metricsManager1001 = it->second;
729     EXPECT_TRUE(metricsManager1001->isActive());
730 
731     metricIt = metricsManager1001->mAllMetricProducers.begin();
732     for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
733         if ((*metricIt)->getMetricId() == metricId1) {
734             break;
735         }
736     }
737     EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
738     auto& metricProducer1001 = *metricIt;
739     EXPECT_TRUE(metricProducer1001->isActive());
740 
741     metricIt = metricsManager1001->mAllMetricProducers.begin();
742     for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
743         if ((*metricIt)->getMetricId() == metricId2) {
744             break;
745         }
746     }
747     EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
748     auto& metricProducer1002 = *metricIt;
749     EXPECT_TRUE(metricProducer1002->isActive());
750 
751     // Second config is active. Metric 3 is inactive, metric 4 is active.
752     it = processor2->mMetricsManagers.find(cfgKey2);
753     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
754     auto& metricsManager1002 = it->second;
755     EXPECT_TRUE(metricsManager1002->isActive());
756 
757     metricIt = metricsManager1002->mAllMetricProducers.begin();
758     for (; metricIt != metricsManager1002->mAllMetricProducers.end(); metricIt++) {
759         if ((*metricIt)->getMetricId() == metricId3) {
760             break;
761         }
762     }
763     EXPECT_TRUE(metricIt != metricsManager1002->mAllMetricProducers.end());
764     auto& metricProducer1003 = *metricIt;
765     EXPECT_FALSE(metricProducer1003->isActive());
766 
767     metricIt = metricsManager1002->mAllMetricProducers.begin();
768     for (; metricIt != metricsManager1002->mAllMetricProducers.end(); metricIt++) {
769         if ((*metricIt)->getMetricId() == metricId4) {
770             break;
771         }
772     }
773     EXPECT_TRUE(metricIt != metricsManager1002->mAllMetricProducers.end());
774     auto& metricProducer1004 = *metricIt;
775     EXPECT_TRUE(metricProducer1004->isActive());
776 
777     // Config 3 is inactive. both metrics are inactive.
778     it = processor2->mMetricsManagers.find(cfgKey3);
779     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
780     auto& metricsManager1003 = it->second;
781     EXPECT_FALSE(metricsManager1003->isActive());
782     ASSERT_EQ(2, metricsManager1003->mAllMetricProducers.size());
783 
784     metricIt = metricsManager1003->mAllMetricProducers.begin();
785     for (; metricIt != metricsManager1002->mAllMetricProducers.end(); metricIt++) {
786         if ((*metricIt)->getMetricId() == metricId5) {
787             break;
788         }
789     }
790     EXPECT_TRUE(metricIt != metricsManager1003->mAllMetricProducers.end());
791     auto& metricProducer1005 = *metricIt;
792     EXPECT_FALSE(metricProducer1005->isActive());
793 
794     metricIt = metricsManager1003->mAllMetricProducers.begin();
795     for (; metricIt != metricsManager1003->mAllMetricProducers.end(); metricIt++) {
796         if ((*metricIt)->getMetricId() == metricId6) {
797             break;
798         }
799     }
800     EXPECT_TRUE(metricIt != metricsManager1003->mAllMetricProducers.end());
801     auto& metricProducer1006 = *metricIt;
802     EXPECT_FALSE(metricProducer1006->isActive());
803 
804     // Assert that all 3 metrics with activation are inactive and that the ttls were properly set.
805     EXPECT_FALSE(metricProducer1003->isActive());
806     const auto& activation1003 = metricProducer1003->mEventActivationMap.begin()->second;
807     EXPECT_EQ(100 * NS_PER_SEC, activation1003->ttl_ns);
808     EXPECT_EQ(0, activation1003->start_ns);
809     EXPECT_FALSE(metricProducer1005->isActive());
810     const auto& activation1005 = metricProducer1005->mEventActivationMap.begin()->second;
811     EXPECT_EQ(100 * NS_PER_SEC, activation1005->ttl_ns);
812     EXPECT_EQ(0, activation1005->start_ns);
813     EXPECT_FALSE(metricProducer1006->isActive());
814     const auto& activation1006 = metricProducer1006->mEventActivationMap.begin()->second;
815     EXPECT_EQ(200 * NS_PER_SEC, activation1006->ttl_ns);
816     EXPECT_EQ(0, activation1006->start_ns);
817 
818     processor2->LoadActiveConfigsFromDisk();
819 
820     // After loading activations from disk, assert that all 3 metrics are active.
821     EXPECT_TRUE(metricProducer1003->isActive());
822     EXPECT_EQ(timeBase2 + ttl3 - activation1003->ttl_ns, activation1003->start_ns);
823     EXPECT_TRUE(metricProducer1005->isActive());
824     EXPECT_EQ(timeBase2 + ttl5 - activation1005->ttl_ns, activation1005->start_ns);
825     EXPECT_TRUE(metricProducer1006->isActive());
826     EXPECT_EQ(timeBase2 + ttl6 - activation1006->ttl_ns, activation1003->start_ns);
827 
828     // Make sure no more broadcasts have happened.
829     EXPECT_EQ(broadcastCount, 1);
830 }
831 
TEST(StatsLogProcessorTest,TestActivationOnBoot)832 TEST(StatsLogProcessorTest, TestActivationOnBoot) {
833     int uid = 1111;
834 
835     StatsdConfig config1;
836     config1.set_id(12341);
837     auto wakelockAcquireMatcher = CreateAcquireWakelockAtomMatcher();
838     *config1.add_atom_matcher() = wakelockAcquireMatcher;
839 
840     long metricId1 = 1234561;
841     long metricId2 = 1234562;
842     auto countMetric1 = config1.add_count_metric();
843     countMetric1->set_id(metricId1);
844     countMetric1->set_what(wakelockAcquireMatcher.id());
845     countMetric1->set_bucket(FIVE_MINUTES);
846 
847     auto countMetric2 = config1.add_count_metric();
848     countMetric2->set_id(metricId2);
849     countMetric2->set_what(wakelockAcquireMatcher.id());
850     countMetric2->set_bucket(FIVE_MINUTES);
851 
852     auto metric1Activation = config1.add_metric_activation();
853     metric1Activation->set_metric_id(metricId1);
854     metric1Activation->set_activation_type(ACTIVATE_ON_BOOT);
855     auto metric1ActivationTrigger = metric1Activation->add_event_activation();
856     metric1ActivationTrigger->set_atom_matcher_id(wakelockAcquireMatcher.id());
857     metric1ActivationTrigger->set_ttl_seconds(100);
858 
859     ConfigKey cfgKey1(uid, 12341);
860     long timeBase1 = 1;
861     sp<StatsLogProcessor> processor =
862             CreateStatsLogProcessor(timeBase1, timeBase1, config1, cfgKey1);
863 
864     ASSERT_EQ(1, processor->mMetricsManagers.size());
865     auto it = processor->mMetricsManagers.find(cfgKey1);
866     EXPECT_TRUE(it != processor->mMetricsManagers.end());
867     auto& metricsManager1 = it->second;
868     EXPECT_TRUE(metricsManager1->isActive());
869 
870     auto metricIt = metricsManager1->mAllMetricProducers.begin();
871     for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
872         if ((*metricIt)->getMetricId() == metricId1) {
873             break;
874         }
875     }
876     EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
877     auto& metricProducer1 = *metricIt;
878     EXPECT_FALSE(metricProducer1->isActive());
879 
880     metricIt = metricsManager1->mAllMetricProducers.begin();
881     for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
882         if ((*metricIt)->getMetricId() == metricId2) {
883             break;
884         }
885     }
886     EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
887     auto& metricProducer2 = *metricIt;
888     EXPECT_TRUE(metricProducer2->isActive());
889 
890     const auto& activation1 = metricProducer1->mEventActivationMap.begin()->second;
891     EXPECT_EQ(100 * NS_PER_SEC, activation1->ttl_ns);
892     EXPECT_EQ(0, activation1->start_ns);
893     EXPECT_EQ(kNotActive, activation1->state);
894 
895     std::vector<int> attributionUids = {111};
896     std::vector<string> attributionTags = {"App1"};
897     std::unique_ptr<LogEvent> event =
898             CreateAcquireWakelockEvent(timeBase1 + 100, attributionUids, attributionTags, "wl1");
899     processor->OnLogEvent(event.get());
900 
901     EXPECT_FALSE(metricProducer1->isActive());
902     EXPECT_EQ(0, activation1->start_ns);
903     EXPECT_EQ(kActiveOnBoot, activation1->state);
904 
905     int64_t shutDownTime = timeBase1 + 100 * NS_PER_SEC;
906     processor->SaveActiveConfigsToDisk(shutDownTime);
907     EXPECT_FALSE(metricProducer1->isActive());
908     const int64_t ttl1 = metric1ActivationTrigger->ttl_seconds() * NS_PER_SEC;
909 
910     long timeBase2 = 1000;
911     sp<StatsLogProcessor> processor2 =
912             CreateStatsLogProcessor(timeBase2, timeBase2, config1, cfgKey1);
913 
914     ASSERT_EQ(1, processor2->mMetricsManagers.size());
915     it = processor2->mMetricsManagers.find(cfgKey1);
916     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
917     auto& metricsManager1001 = it->second;
918     EXPECT_TRUE(metricsManager1001->isActive());
919 
920     metricIt = metricsManager1001->mAllMetricProducers.begin();
921     for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
922         if ((*metricIt)->getMetricId() == metricId1) {
923             break;
924         }
925     }
926     EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
927     auto& metricProducer1001 = *metricIt;
928     EXPECT_FALSE(metricProducer1001->isActive());
929 
930     metricIt = metricsManager1001->mAllMetricProducers.begin();
931     for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
932         if ((*metricIt)->getMetricId() == metricId2) {
933             break;
934         }
935     }
936     EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
937     auto& metricProducer1002 = *metricIt;
938     EXPECT_TRUE(metricProducer1002->isActive());
939 
940     const auto& activation1001 = metricProducer1001->mEventActivationMap.begin()->second;
941     EXPECT_EQ(100 * NS_PER_SEC, activation1001->ttl_ns);
942     EXPECT_EQ(0, activation1001->start_ns);
943     EXPECT_EQ(kNotActive, activation1001->state);
944 
945     processor2->LoadActiveConfigsFromDisk();
946 
947     EXPECT_TRUE(metricProducer1001->isActive());
948     EXPECT_EQ(timeBase2 + ttl1 - activation1001->ttl_ns, activation1001->start_ns);
949     EXPECT_EQ(kActive, activation1001->state);
950 }
951 
TEST(StatsLogProcessorTest,TestActivationOnBootMultipleActivations)952 TEST(StatsLogProcessorTest, TestActivationOnBootMultipleActivations) {
953     int uid = 1111;
954 
955     // Create config with 2 metrics:
956     // Metric 1: Activate on boot with 2 activations
957     // Metric 2: Always active
958     StatsdConfig config1;
959     config1.set_id(12341);
960     auto wakelockAcquireMatcher = CreateAcquireWakelockAtomMatcher();
961     auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
962     *config1.add_atom_matcher() = wakelockAcquireMatcher;
963     *config1.add_atom_matcher() = screenOnMatcher;
964 
965     long metricId1 = 1234561;
966     long metricId2 = 1234562;
967 
968     auto countMetric1 = config1.add_count_metric();
969     countMetric1->set_id(metricId1);
970     countMetric1->set_what(wakelockAcquireMatcher.id());
971     countMetric1->set_bucket(FIVE_MINUTES);
972 
973     auto countMetric2 = config1.add_count_metric();
974     countMetric2->set_id(metricId2);
975     countMetric2->set_what(wakelockAcquireMatcher.id());
976     countMetric2->set_bucket(FIVE_MINUTES);
977 
978     auto metric1Activation = config1.add_metric_activation();
979     metric1Activation->set_metric_id(metricId1);
980     metric1Activation->set_activation_type(ACTIVATE_ON_BOOT);
981     auto metric1ActivationTrigger1 = metric1Activation->add_event_activation();
982     metric1ActivationTrigger1->set_atom_matcher_id(wakelockAcquireMatcher.id());
983     metric1ActivationTrigger1->set_ttl_seconds(100);
984     auto metric1ActivationTrigger2 = metric1Activation->add_event_activation();
985     metric1ActivationTrigger2->set_atom_matcher_id(screenOnMatcher.id());
986     metric1ActivationTrigger2->set_ttl_seconds(200);
987 
988     ConfigKey cfgKey1(uid, 12341);
989     long timeBase1 = 1;
990     sp<StatsLogProcessor> processor =
991             CreateStatsLogProcessor(timeBase1, timeBase1, config1, cfgKey1);
992 
993     // Metric 1 is not active.
994     // Metric 2 is active.
995     // {{{---------------------------------------------------------------------------
996     ASSERT_EQ(1, processor->mMetricsManagers.size());
997     auto it = processor->mMetricsManagers.find(cfgKey1);
998     EXPECT_TRUE(it != processor->mMetricsManagers.end());
999     auto& metricsManager1 = it->second;
1000     EXPECT_TRUE(metricsManager1->isActive());
1001 
1002     auto metricIt = metricsManager1->mAllMetricProducers.begin();
1003     for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
1004         if ((*metricIt)->getMetricId() == metricId1) {
1005             break;
1006         }
1007     }
1008     EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
1009     auto& metricProducer1 = *metricIt;
1010     EXPECT_FALSE(metricProducer1->isActive());
1011 
1012     metricIt = metricsManager1->mAllMetricProducers.begin();
1013     for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
1014         if ((*metricIt)->getMetricId() == metricId2) {
1015             break;
1016         }
1017     }
1018     EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
1019     auto& metricProducer2 = *metricIt;
1020     EXPECT_TRUE(metricProducer2->isActive());
1021 
1022     int i = 0;
1023     for (; i < metricsManager1->mAllAtomMatchingTrackers.size(); i++) {
1024         if (metricsManager1->mAllAtomMatchingTrackers[i]->getId() ==
1025             metric1ActivationTrigger1->atom_matcher_id()) {
1026             break;
1027         }
1028     }
1029     const auto& activation1 = metricProducer1->mEventActivationMap.at(i);
1030     EXPECT_EQ(100 * NS_PER_SEC, activation1->ttl_ns);
1031     EXPECT_EQ(0, activation1->start_ns);
1032     EXPECT_EQ(kNotActive, activation1->state);
1033 
1034     i = 0;
1035     for (; i < metricsManager1->mAllAtomMatchingTrackers.size(); i++) {
1036         if (metricsManager1->mAllAtomMatchingTrackers[i]->getId() ==
1037             metric1ActivationTrigger2->atom_matcher_id()) {
1038             break;
1039         }
1040     }
1041     const auto& activation2 = metricProducer1->mEventActivationMap.at(i);
1042     EXPECT_EQ(200 * NS_PER_SEC, activation2->ttl_ns);
1043     EXPECT_EQ(0, activation2->start_ns);
1044     EXPECT_EQ(kNotActive, activation2->state);
1045     // }}}------------------------------------------------------------------------------
1046 
1047     // Trigger Activation 1 for Metric 1
1048     std::vector<int> attributionUids = {111};
1049     std::vector<string> attributionTags = {"App1"};
1050     std::unique_ptr<LogEvent> event =
1051             CreateAcquireWakelockEvent(timeBase1 + 100, attributionUids, attributionTags, "wl1");
1052     processor->OnLogEvent(event.get());
1053 
1054     // Metric 1 is not active; Activation 1 set to kActiveOnBoot
1055     // Metric 2 is active.
1056     // {{{---------------------------------------------------------------------------
1057     EXPECT_FALSE(metricProducer1->isActive());
1058     EXPECT_EQ(0, activation1->start_ns);
1059     EXPECT_EQ(kActiveOnBoot, activation1->state);
1060     EXPECT_EQ(0, activation2->start_ns);
1061     EXPECT_EQ(kNotActive, activation2->state);
1062 
1063     EXPECT_TRUE(metricProducer2->isActive());
1064     // }}}-----------------------------------------------------------------------------
1065 
1066     // Simulate shutdown by saving state to disk
1067     int64_t shutDownTime = timeBase1 + 100 * NS_PER_SEC;
1068     processor->SaveActiveConfigsToDisk(shutDownTime);
1069     EXPECT_FALSE(metricProducer1->isActive());
1070     int64_t ttl1 = metric1ActivationTrigger1->ttl_seconds() * NS_PER_SEC;
1071 
1072     // Simulate device restarted state by creating new instance of StatsLogProcessor with the
1073     // same config.
1074     long timeBase2 = 1000;
1075     sp<StatsLogProcessor> processor2 =
1076             CreateStatsLogProcessor(timeBase2, timeBase2, config1, cfgKey1);
1077 
1078     // Metric 1 is not active.
1079     // Metric 2 is active.
1080     // {{{---------------------------------------------------------------------------
1081     ASSERT_EQ(1, processor2->mMetricsManagers.size());
1082     it = processor2->mMetricsManagers.find(cfgKey1);
1083     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
1084     auto& metricsManager1001 = it->second;
1085     EXPECT_TRUE(metricsManager1001->isActive());
1086 
1087     metricIt = metricsManager1001->mAllMetricProducers.begin();
1088     for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
1089         if ((*metricIt)->getMetricId() == metricId1) {
1090             break;
1091         }
1092     }
1093     EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
1094     auto& metricProducer1001 = *metricIt;
1095     EXPECT_FALSE(metricProducer1001->isActive());
1096 
1097     metricIt = metricsManager1001->mAllMetricProducers.begin();
1098     for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
1099         if ((*metricIt)->getMetricId() == metricId2) {
1100             break;
1101         }
1102     }
1103     EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
1104     auto& metricProducer1002 = *metricIt;
1105     EXPECT_TRUE(metricProducer1002->isActive());
1106 
1107     i = 0;
1108     for (; i < metricsManager1001->mAllAtomMatchingTrackers.size(); i++) {
1109         if (metricsManager1001->mAllAtomMatchingTrackers[i]->getId() ==
1110             metric1ActivationTrigger1->atom_matcher_id()) {
1111             break;
1112         }
1113     }
1114     const auto& activation1001_1 = metricProducer1001->mEventActivationMap.at(i);
1115     EXPECT_EQ(100 * NS_PER_SEC, activation1001_1->ttl_ns);
1116     EXPECT_EQ(0, activation1001_1->start_ns);
1117     EXPECT_EQ(kNotActive, activation1001_1->state);
1118 
1119     i = 0;
1120     for (; i < metricsManager1001->mAllAtomMatchingTrackers.size(); i++) {
1121         if (metricsManager1001->mAllAtomMatchingTrackers[i]->getId() ==
1122             metric1ActivationTrigger2->atom_matcher_id()) {
1123             break;
1124         }
1125     }
1126 
1127     const auto& activation1001_2 = metricProducer1001->mEventActivationMap.at(i);
1128     EXPECT_EQ(200 * NS_PER_SEC, activation1001_2->ttl_ns);
1129     EXPECT_EQ(0, activation1001_2->start_ns);
1130     EXPECT_EQ(kNotActive, activation1001_2->state);
1131     // }}}-----------------------------------------------------------------------------------
1132 
1133     // Load saved state from disk.
1134     processor2->LoadActiveConfigsFromDisk();
1135 
1136     // Metric 1 active; Activation 1 is active, Activation 2 is not active
1137     // Metric 2 is active.
1138     // {{{---------------------------------------------------------------------------
1139     EXPECT_TRUE(metricProducer1001->isActive());
1140     EXPECT_EQ(timeBase2 + ttl1 - activation1001_1->ttl_ns, activation1001_1->start_ns);
1141     EXPECT_EQ(kActive, activation1001_1->state);
1142     EXPECT_EQ(0, activation1001_2->start_ns);
1143     EXPECT_EQ(kNotActive, activation1001_2->state);
1144 
1145     EXPECT_TRUE(metricProducer1002->isActive());
1146     // }}}--------------------------------------------------------------------------------
1147 
1148     // Trigger Activation 2 for Metric 1.
1149     auto screenOnEvent =
1150             CreateScreenStateChangedEvent(timeBase2 + 200, android::view::DISPLAY_STATE_ON);
1151     processor2->OnLogEvent(screenOnEvent.get());
1152 
1153     // Metric 1 active; Activation 1 is active, Activation 2 is set to kActiveOnBoot
1154     // Metric 2 is active.
1155     // {{{---------------------------------------------------------------------------
1156     EXPECT_TRUE(metricProducer1001->isActive());
1157     EXPECT_EQ(timeBase2 + ttl1 - activation1001_1->ttl_ns, activation1001_1->start_ns);
1158     EXPECT_EQ(kActive, activation1001_1->state);
1159     EXPECT_EQ(0, activation1001_2->start_ns);
1160     EXPECT_EQ(kActiveOnBoot, activation1001_2->state);
1161 
1162     EXPECT_TRUE(metricProducer1002->isActive());
1163     // }}}---------------------------------------------------------------------------
1164 
1165     // Simulate shutdown by saving state to disk
1166     shutDownTime = timeBase2 + 50 * NS_PER_SEC;
1167     processor2->SaveActiveConfigsToDisk(shutDownTime);
1168     EXPECT_TRUE(metricProducer1001->isActive());
1169     EXPECT_TRUE(metricProducer1002->isActive());
1170     ttl1 = timeBase2 + metric1ActivationTrigger1->ttl_seconds() * NS_PER_SEC - shutDownTime;
1171     int64_t ttl2 = metric1ActivationTrigger2->ttl_seconds() * NS_PER_SEC;
1172 
1173     // Simulate device restarted state by creating new instance of StatsLogProcessor with the
1174     // same config.
1175     long timeBase3 = timeBase2 + 120 * NS_PER_SEC;
1176     sp<StatsLogProcessor> processor3 =
1177             CreateStatsLogProcessor(timeBase3, timeBase3, config1, cfgKey1);
1178 
1179     // Metric 1 is not active.
1180     // Metric 2 is active.
1181     // {{{---------------------------------------------------------------------------
1182     ASSERT_EQ(1, processor3->mMetricsManagers.size());
1183     it = processor3->mMetricsManagers.find(cfgKey1);
1184     EXPECT_TRUE(it != processor3->mMetricsManagers.end());
1185     auto& metricsManagerTimeBase3 = it->second;
1186     EXPECT_TRUE(metricsManagerTimeBase3->isActive());
1187 
1188     metricIt = metricsManagerTimeBase3->mAllMetricProducers.begin();
1189     for (; metricIt != metricsManagerTimeBase3->mAllMetricProducers.end(); metricIt++) {
1190         if ((*metricIt)->getMetricId() == metricId1) {
1191             break;
1192         }
1193     }
1194     EXPECT_TRUE(metricIt != metricsManagerTimeBase3->mAllMetricProducers.end());
1195     auto& metricProducerTimeBase3_1 = *metricIt;
1196     EXPECT_FALSE(metricProducerTimeBase3_1->isActive());
1197 
1198     metricIt = metricsManagerTimeBase3->mAllMetricProducers.begin();
1199     for (; metricIt != metricsManagerTimeBase3->mAllMetricProducers.end(); metricIt++) {
1200         if ((*metricIt)->getMetricId() == metricId2) {
1201             break;
1202         }
1203     }
1204     EXPECT_TRUE(metricIt != metricsManagerTimeBase3->mAllMetricProducers.end());
1205     auto& metricProducerTimeBase3_2 = *metricIt;
1206     EXPECT_TRUE(metricProducerTimeBase3_2->isActive());
1207 
1208     i = 0;
1209     for (; i < metricsManagerTimeBase3->mAllAtomMatchingTrackers.size(); i++) {
1210         if (metricsManagerTimeBase3->mAllAtomMatchingTrackers[i]->getId() ==
1211             metric1ActivationTrigger1->atom_matcher_id()) {
1212             break;
1213         }
1214     }
1215     const auto& activationTimeBase3_1 = metricProducerTimeBase3_1->mEventActivationMap.at(i);
1216     EXPECT_EQ(100 * NS_PER_SEC, activationTimeBase3_1->ttl_ns);
1217     EXPECT_EQ(0, activationTimeBase3_1->start_ns);
1218     EXPECT_EQ(kNotActive, activationTimeBase3_1->state);
1219 
1220     i = 0;
1221     for (; i < metricsManagerTimeBase3->mAllAtomMatchingTrackers.size(); i++) {
1222         if (metricsManagerTimeBase3->mAllAtomMatchingTrackers[i]->getId() ==
1223             metric1ActivationTrigger2->atom_matcher_id()) {
1224             break;
1225         }
1226     }
1227 
1228     const auto& activationTimeBase3_2 = metricProducerTimeBase3_1->mEventActivationMap.at(i);
1229     EXPECT_EQ(200 * NS_PER_SEC, activationTimeBase3_2->ttl_ns);
1230     EXPECT_EQ(0, activationTimeBase3_2->start_ns);
1231     EXPECT_EQ(kNotActive, activationTimeBase3_2->state);
1232 
1233     EXPECT_TRUE(metricProducerTimeBase3_2->isActive());
1234     // }}}----------------------------------------------------------------------------------
1235 
1236     // Load saved state from disk.
1237     processor3->LoadActiveConfigsFromDisk();
1238 
1239     // Metric 1 active: Activation 1 is active, Activation 2 is active
1240     // Metric 2 is active.
1241     // {{{---------------------------------------------------------------------------
1242     EXPECT_TRUE(metricProducerTimeBase3_1->isActive());
1243     EXPECT_EQ(timeBase3 + ttl1 - activationTimeBase3_1->ttl_ns, activationTimeBase3_1->start_ns);
1244     EXPECT_EQ(kActive, activationTimeBase3_1->state);
1245     EXPECT_EQ(timeBase3 + ttl2 - activationTimeBase3_2->ttl_ns, activationTimeBase3_2->start_ns);
1246     EXPECT_EQ(kActive, activationTimeBase3_2->state);
1247 
1248     EXPECT_TRUE(metricProducerTimeBase3_2->isActive());
1249     // }}}-------------------------------------------------------------------------------
1250 
1251     // Trigger Activation 2 for Metric 1 again.
1252     screenOnEvent = CreateScreenStateChangedEvent(timeBase3 + 100 * NS_PER_SEC,
1253                                                   android::view::DISPLAY_STATE_ON);
1254     processor3->OnLogEvent(screenOnEvent.get());
1255 
1256     // Metric 1 active; Activation 1 is not active, Activation 2 is set to active
1257     // Metric 2 is active.
1258     // {{{---------------------------------------------------------------------------
1259     EXPECT_TRUE(metricProducerTimeBase3_1->isActive());
1260     EXPECT_EQ(kNotActive, activationTimeBase3_1->state);
1261     EXPECT_EQ(timeBase3 + ttl2 - activationTimeBase3_2->ttl_ns, activationTimeBase3_2->start_ns);
1262     EXPECT_EQ(kActive, activationTimeBase3_2->state);
1263 
1264     EXPECT_TRUE(metricProducerTimeBase3_2->isActive());
1265     // }}}---------------------------------------------------------------------------
1266 
1267     // Simulate shutdown by saving state to disk.
1268     shutDownTime = timeBase3 + 500 * NS_PER_SEC;
1269     processor3->SaveActiveConfigsToDisk(shutDownTime);
1270     EXPECT_TRUE(metricProducer1001->isActive());
1271     EXPECT_TRUE(metricProducer1002->isActive());
1272     ttl1 = timeBase3 + ttl1 - shutDownTime;
1273     ttl2 = timeBase3 + metric1ActivationTrigger2->ttl_seconds() * NS_PER_SEC - shutDownTime;
1274 
1275     // Simulate device restarted state by creating new instance of StatsLogProcessor with the
1276     // same config.
1277     long timeBase4 = timeBase3 + 600 * NS_PER_SEC;
1278     sp<StatsLogProcessor> processor4 =
1279             CreateStatsLogProcessor(timeBase4, timeBase4, config1, cfgKey1);
1280 
1281     // Metric 1 is not active.
1282     // Metric 2 is active.
1283     // {{{---------------------------------------------------------------------------
1284     ASSERT_EQ(1, processor4->mMetricsManagers.size());
1285     it = processor4->mMetricsManagers.find(cfgKey1);
1286     EXPECT_TRUE(it != processor4->mMetricsManagers.end());
1287     auto& metricsManagerTimeBase4 = it->second;
1288     EXPECT_TRUE(metricsManagerTimeBase4->isActive());
1289 
1290     metricIt = metricsManagerTimeBase4->mAllMetricProducers.begin();
1291     for (; metricIt != metricsManagerTimeBase4->mAllMetricProducers.end(); metricIt++) {
1292         if ((*metricIt)->getMetricId() == metricId1) {
1293             break;
1294         }
1295     }
1296     EXPECT_TRUE(metricIt != metricsManagerTimeBase4->mAllMetricProducers.end());
1297     auto& metricProducerTimeBase4_1 = *metricIt;
1298     EXPECT_FALSE(metricProducerTimeBase4_1->isActive());
1299 
1300     metricIt = metricsManagerTimeBase4->mAllMetricProducers.begin();
1301     for (; metricIt != metricsManagerTimeBase4->mAllMetricProducers.end(); metricIt++) {
1302         if ((*metricIt)->getMetricId() == metricId2) {
1303             break;
1304         }
1305     }
1306     EXPECT_TRUE(metricIt != metricsManagerTimeBase4->mAllMetricProducers.end());
1307     auto& metricProducerTimeBase4_2 = *metricIt;
1308     EXPECT_TRUE(metricProducerTimeBase4_2->isActive());
1309 
1310     i = 0;
1311     for (; i < metricsManagerTimeBase4->mAllAtomMatchingTrackers.size(); i++) {
1312         if (metricsManagerTimeBase4->mAllAtomMatchingTrackers[i]->getId() ==
1313             metric1ActivationTrigger1->atom_matcher_id()) {
1314             break;
1315         }
1316     }
1317     const auto& activationTimeBase4_1 = metricProducerTimeBase4_1->mEventActivationMap.at(i);
1318     EXPECT_EQ(100 * NS_PER_SEC, activationTimeBase4_1->ttl_ns);
1319     EXPECT_EQ(0, activationTimeBase4_1->start_ns);
1320     EXPECT_EQ(kNotActive, activationTimeBase4_1->state);
1321 
1322     i = 0;
1323     for (; i < metricsManagerTimeBase4->mAllAtomMatchingTrackers.size(); i++) {
1324         if (metricsManagerTimeBase4->mAllAtomMatchingTrackers[i]->getId() ==
1325             metric1ActivationTrigger2->atom_matcher_id()) {
1326             break;
1327         }
1328     }
1329 
1330     const auto& activationTimeBase4_2 = metricProducerTimeBase4_1->mEventActivationMap.at(i);
1331     EXPECT_EQ(200 * NS_PER_SEC, activationTimeBase4_2->ttl_ns);
1332     EXPECT_EQ(0, activationTimeBase4_2->start_ns);
1333     EXPECT_EQ(kNotActive, activationTimeBase4_2->state);
1334 
1335     EXPECT_TRUE(metricProducerTimeBase4_2->isActive());
1336     // }}}----------------------------------------------------------------------------------
1337 
1338     // Load saved state from disk.
1339     processor4->LoadActiveConfigsFromDisk();
1340 
1341     // Metric 1 active: Activation 1 is not active, Activation 2 is not active
1342     // Metric 2 is active.
1343     // {{{---------------------------------------------------------------------------
1344     EXPECT_FALSE(metricProducerTimeBase4_1->isActive());
1345     EXPECT_EQ(kNotActive, activationTimeBase4_1->state);
1346     EXPECT_EQ(kNotActive, activationTimeBase4_2->state);
1347 
1348     EXPECT_TRUE(metricProducerTimeBase4_2->isActive());
1349     // }}}-------------------------------------------------------------------------------
1350 }
1351 
TEST(StatsLogProcessorTest,TestActivationOnBootMultipleActivationsDifferentActivationTypes)1352 TEST(StatsLogProcessorTest, TestActivationOnBootMultipleActivationsDifferentActivationTypes) {
1353     int uid = 1111;
1354 
1355     // Create config with 2 metrics:
1356     // Metric 1: Activate on boot with 2 activations
1357     // Metric 2: Always active
1358     StatsdConfig config1;
1359     config1.set_id(12341);
1360     auto wakelockAcquireMatcher = CreateAcquireWakelockAtomMatcher();
1361     auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
1362     *config1.add_atom_matcher() = wakelockAcquireMatcher;
1363     *config1.add_atom_matcher() = screenOnMatcher;
1364 
1365     long metricId1 = 1234561;
1366     long metricId2 = 1234562;
1367 
1368     auto countMetric1 = config1.add_count_metric();
1369     countMetric1->set_id(metricId1);
1370     countMetric1->set_what(wakelockAcquireMatcher.id());
1371     countMetric1->set_bucket(FIVE_MINUTES);
1372 
1373     auto countMetric2 = config1.add_count_metric();
1374     countMetric2->set_id(metricId2);
1375     countMetric2->set_what(wakelockAcquireMatcher.id());
1376     countMetric2->set_bucket(FIVE_MINUTES);
1377 
1378     auto metric1Activation = config1.add_metric_activation();
1379     metric1Activation->set_metric_id(metricId1);
1380     metric1Activation->set_activation_type(ACTIVATE_ON_BOOT);
1381     auto metric1ActivationTrigger1 = metric1Activation->add_event_activation();
1382     metric1ActivationTrigger1->set_atom_matcher_id(wakelockAcquireMatcher.id());
1383     metric1ActivationTrigger1->set_ttl_seconds(100);
1384     auto metric1ActivationTrigger2 = metric1Activation->add_event_activation();
1385     metric1ActivationTrigger2->set_atom_matcher_id(screenOnMatcher.id());
1386     metric1ActivationTrigger2->set_ttl_seconds(200);
1387     metric1ActivationTrigger2->set_activation_type(ACTIVATE_IMMEDIATELY);
1388 
1389     ConfigKey cfgKey1(uid, 12341);
1390     long timeBase1 = 1;
1391     sp<StatsLogProcessor> processor1 =
1392             CreateStatsLogProcessor(timeBase1, timeBase1, config1, cfgKey1);
1393 
1394     // Metric 1 is not active.
1395     // Metric 2 is active.
1396     // {{{---------------------------------------------------------------------------
1397     ASSERT_EQ(1, processor1->mMetricsManagers.size());
1398     auto it = processor1->mMetricsManagers.find(cfgKey1);
1399     EXPECT_TRUE(it != processor1->mMetricsManagers.end());
1400     auto& metricsManager1 = it->second;
1401     EXPECT_TRUE(metricsManager1->isActive());
1402 
1403     ASSERT_EQ(metricsManager1->mAllMetricProducers.size(), 2);
1404     // We assume that the index of a MetricProducer within the mAllMetricProducers
1405     // array follows the order in which metrics are added to the config.
1406     auto& metricProducer1_1 = metricsManager1->mAllMetricProducers[0];
1407     EXPECT_EQ(metricProducer1_1->getMetricId(), metricId1);
1408     EXPECT_FALSE(metricProducer1_1->isActive());  // inactive due to associated MetricActivation
1409 
1410     auto& metricProducer1_2 = metricsManager1->mAllMetricProducers[1];
1411     EXPECT_EQ(metricProducer1_2->getMetricId(), metricId2);
1412     EXPECT_TRUE(metricProducer1_2->isActive());
1413 
1414     ASSERT_EQ(metricProducer1_1->mEventActivationMap.size(), 2);
1415     // The key in mEventActivationMap is the index of the associated atom matcher. We assume
1416     // that matchers are indexed in the order that they are added to the config.
1417     const auto& activation1_1_1 = metricProducer1_1->mEventActivationMap.at(0);
1418     EXPECT_EQ(100 * NS_PER_SEC, activation1_1_1->ttl_ns);
1419     EXPECT_EQ(0, activation1_1_1->start_ns);
1420     EXPECT_EQ(kNotActive, activation1_1_1->state);
1421     EXPECT_EQ(ACTIVATE_ON_BOOT, activation1_1_1->activationType);
1422 
1423     const auto& activation1_1_2 = metricProducer1_1->mEventActivationMap.at(1);
1424     EXPECT_EQ(200 * NS_PER_SEC, activation1_1_2->ttl_ns);
1425     EXPECT_EQ(0, activation1_1_2->start_ns);
1426     EXPECT_EQ(kNotActive, activation1_1_2->state);
1427     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation1_1_2->activationType);
1428     // }}}------------------------------------------------------------------------------
1429 
1430     // Trigger Activation 1 for Metric 1
1431     std::vector<int> attributionUids = {111};
1432     std::vector<string> attributionTags = {"App1"};
1433     std::unique_ptr<LogEvent> event =
1434             CreateAcquireWakelockEvent(timeBase1 + 100, attributionUids, attributionTags, "wl1");
1435     processor1->OnLogEvent(event.get());
1436 
1437     // Metric 1 is not active; Activation 1 set to kActiveOnBoot
1438     // Metric 2 is active.
1439     // {{{---------------------------------------------------------------------------
1440     EXPECT_FALSE(metricProducer1_1->isActive());
1441     EXPECT_EQ(0, activation1_1_1->start_ns);
1442     EXPECT_EQ(kActiveOnBoot, activation1_1_1->state);
1443     EXPECT_EQ(0, activation1_1_2->start_ns);
1444     EXPECT_EQ(kNotActive, activation1_1_2->state);
1445 
1446     EXPECT_TRUE(metricProducer1_2->isActive());
1447     // }}}-----------------------------------------------------------------------------
1448 
1449     // Simulate shutdown by saving state to disk
1450     int64_t shutDownTime = timeBase1 + 100 * NS_PER_SEC;
1451     processor1->SaveActiveConfigsToDisk(shutDownTime);
1452     EXPECT_FALSE(metricProducer1_1->isActive());
1453 
1454     // Simulate device restarted state by creating new instance of StatsLogProcessor with the
1455     // same config.
1456     long timeBase2 = 1000;
1457     sp<StatsLogProcessor> processor2 =
1458             CreateStatsLogProcessor(timeBase2, timeBase2, config1, cfgKey1);
1459 
1460     // Metric 1 is not active.
1461     // Metric 2 is active.
1462     // {{{---------------------------------------------------------------------------
1463     ASSERT_EQ(1, processor2->mMetricsManagers.size());
1464     it = processor2->mMetricsManagers.find(cfgKey1);
1465     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
1466     auto& metricsManager2 = it->second;
1467     EXPECT_TRUE(metricsManager2->isActive());
1468 
1469     ASSERT_EQ(metricsManager2->mAllMetricProducers.size(), 2);
1470     // We assume that the index of a MetricProducer within the mAllMetricProducers
1471     // array follows the order in which metrics are added to the config.
1472     auto& metricProducer2_1 = metricsManager2->mAllMetricProducers[0];
1473     EXPECT_EQ(metricProducer2_1->getMetricId(), metricId1);
1474     EXPECT_FALSE(metricProducer2_1->isActive());
1475 
1476     auto& metricProducer2_2 = metricsManager2->mAllMetricProducers[1];
1477     EXPECT_EQ(metricProducer2_2->getMetricId(), metricId2);
1478     EXPECT_TRUE(metricProducer2_2->isActive());
1479 
1480     ASSERT_EQ(metricProducer2_1->mEventActivationMap.size(), 2);
1481     // The key in mEventActivationMap is the index of the associated atom matcher. We assume
1482     // that matchers are indexed in the order that they are added to the config.
1483     const auto& activation2_1_1 = metricProducer2_1->mEventActivationMap.at(0);
1484     EXPECT_EQ(100 * NS_PER_SEC, activation2_1_1->ttl_ns);
1485     EXPECT_EQ(0, activation2_1_1->start_ns);
1486     EXPECT_EQ(kNotActive, activation2_1_1->state);
1487     EXPECT_EQ(ACTIVATE_ON_BOOT, activation2_1_1->activationType);
1488 
1489     const auto& activation2_1_2 = metricProducer2_1->mEventActivationMap.at(1);
1490     EXPECT_EQ(200 * NS_PER_SEC, activation2_1_2->ttl_ns);
1491     EXPECT_EQ(0, activation2_1_2->start_ns);
1492     EXPECT_EQ(kNotActive, activation2_1_2->state);
1493     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation2_1_2->activationType);
1494     // }}}-----------------------------------------------------------------------------------
1495 
1496     // Load saved state from disk.
1497     processor2->LoadActiveConfigsFromDisk();
1498 
1499     // Metric 1 active; Activation 1 is active, Activation 2 is not active
1500     // Metric 2 is active.
1501     // {{{---------------------------------------------------------------------------
1502     EXPECT_TRUE(metricProducer2_1->isActive());
1503     int64_t ttl1 = metric1ActivationTrigger1->ttl_seconds() * NS_PER_SEC;
1504     EXPECT_EQ(timeBase2 + ttl1 - activation2_1_1->ttl_ns, activation2_1_1->start_ns);
1505     EXPECT_EQ(kActive, activation2_1_1->state);
1506     EXPECT_EQ(0, activation2_1_2->start_ns);
1507     EXPECT_EQ(kNotActive, activation2_1_2->state);
1508 
1509     EXPECT_TRUE(metricProducer2_2->isActive());
1510     // }}}--------------------------------------------------------------------------------
1511 
1512     // Trigger Activation 2 for Metric 1.
1513     auto screenOnEvent =
1514             CreateScreenStateChangedEvent(timeBase2 + 200, android::view::DISPLAY_STATE_ON);
1515     processor2->OnLogEvent(screenOnEvent.get());
1516 
1517     // Metric 1 active; Activation 1 is active, Activation 2 is active
1518     // Metric 2 is active.
1519     // {{{---------------------------------------------------------------------------
1520     EXPECT_TRUE(metricProducer2_1->isActive());
1521     EXPECT_EQ(timeBase2 + ttl1 - activation2_1_1->ttl_ns, activation2_1_1->start_ns);
1522     EXPECT_EQ(kActive, activation2_1_1->state);
1523     EXPECT_EQ(screenOnEvent->GetElapsedTimestampNs(), activation2_1_2->start_ns);
1524     EXPECT_EQ(kActive, activation2_1_2->state);
1525 
1526     EXPECT_TRUE(metricProducer2_2->isActive());
1527     // }}}---------------------------------------------------------------------------
1528 
1529     // Simulate shutdown by saving state to disk
1530     shutDownTime = timeBase2 + 50 * NS_PER_SEC;
1531     processor2->SaveActiveConfigsToDisk(shutDownTime);
1532     EXPECT_TRUE(metricProducer2_1->isActive());
1533     EXPECT_TRUE(metricProducer2_2->isActive());
1534     ttl1 -= shutDownTime - timeBase2;
1535     int64_t ttl2 = metric1ActivationTrigger2->ttl_seconds() * NS_PER_SEC -
1536                    (shutDownTime - screenOnEvent->GetElapsedTimestampNs());
1537 
1538     // Simulate device restarted state by creating new instance of StatsLogProcessor with the
1539     // same config.
1540     long timeBase3 = timeBase2 + 120 * NS_PER_SEC;
1541     sp<StatsLogProcessor> processor3 =
1542             CreateStatsLogProcessor(timeBase3, timeBase3, config1, cfgKey1);
1543 
1544     // Metric 1 is not active.
1545     // Metric 2 is active.
1546     // {{{---------------------------------------------------------------------------
1547     ASSERT_EQ(1, processor3->mMetricsManagers.size());
1548     it = processor3->mMetricsManagers.find(cfgKey1);
1549     EXPECT_TRUE(it != processor3->mMetricsManagers.end());
1550     auto& metricsManager3 = it->second;
1551     EXPECT_TRUE(metricsManager3->isActive());
1552 
1553     ASSERT_EQ(metricsManager3->mAllMetricProducers.size(), 2);
1554     // We assume that the index of a MetricProducer within the mAllMetricProducers
1555     // array follows the order in which metrics are added to the config.
1556     auto& metricProducer3_1 = metricsManager3->mAllMetricProducers[0];
1557     EXPECT_EQ(metricProducer3_1->getMetricId(), metricId1);
1558     EXPECT_FALSE(metricProducer3_1->isActive());
1559 
1560     auto& metricProducer3_2 = metricsManager3->mAllMetricProducers[1];
1561     EXPECT_EQ(metricProducer3_2->getMetricId(), metricId2);
1562     EXPECT_TRUE(metricProducer3_2->isActive());
1563 
1564     ASSERT_EQ(metricProducer3_1->mEventActivationMap.size(), 2);
1565     // The key in mEventActivationMap is the index of the associated atom matcher. We assume
1566     // that matchers are indexed in the order that they are added to the config.
1567     const auto& activation3_1_1 = metricProducer3_1->mEventActivationMap.at(0);
1568     EXPECT_EQ(100 * NS_PER_SEC, activation3_1_1->ttl_ns);
1569     EXPECT_EQ(0, activation3_1_1->start_ns);
1570     EXPECT_EQ(kNotActive, activation3_1_1->state);
1571     EXPECT_EQ(ACTIVATE_ON_BOOT, activation3_1_1->activationType);
1572 
1573     const auto& activation3_1_2 = metricProducer3_1->mEventActivationMap.at(1);
1574     EXPECT_EQ(200 * NS_PER_SEC, activation3_1_2->ttl_ns);
1575     EXPECT_EQ(0, activation3_1_2->start_ns);
1576     EXPECT_EQ(kNotActive, activation3_1_2->state);
1577     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation3_1_2->activationType);
1578     // }}}----------------------------------------------------------------------------------
1579 
1580     // Load saved state from disk.
1581     processor3->LoadActiveConfigsFromDisk();
1582 
1583     // Metric 1 active: Activation 1 is active, Activation 2 is active
1584     // Metric 2 is active.
1585     // {{{---------------------------------------------------------------------------
1586     EXPECT_TRUE(metricProducer3_1->isActive());
1587     EXPECT_EQ(timeBase3 + ttl1 - activation3_1_1->ttl_ns, activation3_1_1->start_ns);
1588     EXPECT_EQ(kActive, activation3_1_1->state);
1589     EXPECT_EQ(timeBase3 + ttl2 - activation3_1_2->ttl_ns, activation3_1_2->start_ns);
1590     EXPECT_EQ(kActive, activation3_1_2->state);
1591 
1592     EXPECT_TRUE(metricProducer3_2->isActive());
1593     // }}}-------------------------------------------------------------------------------
1594 
1595     // Trigger Activation 2 for Metric 1 again.
1596     screenOnEvent = CreateScreenStateChangedEvent(timeBase3 + 100 * NS_PER_SEC,
1597                                                   android::view::DISPLAY_STATE_ON);
1598     processor3->OnLogEvent(screenOnEvent.get());
1599 
1600     // Metric 1 active; Activation 1 is inactive (above screenOnEvent causes ttl1 to expire),
1601     //                  Activation 2 is set to active
1602     // Metric 2 is active.
1603     // {{{---------------------------------------------------------------------------
1604     EXPECT_TRUE(metricProducer3_1->isActive());
1605     EXPECT_EQ(kNotActive, activation3_1_1->state);
1606     EXPECT_EQ(screenOnEvent->GetElapsedTimestampNs(), activation3_1_2->start_ns);
1607     EXPECT_EQ(kActive, activation3_1_2->state);
1608 
1609     EXPECT_TRUE(metricProducer3_2->isActive());
1610     // }}}---------------------------------------------------------------------------
1611 }
1612 
TEST(StatsLogProcessorTest,TestActivationsPersistAcrossSystemServerRestart)1613 TEST(StatsLogProcessorTest, TestActivationsPersistAcrossSystemServerRestart) {
1614     int uid = 9876;
1615     long configId = 12341;
1616 
1617     // Create config with 3 metrics:
1618     // Metric 1: Activate on 2 activations, 1 on boot, 1 immediate.
1619     // Metric 2: Activate on 2 activations, 1 on boot, 1 immediate.
1620     // Metric 3: Always active
1621     StatsdConfig config1;
1622     config1.set_id(configId);
1623     auto wakelockAcquireMatcher = CreateAcquireWakelockAtomMatcher();
1624     auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
1625     auto jobStartMatcher = CreateStartScheduledJobAtomMatcher();
1626     auto jobFinishMatcher = CreateFinishScheduledJobAtomMatcher();
1627     *config1.add_atom_matcher() = wakelockAcquireMatcher;
1628     *config1.add_atom_matcher() = screenOnMatcher;
1629     *config1.add_atom_matcher() = jobStartMatcher;
1630     *config1.add_atom_matcher() = jobFinishMatcher;
1631 
1632     long metricId1 = 1234561;
1633     long metricId2 = 1234562;
1634     long metricId3 = 1234563;
1635 
1636     auto countMetric1 = config1.add_count_metric();
1637     countMetric1->set_id(metricId1);
1638     countMetric1->set_what(wakelockAcquireMatcher.id());
1639     countMetric1->set_bucket(FIVE_MINUTES);
1640 
1641     auto countMetric2 = config1.add_count_metric();
1642     countMetric2->set_id(metricId2);
1643     countMetric2->set_what(wakelockAcquireMatcher.id());
1644     countMetric2->set_bucket(FIVE_MINUTES);
1645 
1646     auto countMetric3 = config1.add_count_metric();
1647     countMetric3->set_id(metricId3);
1648     countMetric3->set_what(wakelockAcquireMatcher.id());
1649     countMetric3->set_bucket(FIVE_MINUTES);
1650 
1651     // Metric 1 activates on boot for wakelock acquire, immediately for screen on.
1652     auto metric1Activation = config1.add_metric_activation();
1653     metric1Activation->set_metric_id(metricId1);
1654     auto metric1ActivationTrigger1 = metric1Activation->add_event_activation();
1655     metric1ActivationTrigger1->set_atom_matcher_id(wakelockAcquireMatcher.id());
1656     metric1ActivationTrigger1->set_ttl_seconds(100);
1657     metric1ActivationTrigger1->set_activation_type(ACTIVATE_ON_BOOT);
1658     auto metric1ActivationTrigger2 = metric1Activation->add_event_activation();
1659     metric1ActivationTrigger2->set_atom_matcher_id(screenOnMatcher.id());
1660     metric1ActivationTrigger2->set_ttl_seconds(200);
1661     metric1ActivationTrigger2->set_activation_type(ACTIVATE_IMMEDIATELY);
1662 
1663     // Metric 2 activates on boot for scheduled job start, immediately for scheduled job finish.
1664     auto metric2Activation = config1.add_metric_activation();
1665     metric2Activation->set_metric_id(metricId2);
1666     auto metric2ActivationTrigger1 = metric2Activation->add_event_activation();
1667     metric2ActivationTrigger1->set_atom_matcher_id(jobStartMatcher.id());
1668     metric2ActivationTrigger1->set_ttl_seconds(100);
1669     metric2ActivationTrigger1->set_activation_type(ACTIVATE_ON_BOOT);
1670     auto metric2ActivationTrigger2 = metric2Activation->add_event_activation();
1671     metric2ActivationTrigger2->set_atom_matcher_id(jobFinishMatcher.id());
1672     metric2ActivationTrigger2->set_ttl_seconds(200);
1673     metric2ActivationTrigger2->set_activation_type(ACTIVATE_IMMEDIATELY);
1674 
1675     // Send the config.
1676     const sp<UidMap> uidMap = new UidMap();
1677     const shared_ptr<StatsService> service = SharedRefBase::make<StatsService>(
1678             uidMap, /* queue */ nullptr, std::make_shared<LogEventFilter>());
1679     string serialized = config1.SerializeAsString();
1680     service->addConfigurationChecked(uid, configId, {serialized.begin(), serialized.end()});
1681 
1682     // Make sure the config is stored on disk. Otherwise, we will not reset on system server death.
1683     StatsdConfig tmpConfig;
1684     ConfigKey cfgKey1(uid, configId);
1685     EXPECT_TRUE(StorageManager::readConfigFromDisk(cfgKey1, &tmpConfig));
1686 
1687     // Metric 1 is not active.
1688     // Metric 2 is not active.
1689     // Metric 3 is active.
1690     // {{{---------------------------------------------------------------------------
1691     sp<StatsLogProcessor> processor = service->mProcessor;
1692     ASSERT_EQ(1, processor->mMetricsManagers.size());
1693     auto it = processor->mMetricsManagers.find(cfgKey1);
1694     EXPECT_TRUE(it != processor->mMetricsManagers.end());
1695     auto& metricsManager1 = it->second;
1696     EXPECT_TRUE(metricsManager1->isActive());
1697     ASSERT_EQ(3, metricsManager1->mAllMetricProducers.size());
1698 
1699     auto& metricProducer1 = metricsManager1->mAllMetricProducers[0];
1700     EXPECT_EQ(metricId1, metricProducer1->getMetricId());
1701     EXPECT_FALSE(metricProducer1->isActive());
1702 
1703     auto& metricProducer2 = metricsManager1->mAllMetricProducers[1];
1704     EXPECT_EQ(metricId2, metricProducer2->getMetricId());
1705     EXPECT_FALSE(metricProducer2->isActive());
1706 
1707     auto& metricProducer3 = metricsManager1->mAllMetricProducers[2];
1708     EXPECT_EQ(metricId3, metricProducer3->getMetricId());
1709     EXPECT_TRUE(metricProducer3->isActive());
1710 
1711     // Check event activations.
1712     ASSERT_EQ(metricsManager1->mAllAtomMatchingTrackers.size(), 4);
1713     EXPECT_EQ(metricsManager1->mAllAtomMatchingTrackers[0]->getId(),
1714               metric1ActivationTrigger1->atom_matcher_id());
1715     const auto& activation1 = metricProducer1->mEventActivationMap.at(0);
1716     EXPECT_EQ(100 * NS_PER_SEC, activation1->ttl_ns);
1717     EXPECT_EQ(0, activation1->start_ns);
1718     EXPECT_EQ(kNotActive, activation1->state);
1719     EXPECT_EQ(ACTIVATE_ON_BOOT, activation1->activationType);
1720 
1721     EXPECT_EQ(metricsManager1->mAllAtomMatchingTrackers[1]->getId(),
1722               metric1ActivationTrigger2->atom_matcher_id());
1723     const auto& activation2 = metricProducer1->mEventActivationMap.at(1);
1724     EXPECT_EQ(200 * NS_PER_SEC, activation2->ttl_ns);
1725     EXPECT_EQ(0, activation2->start_ns);
1726     EXPECT_EQ(kNotActive, activation2->state);
1727     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation2->activationType);
1728 
1729     EXPECT_EQ(metricsManager1->mAllAtomMatchingTrackers[2]->getId(),
1730               metric2ActivationTrigger1->atom_matcher_id());
1731     const auto& activation3 = metricProducer2->mEventActivationMap.at(2);
1732     EXPECT_EQ(100 * NS_PER_SEC, activation3->ttl_ns);
1733     EXPECT_EQ(0, activation3->start_ns);
1734     EXPECT_EQ(kNotActive, activation3->state);
1735     EXPECT_EQ(ACTIVATE_ON_BOOT, activation3->activationType);
1736 
1737     EXPECT_EQ(metricsManager1->mAllAtomMatchingTrackers[3]->getId(),
1738               metric2ActivationTrigger2->atom_matcher_id());
1739     const auto& activation4 = metricProducer2->mEventActivationMap.at(3);
1740     EXPECT_EQ(200 * NS_PER_SEC, activation4->ttl_ns);
1741     EXPECT_EQ(0, activation4->start_ns);
1742     EXPECT_EQ(kNotActive, activation4->state);
1743     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation4->activationType);
1744     // }}}------------------------------------------------------------------------------
1745 
1746     // Trigger Activation 1 for Metric 1. Should activate on boot.
1747     // Trigger Activation 4 for Metric 2. Should activate immediately.
1748     int64_t configAddedTimeNs = metricsManager1->mLastReportTimeNs;
1749     std::vector<int> attributionUids = {111};
1750     std::vector<string> attributionTags = {"App1"};
1751     std::unique_ptr<LogEvent> event1 = CreateAcquireWakelockEvent(
1752             1 + configAddedTimeNs, attributionUids, attributionTags, "wl1");
1753     processor->OnLogEvent(event1.get());
1754 
1755     std::unique_ptr<LogEvent> event2 = CreateFinishScheduledJobEvent(
1756             2 + configAddedTimeNs, attributionUids, attributionTags, "finish1");
1757     processor->OnLogEvent(event2.get());
1758 
1759     // Metric 1 is not active; Activation 1 set to kActiveOnBoot
1760     // Metric 2 is active. Activation 4 set to kActive
1761     // Metric 3 is active.
1762     // {{{---------------------------------------------------------------------------
1763     EXPECT_FALSE(metricProducer1->isActive());
1764     EXPECT_EQ(0, activation1->start_ns);
1765     EXPECT_EQ(kActiveOnBoot, activation1->state);
1766     EXPECT_EQ(0, activation2->start_ns);
1767     EXPECT_EQ(kNotActive, activation2->state);
1768 
1769     EXPECT_TRUE(metricProducer2->isActive());
1770     EXPECT_EQ(0, activation3->start_ns);
1771     EXPECT_EQ(kNotActive, activation3->state);
1772     EXPECT_EQ(2 + configAddedTimeNs, activation4->start_ns);
1773     EXPECT_EQ(kActive, activation4->state);
1774 
1775     EXPECT_TRUE(metricProducer3->isActive());
1776     // }}}-----------------------------------------------------------------------------
1777 
1778     // Can't fake time with StatsService.
1779     // Lets get a time close to the system server death time and make sure it's sane.
1780     int64_t approximateSystemServerDeath = getElapsedRealtimeNs();
1781     EXPECT_TRUE(approximateSystemServerDeath > 2 + configAddedTimeNs);
1782     EXPECT_TRUE(approximateSystemServerDeath < NS_PER_SEC + configAddedTimeNs);
1783 
1784     // System server dies.
1785     service->statsCompanionServiceDiedImpl();
1786 
1787     // We should have a new metrics manager. Lets get it and ensure activation status is restored.
1788     // {{{---------------------------------------------------------------------------
1789     ASSERT_EQ(1, processor->mMetricsManagers.size());
1790     it = processor->mMetricsManagers.find(cfgKey1);
1791     EXPECT_TRUE(it != processor->mMetricsManagers.end());
1792     auto& metricsManager2 = it->second;
1793     EXPECT_TRUE(metricsManager2->isActive());
1794     ASSERT_EQ(3, metricsManager2->mAllMetricProducers.size());
1795 
1796     auto& metricProducer1001 = metricsManager2->mAllMetricProducers[0];
1797     EXPECT_EQ(metricId1, metricProducer1001->getMetricId());
1798     EXPECT_FALSE(metricProducer1001->isActive());
1799 
1800     auto& metricProducer1002 = metricsManager2->mAllMetricProducers[1];
1801     EXPECT_EQ(metricId2, metricProducer1002->getMetricId());
1802     EXPECT_TRUE(metricProducer1002->isActive());
1803 
1804     auto& metricProducer1003 = metricsManager2->mAllMetricProducers[2];
1805     EXPECT_EQ(metricId3, metricProducer1003->getMetricId());
1806     EXPECT_TRUE(metricProducer1003->isActive());
1807 
1808     // Check event activations.
1809     // Activation 1 is kActiveOnBoot.
1810     // Activation 2 and 3 are not active.
1811     // Activation 4 is active.
1812     ASSERT_EQ(metricsManager2->mAllAtomMatchingTrackers.size(), 4);
1813     EXPECT_EQ(metricsManager2->mAllAtomMatchingTrackers[0]->getId(),
1814               metric1ActivationTrigger1->atom_matcher_id());
1815     const auto& activation1001 = metricProducer1001->mEventActivationMap.at(0);
1816     EXPECT_EQ(100 * NS_PER_SEC, activation1001->ttl_ns);
1817     EXPECT_EQ(0, activation1001->start_ns);
1818     EXPECT_EQ(kActiveOnBoot, activation1001->state);
1819     EXPECT_EQ(ACTIVATE_ON_BOOT, activation1001->activationType);
1820 
1821     EXPECT_EQ(metricsManager2->mAllAtomMatchingTrackers[1]->getId(),
1822               metric1ActivationTrigger2->atom_matcher_id());
1823     const auto& activation1002 = metricProducer1001->mEventActivationMap.at(1);
1824     EXPECT_EQ(200 * NS_PER_SEC, activation1002->ttl_ns);
1825     EXPECT_EQ(0, activation1002->start_ns);
1826     EXPECT_EQ(kNotActive, activation1002->state);
1827     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation1002->activationType);
1828 
1829     EXPECT_EQ(metricsManager2->mAllAtomMatchingTrackers[2]->getId(),
1830               metric2ActivationTrigger1->atom_matcher_id());
1831     const auto& activation1003 = metricProducer1002->mEventActivationMap.at(2);
1832     EXPECT_EQ(100 * NS_PER_SEC, activation1003->ttl_ns);
1833     EXPECT_EQ(0, activation1003->start_ns);
1834     EXPECT_EQ(kNotActive, activation1003->state);
1835     EXPECT_EQ(ACTIVATE_ON_BOOT, activation1003->activationType);
1836 
1837     EXPECT_EQ(metricsManager2->mAllAtomMatchingTrackers[3]->getId(),
1838               metric2ActivationTrigger2->atom_matcher_id());
1839     const auto& activation1004 = metricProducer1002->mEventActivationMap.at(3);
1840     EXPECT_EQ(200 * NS_PER_SEC, activation1004->ttl_ns);
1841     EXPECT_EQ(2 + configAddedTimeNs, activation1004->start_ns);
1842     EXPECT_EQ(kActive, activation1004->state);
1843     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation1004->activationType);
1844     // }}}------------------------------------------------------------------------------
1845 
1846     // Clear the data stored on disk as a result of the system server death.
1847     vector<uint8_t> buffer;
1848     processor->onDumpReport(cfgKey1, configAddedTimeNs + NS_PER_SEC, false, true, ADB_DUMP, FAST,
1849                             &buffer);
1850 
1851     service->removeConfiguration(configId, uid);
1852     service->mProcessor->onDumpReport(cfgKey1, getElapsedRealtimeNs(),
1853                                       false /* include_current_bucket*/, true /* erase_data */,
1854                                       ADB_DUMP, NO_TIME_CONSTRAINTS, nullptr);
1855 }
1856 
TEST(StatsLogProcessorTest,LogEventFilterOnSetPrintLogs)1857 TEST(StatsLogProcessorTest, LogEventFilterOnSetPrintLogs) {
1858     sp<UidMap> m = new UidMap();
1859     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
1860     sp<AlarmMonitor> anomalyAlarmMonitor;
1861     sp<AlarmMonitor> periodicAlarmMonitor;
1862 
1863     std::shared_ptr<MockLogEventFilter> mockLogEventFilter = std::make_shared<MockLogEventFilter>();
1864     EXPECT_CALL(*mockLogEventFilter, setAtomIds(StatsLogProcessor::getDefaultAtomIdSet(), _))
1865             .Times(1);
1866     StatsLogProcessor p(
1867             m, pullerManager, anomalyAlarmMonitor, periodicAlarmMonitor, 0,
1868             [](const ConfigKey& key) { return true; },
1869             [](const int&, const vector<int64_t>&) { return true; },
1870             [](const ConfigKey&, const string&, const vector<int64_t>&) {}, mockLogEventFilter);
1871 
1872     Expectation filterSetFalse =
1873             EXPECT_CALL(*mockLogEventFilter, setFilteringEnabled(false)).Times(1);
1874     EXPECT_CALL(*mockLogEventFilter, setFilteringEnabled(true)).Times(1).After(filterSetFalse);
1875 
1876     p.setPrintLogs(true);
1877     p.setPrintLogs(false);
1878 }
1879 
TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid,LogHostUid)1880 TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid, LogHostUid) {
1881     int hostUid = 20;
1882     int isolatedUid = 30;
1883     uint64_t eventTimeNs = 12355;
1884     int atomId = 89;
1885     int field1 = 90;
1886     int field2 = 28;
1887     sp<MockUidMap> mockUidMap = makeMockUidMapForHosts({{hostUid, {isolatedUid}}});
1888 
1889     ConfigKey cfgKey;
1890     StatsdConfig config = MakeConfig(false);
1891     sp<StatsLogProcessor> processor =
1892             CreateStatsLogProcessor(1, 1, config, cfgKey, nullptr, 0, mockUidMap);
1893 
1894     shared_ptr<LogEvent> logEvent = makeUidLogEvent(atomId, eventTimeNs, hostUid, field1, field2);
1895 
1896     processor->OnLogEvent(logEvent.get());
1897 
1898     const vector<FieldValue>* actualFieldValues = &logEvent->getValues();
1899     ASSERT_EQ(3, actualFieldValues->size());
1900     EXPECT_EQ(hostUid, actualFieldValues->at(0).mValue.int_value);
1901     EXPECT_EQ(field1, actualFieldValues->at(1).mValue.int_value);
1902     EXPECT_EQ(field2, actualFieldValues->at(2).mValue.int_value);
1903 }
1904 
TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid,LogIsolatedUid)1905 TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid, LogIsolatedUid) {
1906     int hostUid = 20;
1907     int isolatedUid = 30;
1908     uint64_t eventTimeNs = 12355;
1909     int atomId = 89;
1910     int field1 = 90;
1911     int field2 = 28;
1912     sp<MockUidMap> mockUidMap = makeMockUidMapForHosts({{hostUid, {isolatedUid}}});
1913 
1914     ConfigKey cfgKey;
1915     StatsdConfig config = MakeConfig(false);
1916     sp<StatsLogProcessor> processor =
1917             CreateStatsLogProcessor(1, 1, config, cfgKey, nullptr, 0, mockUidMap);
1918 
1919     shared_ptr<LogEvent> logEvent =
1920             makeUidLogEvent(atomId, eventTimeNs, isolatedUid, field1, field2);
1921 
1922     processor->OnLogEvent(logEvent.get());
1923 
1924     const vector<FieldValue>* actualFieldValues = &logEvent->getValues();
1925     ASSERT_EQ(3, actualFieldValues->size());
1926     EXPECT_EQ(hostUid, actualFieldValues->at(0).mValue.int_value);
1927     EXPECT_EQ(field1, actualFieldValues->at(1).mValue.int_value);
1928     EXPECT_EQ(field2, actualFieldValues->at(2).mValue.int_value);
1929 }
1930 
TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid,LogThreeIsolatedUids)1931 TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid, LogThreeIsolatedUids) {
1932     int hostUid = 20;
1933     int isolatedUid = 30;
1934     int hostUid2 = 200;
1935     int isolatedUid2 = 300;
1936     int hostUid3 = 2000;
1937     int isolatedUid3 = 3000;
1938     uint64_t eventTimeNs = 12355;
1939     int atomId = 89;
1940     int field1 = 90;
1941     int field2 = 28;
1942     sp<MockUidMap> mockUidMap = makeMockUidMapForHosts(
1943             {{hostUid, {isolatedUid}}, {hostUid2, {isolatedUid2}}, {hostUid3, {isolatedUid3}}});
1944     ConfigKey cfgKey;
1945     StatsdConfig config = MakeConfig(false);
1946     sp<StatsLogProcessor> processor =
1947             CreateStatsLogProcessor(1, 1, config, cfgKey, nullptr, 0, mockUidMap);
1948 
1949     shared_ptr<LogEvent> logEvent = makeExtraUidsLogEvent(atomId, eventTimeNs, isolatedUid, field1,
1950                                                           field2, {isolatedUid2, isolatedUid3});
1951 
1952     processor->OnLogEvent(logEvent.get());
1953 
1954     const vector<FieldValue>* actualFieldValues = &logEvent->getValues();
1955     ASSERT_EQ(5, actualFieldValues->size());
1956     EXPECT_EQ(hostUid, actualFieldValues->at(0).mValue.int_value);
1957     EXPECT_EQ(field1, actualFieldValues->at(1).mValue.int_value);
1958     EXPECT_EQ(field2, actualFieldValues->at(2).mValue.int_value);
1959     EXPECT_EQ(hostUid2, actualFieldValues->at(3).mValue.int_value);
1960     EXPECT_EQ(hostUid3, actualFieldValues->at(4).mValue.int_value);
1961 }
1962 
TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid,LogHostUidAttributionChain)1963 TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid, LogHostUidAttributionChain) {
1964     int hostUid = 20;
1965     int isolatedUid = 30;
1966     uint64_t eventTimeNs = 12355;
1967     int atomId = 89;
1968     int field1 = 90;
1969     int field2 = 28;
1970     sp<MockUidMap> mockUidMap = makeMockUidMapForHosts({{hostUid, {isolatedUid}}});
1971 
1972     ConfigKey cfgKey;
1973     StatsdConfig config = MakeConfig(false);
1974     sp<StatsLogProcessor> processor =
1975             CreateStatsLogProcessor(1, 1, config, cfgKey, nullptr, 0, mockUidMap);
1976 
1977     shared_ptr<LogEvent> logEvent = makeAttributionLogEvent(atomId, eventTimeNs, {hostUid, 200},
1978                                                             {"tag1", "tag2"}, field1, field2);
1979 
1980     processor->OnLogEvent(logEvent.get());
1981 
1982     const vector<FieldValue>* actualFieldValues = &logEvent->getValues();
1983     ASSERT_EQ(6, actualFieldValues->size());
1984     EXPECT_EQ(hostUid, actualFieldValues->at(0).mValue.int_value);
1985     EXPECT_EQ("tag1", actualFieldValues->at(1).mValue.str_value);
1986     EXPECT_EQ(200, actualFieldValues->at(2).mValue.int_value);
1987     EXPECT_EQ("tag2", actualFieldValues->at(3).mValue.str_value);
1988     EXPECT_EQ(field1, actualFieldValues->at(4).mValue.int_value);
1989     EXPECT_EQ(field2, actualFieldValues->at(5).mValue.int_value);
1990 }
1991 
TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid,LogIsolatedUidAttributionChain)1992 TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid, LogIsolatedUidAttributionChain) {
1993     int hostUid = 20;
1994     int isolatedUid = 30;
1995     uint64_t eventTimeNs = 12355;
1996     int atomId = 89;
1997     int field1 = 90;
1998     int field2 = 28;
1999     sp<MockUidMap> mockUidMap = makeMockUidMapForHosts({{hostUid, {isolatedUid}}});
2000     ConfigKey cfgKey;
2001     StatsdConfig config = MakeConfig(false);
2002     sp<StatsLogProcessor> processor =
2003             CreateStatsLogProcessor(1, 1, config, cfgKey, nullptr, 0, mockUidMap);
2004 
2005     shared_ptr<LogEvent> logEvent = makeAttributionLogEvent(atomId, eventTimeNs, {isolatedUid, 200},
2006                                                             {"tag1", "tag2"}, field1, field2);
2007 
2008     processor->OnLogEvent(logEvent.get());
2009 
2010     const vector<FieldValue>* actualFieldValues = &logEvent->getValues();
2011     ASSERT_EQ(6, actualFieldValues->size());
2012     EXPECT_EQ(hostUid, actualFieldValues->at(0).mValue.int_value);
2013     EXPECT_EQ("tag1", actualFieldValues->at(1).mValue.str_value);
2014     EXPECT_EQ(200, actualFieldValues->at(2).mValue.int_value);
2015     EXPECT_EQ("tag2", actualFieldValues->at(3).mValue.str_value);
2016     EXPECT_EQ(field1, actualFieldValues->at(4).mValue.int_value);
2017     EXPECT_EQ(field2, actualFieldValues->at(5).mValue.int_value);
2018 }
2019 
2020 /* *
2021  * Test cases for repeated uid fields:
2022  * - empty field
2023  * - single host uid
2024  * - single isolated uid
2025  * - multiple host uids
2026  * - multiple isolated uids
2027  * - multiple host and isolated uids
2028  */
TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid,LogRepeatedUidField)2029 TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid, LogRepeatedUidField) {
2030     int hostUid1 = 21;
2031     int hostUid2 = 22;
2032     int isolatedUid1 = 31;
2033     int isolatedUid2 = 32;
2034     uint64_t eventTimeNs = 12355;
2035     int atomId = 89;
2036     int field1 = 90;
2037     int field2 = 28;
2038     sp<MockUidMap> mockUidMap =
2039             makeMockUidMapForHosts({{hostUid1, {isolatedUid1}}, {hostUid2, {isolatedUid2}}});
2040 
2041     ConfigKey cfgKey;
2042     StatsdConfig config = MakeConfig(false);
2043     sp<StatsLogProcessor> processor =
2044             CreateStatsLogProcessor(1, 1, config, cfgKey, nullptr, 0, mockUidMap);
2045 
2046     // Empty repeated uid field.
2047     shared_ptr<LogEvent> logEvent = makeRepeatedUidLogEvent(atomId, eventTimeNs, {});
2048     processor->OnLogEvent(logEvent.get());
2049 
2050     const vector<FieldValue>* actualFieldValues = &logEvent->getValues();
2051     ASSERT_EQ(0, actualFieldValues->size());
2052 
2053     // Single host uid.
2054     logEvent = makeRepeatedUidLogEvent(atomId, eventTimeNs, {hostUid1});
2055     processor->OnLogEvent(logEvent.get());
2056 
2057     actualFieldValues = &logEvent->getValues();
2058     ASSERT_EQ(1, actualFieldValues->size());
2059     EXPECT_EQ(hostUid1, actualFieldValues->at(0).mValue.int_value);
2060 
2061     // Single isolated uid.
2062     logEvent = makeRepeatedUidLogEvent(atomId, eventTimeNs, {isolatedUid1});
2063     processor->OnLogEvent(logEvent.get());
2064 
2065     actualFieldValues = &logEvent->getValues();
2066     ASSERT_EQ(1, actualFieldValues->size());
2067     EXPECT_EQ(hostUid1, actualFieldValues->at(0).mValue.int_value);
2068 
2069     // Multiple host uids.
2070     logEvent = makeRepeatedUidLogEvent(atomId, eventTimeNs, {hostUid1, hostUid2});
2071     processor->OnLogEvent(logEvent.get());
2072 
2073     actualFieldValues = &logEvent->getValues();
2074     ASSERT_EQ(2, actualFieldValues->size());
2075     EXPECT_EQ(hostUid1, actualFieldValues->at(0).mValue.int_value);
2076     EXPECT_EQ(hostUid2, actualFieldValues->at(1).mValue.int_value);
2077 
2078     // Multiple isolated uids.
2079     logEvent = makeRepeatedUidLogEvent(atomId, eventTimeNs, {isolatedUid1, isolatedUid2});
2080     processor->OnLogEvent(logEvent.get());
2081 
2082     actualFieldValues = &logEvent->getValues();
2083     ASSERT_EQ(2, actualFieldValues->size());
2084     EXPECT_EQ(hostUid1, actualFieldValues->at(0).mValue.int_value);
2085     EXPECT_EQ(hostUid2, actualFieldValues->at(1).mValue.int_value);
2086 
2087     // Multiple host and isolated uids.
2088     logEvent = makeRepeatedUidLogEvent(atomId, eventTimeNs,
2089                                        {isolatedUid1, hostUid2, isolatedUid2, hostUid1});
2090     processor->OnLogEvent(logEvent.get());
2091 
2092     actualFieldValues = &logEvent->getValues();
2093     ASSERT_EQ(4, actualFieldValues->size());
2094     EXPECT_EQ(hostUid1, actualFieldValues->at(0).mValue.int_value);
2095     EXPECT_EQ(hostUid2, actualFieldValues->at(1).mValue.int_value);
2096     EXPECT_EQ(hostUid2, actualFieldValues->at(2).mValue.int_value);
2097     EXPECT_EQ(hostUid1, actualFieldValues->at(3).mValue.int_value);
2098 }
2099 
TEST(StatsLogProcessorTest,TestDumpReportWithoutErasingDataDoesNotUpdateTimestamp)2100 TEST(StatsLogProcessorTest, TestDumpReportWithoutErasingDataDoesNotUpdateTimestamp) {
2101     int hostUid = 20;
2102     int isolatedUid = 30;
2103     sp<MockUidMap> mockUidMap = makeMockUidMapForHosts({{hostUid, {isolatedUid}}});
2104     ConfigKey key(3, 4);
2105 
2106     // TODO: All tests should not persist state on disk. This removes any reports that were present.
2107     ProtoOutputStream proto;
2108     StorageManager::appendConfigMetricsReport(key, &proto, /*erase data=*/true, /*isAdb=*/false);
2109 
2110     StatsdConfig config = MakeConfig(false);
2111     sp<StatsLogProcessor> processor =
2112             CreateStatsLogProcessor(1, 1, config, key, nullptr, 0, mockUidMap);
2113     vector<uint8_t> bytes;
2114 
2115     int64_t dumpTime1Ns = 1 * NS_PER_SEC;
2116     processor->onDumpReport(key, dumpTime1Ns, false /* include_current_bucket */,
2117             true /* erase_data */, ADB_DUMP, FAST, &bytes);
2118 
2119     ConfigMetricsReportList output;
2120     output.ParseFromArray(bytes.data(), bytes.size());
2121     EXPECT_EQ(output.reports_size(), 1);
2122     EXPECT_EQ(output.reports(0).current_report_elapsed_nanos(), dumpTime1Ns);
2123 
2124     int64_t dumpTime2Ns = 5 * NS_PER_SEC;
2125     processor->onDumpReport(key, dumpTime2Ns, false /* include_current_bucket */,
2126             false /* erase_data */, ADB_DUMP, FAST, &bytes);
2127 
2128     // Check that the dump report without clearing data is successful.
2129     output.ParseFromArray(bytes.data(), bytes.size());
2130     EXPECT_EQ(output.reports_size(), 1);
2131     EXPECT_EQ(output.reports(0).current_report_elapsed_nanos(), dumpTime2Ns);
2132     EXPECT_EQ(output.reports(0).last_report_elapsed_nanos(), dumpTime1Ns);
2133 
2134     int64_t dumpTime3Ns = 10 * NS_PER_SEC;
2135     processor->onDumpReport(key, dumpTime3Ns, false /* include_current_bucket */,
2136             true /* erase_data */, ADB_DUMP, FAST, &bytes);
2137 
2138     // Check that the previous dump report that didn't clear data did not overwrite the first dump's
2139     // timestamps.
2140     output.ParseFromArray(bytes.data(), bytes.size());
2141     EXPECT_EQ(output.reports_size(), 1);
2142     EXPECT_EQ(output.reports(0).current_report_elapsed_nanos(), dumpTime3Ns);
2143     EXPECT_EQ(output.reports(0).last_report_elapsed_nanos(), dumpTime1Ns);
2144 }
2145 
TEST(StatsLogProcessorTest,TestDataCorruptedEnum)2146 TEST(StatsLogProcessorTest, TestDataCorruptedEnum) {
2147     ConfigKey cfgKey;
2148     StatsdConfig config = MakeConfig(true);
2149     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(1, 1, config, cfgKey);
2150 
2151     StatsdStats::getInstance().noteEventQueueOverflow(/*oldestEventTimestampNs=*/0, /*atomId=*/100,
2152                                                       /*isSkipped=*/false);
2153     StatsdStats::getInstance().noteLogLost(/*wallClockTimeSec=*/0, /*count=*/1, /*lastError=*/0,
2154                                            /*lastTag=*/0, /*uid=*/0, /*pid=*/0);
2155     vector<uint8_t> bytes;
2156     ConfigMetricsReportList output;
2157     processor->onDumpReport(cfgKey, 3, true, true, ADB_DUMP, FAST, &bytes);
2158 
2159     output.ParseFromArray(bytes.data(), bytes.size());
2160     ASSERT_EQ(output.reports_size(), 1);
2161     ASSERT_EQ(output.reports(0).data_corrupted_reason().size(), 2);
2162     EXPECT_EQ(output.reports(0).data_corrupted_reason(0), DATA_CORRUPTED_EVENT_QUEUE_OVERFLOW);
2163     EXPECT_EQ(output.reports(0).data_corrupted_reason(1), DATA_CORRUPTED_SOCKET_LOSS);
2164 }
2165 
2166 class StatsLogProcessorTestRestricted : public Test {
2167 protected:
2168     const ConfigKey mConfigKey = ConfigKey(1, 12345);
SetUp()2169     void SetUp() override {
2170         if (!isAtLeastU()) {
2171             GTEST_SKIP();
2172         }
2173     }
TearDown()2174     void TearDown() override {
2175         if (!isAtLeastU()) {
2176             GTEST_SKIP();
2177         }
2178         FlagProvider::getInstance().resetOverrides();
2179         StorageManager::deleteAllFiles(STATS_DATA_DIR);
2180         dbutils::deleteDb(mConfigKey);
2181     }
2182 };
2183 
TEST_F(StatsLogProcessorTestRestricted,TestInconsistentRestrictedMetricsConfigUpdate)2184 TEST_F(StatsLogProcessorTestRestricted, TestInconsistentRestrictedMetricsConfigUpdate) {
2185     ConfigKey key(3, 4);
2186     StatsdConfig config = makeRestrictedConfig(true);
2187     config.set_restricted_metrics_delegate_package_name("rm_package");
2188 
2189     sp<UidMap> m = new UidMap();
2190     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
2191     UidData uidData;
2192     *uidData.add_app_info() = createApplicationInfo(/*uid*/ 1, /*version*/ 1, "v1", "p1");
2193     *uidData.add_app_info() = createApplicationInfo(/*uid*/ 2, /*version*/ 2, "v2", "p2");
2194     m->updateMap(1, uidData);
2195     sp<AlarmMonitor> anomalyAlarmMonitor;
2196     sp<AlarmMonitor> subscriberAlarmMonitor;
2197     std::shared_ptr<MockLogEventFilter> mockLogEventFilter = std::make_shared<MockLogEventFilter>();
2198     EXPECT_CALL(*mockLogEventFilter, setAtomIds(StatsLogProcessor::getDefaultAtomIdSet(), _))
2199             .Times(1);
2200     StatsLogProcessor p(
2201             m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
2202             [](const ConfigKey& key) { return true; },
2203             [](const int&, const vector<int64_t>&) { return true; },
2204             [](const ConfigKey&, const string&, const vector<int64_t>&) {}, mockLogEventFilter);
2205 
2206     // new newConfig will be the same as config
2207     const LogEventFilter::AtomIdSet atomIdsList = CreateAtomIdSetFromConfig(config);
2208     EXPECT_CALL(*mockLogEventFilter, setAtomIds(atomIdsList, &p)).Times(2);
2209 
2210     p.OnConfigUpdated(0, key, config);
2211 
2212     EXPECT_EQ(1, p.mMetricsManagers.size());
2213     EXPECT_NE(p.mMetricsManagers.find(key), p.mMetricsManagers.end());
2214     sp<MetricsManager> oldMetricsManager = p.mMetricsManagers.find(key)->second;
2215 
2216     StatsdConfig newConfig = makeRestrictedConfig(true);
2217     newConfig.clear_restricted_metrics_delegate_package_name();
2218     p.OnConfigUpdated(/*timestampNs=*/0, key, newConfig);
2219 
2220     ASSERT_NE(p.mMetricsManagers.find(key)->second, oldMetricsManager);
2221 }
2222 
TEST_F(StatsLogProcessorTestRestricted,TestRestrictedLogEventNotPassed)2223 TEST_F(StatsLogProcessorTestRestricted, TestRestrictedLogEventNotPassed) {
2224     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(
2225             /*timeBaseNs=*/1, /*currentTimeNs=*/1, StatsdConfig(), mConfigKey);
2226     ConfigKey key(3, 4);
2227     sp<MockMetricsManager> metricsManager = new MockMetricsManager(mConfigKey);
2228     EXPECT_CALL(*metricsManager, onLogEvent).Times(0);
2229 
2230     processor->mMetricsManagers[mConfigKey] = metricsManager;
2231     EXPECT_FALSE(processor->mMetricsManagers[mConfigKey]->hasRestrictedMetricsDelegate());
2232 
2233     unique_ptr<LogEvent> event = CreateRestrictedLogEvent(123);
2234     EXPECT_TRUE(event->isValid());
2235     EXPECT_TRUE(event->isRestricted());
2236     processor->OnLogEvent(event.get());
2237 }
2238 
TEST_F(StatsLogProcessorTestRestricted,TestRestrictedLogEventPassed)2239 TEST_F(StatsLogProcessorTestRestricted, TestRestrictedLogEventPassed) {
2240     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(
2241             /*timeBaseNs=*/1, /*currentTimeNs=*/1, StatsdConfig(), mConfigKey);
2242     sp<MockRestrictedMetricsManager> metricsManager = new MockRestrictedMetricsManager(mConfigKey);
2243     EXPECT_CALL(*metricsManager, onLogEvent).Times(1);
2244 
2245     processor->mMetricsManagers[mConfigKey] = metricsManager;
2246     EXPECT_TRUE(processor->mMetricsManagers[mConfigKey]->hasRestrictedMetricsDelegate());
2247 
2248     unique_ptr<LogEvent> event = CreateRestrictedLogEvent(123);
2249     EXPECT_TRUE(event->isValid());
2250     EXPECT_TRUE(event->isRestricted());
2251     processor->OnLogEvent(event.get());
2252 }
2253 
TEST_F(StatsLogProcessorTestRestricted,RestrictedMetricsManagerOnDumpReportNotCalled)2254 TEST_F(StatsLogProcessorTestRestricted, RestrictedMetricsManagerOnDumpReportNotCalled) {
2255     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(
2256             /*timeBaseNs=*/1, /*currentTimeNs=*/1, makeRestrictedConfig(/*includeMetric=*/true),
2257             mConfigKey);
2258     sp<MockRestrictedMetricsManager> metricsManager = new MockRestrictedMetricsManager(mConfigKey);
2259     EXPECT_CALL(*metricsManager, onDumpReport).Times(0);
2260 
2261     processor->mMetricsManagers[mConfigKey] = metricsManager;
2262     EXPECT_TRUE(processor->mMetricsManagers[mConfigKey]->hasRestrictedMetricsDelegate());
2263 
2264     vector<uint8_t> buffer;
2265     processor->onConfigMetricsReportLocked(mConfigKey, /*dumpTimeStampNs=*/1, /*wallClockNs=*/0,
2266                                            /*include_current_partial_bucket=*/true,
2267                                            /*erase_data=*/true, GET_DATA_CALLED, FAST,
2268                                            /*dataSavedToDisk=*/true, &buffer);
2269 }
2270 
TEST_F(StatsLogProcessorTestRestricted,RestrictedMetricFlushIfReachMemoryLimit)2271 TEST_F(StatsLogProcessorTestRestricted, RestrictedMetricFlushIfReachMemoryLimit) {
2272     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(
2273             /*timeBaseNs=*/1, /*currentTimeNs=*/1, makeRestrictedConfig(/*includeMetric=*/true),
2274             mConfigKey);
2275     sp<MockRestrictedMetricsManager> metricsManager = new MockRestrictedMetricsManager(mConfigKey);
2276     EXPECT_CALL(*metricsManager, flushRestrictedData).Times(1);
2277     EXPECT_CALL(*metricsManager, byteSize)
2278             .Times(1)
2279             .WillOnce(Return(StatsdStats::kBytesPerRestrictedConfigTriggerFlush + 1));
2280 
2281     processor->mMetricsManagers[mConfigKey] = metricsManager;
2282     EXPECT_TRUE(processor->mMetricsManagers[mConfigKey]->hasRestrictedMetricsDelegate());
2283 
2284     processor->flushIfNecessaryLocked(mConfigKey, *metricsManager);
2285 }
2286 
TEST_F(StatsLogProcessorTestRestricted,RestrictedMetricNotFlushIfNotReachMemoryLimit)2287 TEST_F(StatsLogProcessorTestRestricted, RestrictedMetricNotFlushIfNotReachMemoryLimit) {
2288     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(
2289             /*timeBaseNs=*/1, /*currentTimeNs=*/1, makeRestrictedConfig(/*includeMetric=*/true),
2290             mConfigKey);
2291     sp<MockRestrictedMetricsManager> metricsManager = new MockRestrictedMetricsManager(mConfigKey);
2292     EXPECT_CALL(*metricsManager, flushRestrictedData).Times(0);
2293     EXPECT_CALL(*metricsManager, byteSize)
2294             .Times(1)
2295             .WillOnce(Return(StatsdStats::kBytesPerRestrictedConfigTriggerFlush - 1));
2296 
2297     processor->mMetricsManagers[mConfigKey] = metricsManager;
2298     EXPECT_TRUE(processor->mMetricsManagers[mConfigKey]->hasRestrictedMetricsDelegate());
2299 
2300     processor->flushIfNecessaryLocked(mConfigKey, *metricsManager);
2301 }
2302 
TEST_F(StatsLogProcessorTestRestricted,NonRestrictedMetricsManagerOnDumpReportCalled)2303 TEST_F(StatsLogProcessorTestRestricted, NonRestrictedMetricsManagerOnDumpReportCalled) {
2304     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(
2305             /*timeBaseNs=*/1, /*currentTimeNs=*/1, MakeConfig(/*includeMetric=*/true), mConfigKey);
2306     sp<MockMetricsManager> metricsManager = new MockMetricsManager(mConfigKey);
2307     EXPECT_CALL(*metricsManager, onDumpReport).Times(1);
2308 
2309     processor->mMetricsManagers[mConfigKey] = metricsManager;
2310     EXPECT_FALSE(processor->mMetricsManagers[mConfigKey]->hasRestrictedMetricsDelegate());
2311 
2312     vector<uint8_t> buffer;
2313     processor->onConfigMetricsReportLocked(mConfigKey, /*dumpTimeStampNs=*/1, /*wallClockNs=*/0,
2314                                            /*include_current_partial_bucket=*/true,
2315                                            /*erase_data=*/true, GET_DATA_CALLED, FAST,
2316                                            /*dataSavedToDisk=*/true, &buffer);
2317 }
2318 
TEST_F(StatsLogProcessorTestRestricted,RestrictedMetricOnDumpReportEmpty)2319 TEST_F(StatsLogProcessorTestRestricted, RestrictedMetricOnDumpReportEmpty) {
2320     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(
2321             /*timeBaseNs=*/1, /*currentTimeNs=*/1, makeRestrictedConfig(/*includeMetric=*/true),
2322             mConfigKey);
2323     ProtoOutputStream proto;
2324     processor->onDumpReport(mConfigKey, /*dumpTimeStampNs=*/1, /*wallClockNs=*/2,
2325                             /*include_current_partial_bucket=*/true, /*erase_data=*/true,
2326                             DEVICE_SHUTDOWN, FAST, &proto);
2327     ASSERT_EQ(proto.size(), 0);
2328 }
2329 
TEST_F(StatsLogProcessorTestRestricted,NonRestrictedMetricOnDumpReportNotEmpty)2330 TEST_F(StatsLogProcessorTestRestricted, NonRestrictedMetricOnDumpReportNotEmpty) {
2331     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(
2332             /*timeBaseNs=*/1, /*currentTimeNs=*/1, MakeConfig(/*includeMetric=*/true), mConfigKey);
2333 
2334     ProtoOutputStream proto;
2335     processor->onDumpReport(mConfigKey, /*dumpTimeStampNs=*/1, /*wallClockNs=*/2,
2336                             /*include_current_partial_bucket=*/true, /*erase_data=*/true,
2337                             DEVICE_SHUTDOWN, FAST, &proto);
2338     ASSERT_NE(proto.size(), 0);
2339 }
2340 
TEST_F(StatsLogProcessorTestRestricted,RestrictedMetricNotWriteToDisk)2341 TEST_F(StatsLogProcessorTestRestricted, RestrictedMetricNotWriteToDisk) {
2342     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(
2343             /*timeBaseNs=*/1, /*currentTimeNs=*/1, makeRestrictedConfig(/*includeMetric=*/true),
2344             mConfigKey);
2345 
2346     processor->WriteDataToDiskLocked(mConfigKey, /*timestampNs=*/0, /*wallClockNs=*/0,
2347                                      CONFIG_UPDATED, FAST);
2348 
2349     ASSERT_FALSE(StorageManager::hasConfigMetricsReport(mConfigKey));
2350 }
2351 
TEST_F(StatsLogProcessorTestRestricted,NonRestrictedMetricWriteToDisk)2352 TEST_F(StatsLogProcessorTestRestricted, NonRestrictedMetricWriteToDisk) {
2353     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(
2354             /*timeBaseNs=*/1, /*currentTimeNs=*/1, MakeConfig(true), mConfigKey);
2355 
2356     processor->WriteDataToDiskLocked(mConfigKey, /*timestampNs=*/0, /*wallClockNs=*/0,
2357                                      CONFIG_UPDATED, FAST);
2358 
2359     ASSERT_TRUE(StorageManager::hasConfigMetricsReport(mConfigKey));
2360 }
2361 
2362 #else
2363 GTEST_LOG_(INFO) << "This test does nothing.\n";
2364 #endif
2365 
2366 }  // namespace statsd
2367 }  // namespace os
2368 }  // namespace android
2369