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 <gmock/gmock.h>
18 #include <gtest/gtest.h>
19 #include <stdio.h>
20 
21 #include "StatsService.h"
22 #include "config/ConfigKey.h"
23 #include "frameworks/base/cmds/statsd/src/stats_log.pb.h"
24 #include "frameworks/base/cmds/statsd/src/statsd_config.pb.h"
25 #include "guardrail/StatsdStats.h"
26 #include "logd/LogEvent.h"
27 #include "packages/UidMap.h"
28 #include "statslog_statsdtest.h"
29 #include "storage/StorageManager.h"
30 #include "tests/statsd_test_util.h"
31 
32 using namespace android;
33 using namespace testing;
34 using ::ndk::SharedRefBase;
35 using std::shared_ptr;
36 
37 namespace android {
38 namespace os {
39 namespace statsd {
40 
41 using android::util::ProtoOutputStream;
42 
43 #ifdef __ANDROID__
44 
45 /**
46  * Mock MetricsManager (ByteSize() is called).
47  */
48 class MockMetricsManager : public MetricsManager {
49 public:
MockMetricsManager()50     MockMetricsManager()
51         : MetricsManager(ConfigKey(1, 12345), StatsdConfig(), 1000, 1000, new UidMap(),
52                          new StatsPullerManager(),
53                          new AlarmMonitor(10,
54                                           [](const shared_ptr<IStatsCompanionService>&, int64_t) {},
__anon2030b8940202(const shared_ptr<IStatsCompanionService>&) 55                                           [](const shared_ptr<IStatsCompanionService>&) {}),
56                          new AlarmMonitor(10,
__anon2030b8940302(const shared_ptr<IStatsCompanionService>&, int64_t) 57                                           [](const shared_ptr<IStatsCompanionService>&, int64_t) {},
__anon2030b8940402(const shared_ptr<IStatsCompanionService>&) 58                                           [](const shared_ptr<IStatsCompanionService>&) {})) {
59     }
60 
61     MOCK_METHOD0(byteSize, size_t());
62 
63     MOCK_METHOD1(dropData, void(const int64_t dropTimeNs));
64 };
65 
TEST(StatsLogProcessorTest,TestRateLimitByteSize)66 TEST(StatsLogProcessorTest, TestRateLimitByteSize) {
67     sp<UidMap> m = new UidMap();
68     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
69     sp<AlarmMonitor> anomalyAlarmMonitor;
70     sp<AlarmMonitor> periodicAlarmMonitor;
71     // Construct the processor with a dummy sendBroadcast function that does nothing.
72     StatsLogProcessor p(m, pullerManager, anomalyAlarmMonitor, periodicAlarmMonitor, 0,
73                         [](const ConfigKey& key) { return true; },
74                         [](const int&, const vector<int64_t>&) {return true;});
75 
76     MockMetricsManager mockMetricsManager;
77 
78     ConfigKey key(100, 12345);
79     // Expect only the first flush to trigger a check for byte size since the last two are
80     // rate-limited.
81     EXPECT_CALL(mockMetricsManager, byteSize()).Times(1);
82     p.flushIfNecessaryLocked(key, mockMetricsManager);
83     p.flushIfNecessaryLocked(key, mockMetricsManager);
84     p.flushIfNecessaryLocked(key, mockMetricsManager);
85 }
86 
TEST(StatsLogProcessorTest,TestRateLimitBroadcast)87 TEST(StatsLogProcessorTest, TestRateLimitBroadcast) {
88     sp<UidMap> m = new UidMap();
89     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
90     sp<AlarmMonitor> anomalyAlarmMonitor;
91     sp<AlarmMonitor> subscriberAlarmMonitor;
92     int broadcastCount = 0;
93     StatsLogProcessor p(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
94                         [&broadcastCount](const ConfigKey& key) {
95                             broadcastCount++;
96                             return true;
97                         },
98                         [](const int&, const vector<int64_t>&) {return true;});
99 
100     MockMetricsManager mockMetricsManager;
101 
102     ConfigKey key(100, 12345);
103     EXPECT_CALL(mockMetricsManager, byteSize())
104             .Times(1)
105             .WillRepeatedly(::testing::Return(int(
106                     StatsdStats::kMaxMetricsBytesPerConfig * .95)));
107 
108     // Expect only one broadcast despite always returning a size that should trigger broadcast.
109     p.flushIfNecessaryLocked(key, mockMetricsManager);
110     EXPECT_EQ(1, broadcastCount);
111 
112     // b/73089712
113     // This next call to flush should not trigger a broadcast.
114     // p.mLastByteSizeTimes.clear();  // Force another check for byte size.
115     // p.flushIfNecessaryLocked(2, key, mockMetricsManager);
116     // EXPECT_EQ(1, broadcastCount);
117 }
118 
TEST(StatsLogProcessorTest,TestDropWhenByteSizeTooLarge)119 TEST(StatsLogProcessorTest, TestDropWhenByteSizeTooLarge) {
120     sp<UidMap> m = new UidMap();
121     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
122     sp<AlarmMonitor> anomalyAlarmMonitor;
123     sp<AlarmMonitor> subscriberAlarmMonitor;
124     int broadcastCount = 0;
125     StatsLogProcessor p(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
126                         [&broadcastCount](const ConfigKey& key) {
127                             broadcastCount++;
128                             return true;
129                         },
130                         [](const int&, const vector<int64_t>&) {return true;});
131 
132     MockMetricsManager mockMetricsManager;
133 
134     ConfigKey key(100, 12345);
135     EXPECT_CALL(mockMetricsManager, byteSize())
136             .Times(1)
137             .WillRepeatedly(::testing::Return(int(StatsdStats::kMaxMetricsBytesPerConfig * 1.2)));
138 
139     EXPECT_CALL(mockMetricsManager, dropData(_)).Times(1);
140 
141     // Expect to call the onDumpReport and skip the broadcast.
142     p.flushIfNecessaryLocked(key, mockMetricsManager);
143     EXPECT_EQ(0, broadcastCount);
144 }
145 
MakeConfig(bool includeMetric)146 StatsdConfig MakeConfig(bool includeMetric) {
147     StatsdConfig config;
148     config.add_allowed_log_source("AID_ROOT");  // LogEvent defaults to UID of root.
149 
150     if (includeMetric) {
151         auto appCrashMatcher = CreateProcessCrashAtomMatcher();
152         *config.add_atom_matcher() = appCrashMatcher;
153         auto countMetric = config.add_count_metric();
154         countMetric->set_id(StringToId("AppCrashes"));
155         countMetric->set_what(appCrashMatcher.id());
156         countMetric->set_bucket(FIVE_MINUTES);
157     }
158     return config;
159 }
160 
TEST(StatsLogProcessorTest,TestUidMapHasSnapshot)161 TEST(StatsLogProcessorTest, TestUidMapHasSnapshot) {
162     // Setup simple config key corresponding to empty config.
163     sp<UidMap> m = new UidMap();
164     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
165     m->updateMap(1, {1, 2}, {1, 2}, {String16("v1"), String16("v2")},
166                  {String16("p1"), String16("p2")}, {String16(""), String16("")});
167     sp<AlarmMonitor> anomalyAlarmMonitor;
168     sp<AlarmMonitor> subscriberAlarmMonitor;
169     int broadcastCount = 0;
170     StatsLogProcessor p(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
171                         [&broadcastCount](const ConfigKey& key) {
172                             broadcastCount++;
173                             return true;
174                         },
175                         [](const int&, const vector<int64_t>&) {return true;});
176     ConfigKey key(3, 4);
177     StatsdConfig config = MakeConfig(true);
178     p.OnConfigUpdated(0, key, config);
179 
180     // Expect to get no metrics, but snapshot specified above in uidmap.
181     vector<uint8_t> bytes;
182     p.onDumpReport(key, 1, false, true, ADB_DUMP, FAST, &bytes);
183 
184     ConfigMetricsReportList output;
185     output.ParseFromArray(bytes.data(), bytes.size());
186     EXPECT_TRUE(output.reports_size() > 0);
187     auto uidmap = output.reports(0).uid_map();
188     EXPECT_TRUE(uidmap.snapshots_size() > 0);
189     ASSERT_EQ(2, uidmap.snapshots(0).package_info_size());
190 }
191 
TEST(StatsLogProcessorTest,TestEmptyConfigHasNoUidMap)192 TEST(StatsLogProcessorTest, TestEmptyConfigHasNoUidMap) {
193     // Setup simple config key corresponding to empty config.
194     sp<UidMap> m = new UidMap();
195     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
196     m->updateMap(1, {1, 2}, {1, 2}, {String16("v1"), String16("v2")},
197                  {String16("p1"), String16("p2")}, {String16(""), String16("")});
198     sp<AlarmMonitor> anomalyAlarmMonitor;
199     sp<AlarmMonitor> subscriberAlarmMonitor;
200     int broadcastCount = 0;
201     StatsLogProcessor p(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
202                         [&broadcastCount](const ConfigKey& key) {
203                             broadcastCount++;
204                             return true;
205                         },
206                         [](const int&, const vector<int64_t>&) {return true;});
207     ConfigKey key(3, 4);
208     StatsdConfig config = MakeConfig(false);
209     p.OnConfigUpdated(0, key, config);
210 
211     // Expect to get no metrics, but snapshot specified above in uidmap.
212     vector<uint8_t> bytes;
213     p.onDumpReport(key, 1, false, true, ADB_DUMP, FAST, &bytes);
214 
215     ConfigMetricsReportList output;
216     output.ParseFromArray(bytes.data(), bytes.size());
217     EXPECT_TRUE(output.reports_size() > 0);
218     EXPECT_FALSE(output.reports(0).has_uid_map());
219 }
220 
TEST(StatsLogProcessorTest,TestReportIncludesSubConfig)221 TEST(StatsLogProcessorTest, TestReportIncludesSubConfig) {
222     // Setup simple config key corresponding to empty config.
223     sp<UidMap> m = new UidMap();
224     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
225     sp<AlarmMonitor> anomalyAlarmMonitor;
226     sp<AlarmMonitor> subscriberAlarmMonitor;
227     int broadcastCount = 0;
228     StatsLogProcessor p(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
229                         [&broadcastCount](const ConfigKey& key) {
230                             broadcastCount++;
231                             return true;
232                         },
233                         [](const int&, const vector<int64_t>&) {return true;});
234     ConfigKey key(3, 4);
235     StatsdConfig config;
236     auto annotation = config.add_annotation();
237     annotation->set_field_int64(1);
238     annotation->set_field_int32(2);
239     config.add_allowed_log_source("AID_ROOT");
240     p.OnConfigUpdated(1, key, config);
241 
242     // Expect to get no metrics, but snapshot specified above in uidmap.
243     vector<uint8_t> bytes;
244     p.onDumpReport(key, 1, false, true, ADB_DUMP, FAST, &bytes);
245 
246     ConfigMetricsReportList output;
247     output.ParseFromArray(bytes.data(), bytes.size());
248     EXPECT_TRUE(output.reports_size() > 0);
249     auto report = output.reports(0);
250     ASSERT_EQ(1, report.annotation_size());
251     EXPECT_EQ(1, report.annotation(0).field_int64());
252     EXPECT_EQ(2, report.annotation(0).field_int32());
253 }
254 
TEST(StatsLogProcessorTest,TestOnDumpReportEraseData)255 TEST(StatsLogProcessorTest, TestOnDumpReportEraseData) {
256     // Setup a simple config.
257     StatsdConfig config;
258     config.add_allowed_log_source("AID_ROOT");  // LogEvent defaults to UID of root.
259     auto wakelockAcquireMatcher = CreateAcquireWakelockAtomMatcher();
260     *config.add_atom_matcher() = wakelockAcquireMatcher;
261 
262     auto countMetric = config.add_count_metric();
263     countMetric->set_id(123456);
264     countMetric->set_what(wakelockAcquireMatcher.id());
265     countMetric->set_bucket(FIVE_MINUTES);
266 
267     ConfigKey cfgKey;
268     sp<StatsLogProcessor> processor = CreateStatsLogProcessor(1, 1, config, cfgKey);
269 
270     std::vector<int> attributionUids = {111};
271     std::vector<string> attributionTags = {"App1"};
272     std::unique_ptr<LogEvent> event =
273             CreateAcquireWakelockEvent(2 /*timestamp*/, attributionUids, attributionTags, "wl1");
274     processor->OnLogEvent(event.get());
275 
276     vector<uint8_t> bytes;
277     ConfigMetricsReportList output;
278 
279     // Dump report WITHOUT erasing data.
280     processor->onDumpReport(cfgKey, 3, true, false /* Do NOT erase data. */, ADB_DUMP, FAST,
281                             &bytes);
282     output.ParseFromArray(bytes.data(), bytes.size());
283     ASSERT_EQ(output.reports_size(), 1);
284     ASSERT_EQ(output.reports(0).metrics_size(), 1);
285     ASSERT_EQ(output.reports(0).metrics(0).count_metrics().data_size(), 1);
286 
287     // Dump report WITH erasing data. There should be data since we didn't previously erase it.
288     processor->onDumpReport(cfgKey, 4, true, true /* DO erase data. */, ADB_DUMP, FAST, &bytes);
289     output.ParseFromArray(bytes.data(), bytes.size());
290     ASSERT_EQ(output.reports_size(), 1);
291     ASSERT_EQ(output.reports(0).metrics_size(), 1);
292     ASSERT_EQ(output.reports(0).metrics(0).count_metrics().data_size(), 1);
293 
294     // Dump report again. There should be no data since we erased it.
295     processor->onDumpReport(cfgKey, 5, true, true /* DO erase data. */, ADB_DUMP, FAST, &bytes);
296     output.ParseFromArray(bytes.data(), bytes.size());
297     // We don't care whether statsd has a report, as long as it has no count metrics in it.
298     bool noData = output.reports_size() == 0 || output.reports(0).metrics_size() == 0 ||
299                   output.reports(0).metrics(0).count_metrics().data_size() == 0;
300     EXPECT_TRUE(noData);
301 }
302 
TEST(StatsLogProcessorTest,TestPullUidProviderSetOnConfigUpdate)303 TEST(StatsLogProcessorTest, TestPullUidProviderSetOnConfigUpdate) {
304     // Setup simple config key corresponding to empty config.
305     sp<UidMap> m = new UidMap();
306     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
307     sp<AlarmMonitor> anomalyAlarmMonitor;
308     sp<AlarmMonitor> subscriberAlarmMonitor;
309     StatsLogProcessor p(
310             m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
311             [](const ConfigKey& key) { return true; },
312             [](const int&, const vector<int64_t>&) { return true; });
313     ConfigKey key(3, 4);
314     StatsdConfig config = MakeConfig(false);
315     p.OnConfigUpdated(0, key, config);
316     EXPECT_NE(pullerManager->mPullUidProviders.find(key), pullerManager->mPullUidProviders.end());
317 
318     config.add_default_pull_packages("AID_STATSD");
319     p.OnConfigUpdated(5, key, config);
320     EXPECT_NE(pullerManager->mPullUidProviders.find(key), pullerManager->mPullUidProviders.end());
321 
322     p.OnConfigRemoved(key);
323     EXPECT_EQ(pullerManager->mPullUidProviders.find(key), pullerManager->mPullUidProviders.end());
324 }
325 
TEST(StatsLogProcessorTest,InvalidConfigRemoved)326 TEST(StatsLogProcessorTest, InvalidConfigRemoved) {
327     // Setup simple config key corresponding to empty config.
328     StatsdStats::getInstance().reset();
329     sp<UidMap> m = new UidMap();
330     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
331     m->updateMap(1, {1, 2}, {1, 2}, {String16("v1"), String16("v2")},
332                  {String16("p1"), String16("p2")}, {String16(""), String16("")});
333     sp<AlarmMonitor> anomalyAlarmMonitor;
334     sp<AlarmMonitor> subscriberAlarmMonitor;
335     StatsLogProcessor p(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, 0,
336                         [](const ConfigKey& key) { return true; },
337                         [](const int&, const vector<int64_t>&) {return true;});
338     ConfigKey key(3, 4);
339     StatsdConfig config = MakeConfig(true);
340     p.OnConfigUpdated(0, key, config);
341     EXPECT_EQ(1, p.mMetricsManagers.size());
342     EXPECT_NE(p.mMetricsManagers.find(key), p.mMetricsManagers.end());
343     // Cannot assert the size of mConfigStats since it is static and does not get cleared on reset.
344     EXPECT_NE(StatsdStats::getInstance().mConfigStats.end(),
345               StatsdStats::getInstance().mConfigStats.find(key));
346     EXPECT_EQ(0, StatsdStats::getInstance().mIceBox.size());
347 
348     StatsdConfig invalidConfig = MakeConfig(true);
349     invalidConfig.clear_allowed_log_source();
350     p.OnConfigUpdated(0, key, invalidConfig);
351     EXPECT_EQ(0, p.mMetricsManagers.size());
352     // The current configs should not contain the invalid config.
353     EXPECT_EQ(StatsdStats::getInstance().mConfigStats.end(),
354               StatsdStats::getInstance().mConfigStats.find(key));
355     // Both "config" and "invalidConfig" should be in the icebox.
356     EXPECT_EQ(2, StatsdStats::getInstance().mIceBox.size());
357 
358 }
359 
360 
TEST(StatsLogProcessorTest,TestActiveConfigMetricDiskWriteRead)361 TEST(StatsLogProcessorTest, TestActiveConfigMetricDiskWriteRead) {
362     int uid = 1111;
363 
364     // Setup a simple config, no activation
365     StatsdConfig config1;
366     int64_t cfgId1 = 12341;
367     config1.set_id(cfgId1);
368     config1.add_allowed_log_source("AID_ROOT");  // LogEvent defaults to UID of root.
369     auto wakelockAcquireMatcher = CreateAcquireWakelockAtomMatcher();
370     *config1.add_atom_matcher() = wakelockAcquireMatcher;
371 
372     long metricId1 = 1234561;
373     long metricId2 = 1234562;
374     auto countMetric1 = config1.add_count_metric();
375     countMetric1->set_id(metricId1);
376     countMetric1->set_what(wakelockAcquireMatcher.id());
377     countMetric1->set_bucket(FIVE_MINUTES);
378 
379     auto countMetric2 = config1.add_count_metric();
380     countMetric2->set_id(metricId2);
381     countMetric2->set_what(wakelockAcquireMatcher.id());
382     countMetric2->set_bucket(FIVE_MINUTES);
383 
384     ConfigKey cfgKey1(uid, cfgId1);
385 
386     // Add another config, with two metrics, one with activation
387     StatsdConfig config2;
388     int64_t cfgId2 = 12342;
389     config2.set_id(cfgId2);
390     config2.add_allowed_log_source("AID_ROOT");  // LogEvent defaults to UID of root.
391     *config2.add_atom_matcher() = wakelockAcquireMatcher;
392 
393     long metricId3 = 1234561;
394     long metricId4 = 1234562;
395 
396     auto countMetric3 = config2.add_count_metric();
397     countMetric3->set_id(metricId3);
398     countMetric3->set_what(wakelockAcquireMatcher.id());
399     countMetric3->set_bucket(FIVE_MINUTES);
400 
401     auto countMetric4 = config2.add_count_metric();
402     countMetric4->set_id(metricId4);
403     countMetric4->set_what(wakelockAcquireMatcher.id());
404     countMetric4->set_bucket(FIVE_MINUTES);
405 
406     auto metric3Activation = config2.add_metric_activation();
407     metric3Activation->set_metric_id(metricId3);
408     metric3Activation->set_activation_type(ACTIVATE_IMMEDIATELY);
409     auto metric3ActivationTrigger = metric3Activation->add_event_activation();
410     metric3ActivationTrigger->set_atom_matcher_id(wakelockAcquireMatcher.id());
411     metric3ActivationTrigger->set_ttl_seconds(100);
412 
413     ConfigKey cfgKey2(uid, cfgId2);
414 
415     // Add another config, with two metrics, both with activations
416     StatsdConfig config3;
417     int64_t cfgId3 = 12343;
418     config3.set_id(cfgId3);
419     config3.add_allowed_log_source("AID_ROOT");  // LogEvent defaults to UID of root.
420     *config3.add_atom_matcher() = wakelockAcquireMatcher;
421 
422     long metricId5 = 1234565;
423     long metricId6 = 1234566;
424     auto countMetric5 = config3.add_count_metric();
425     countMetric5->set_id(metricId5);
426     countMetric5->set_what(wakelockAcquireMatcher.id());
427     countMetric5->set_bucket(FIVE_MINUTES);
428 
429     auto countMetric6 = config3.add_count_metric();
430     countMetric6->set_id(metricId6);
431     countMetric6->set_what(wakelockAcquireMatcher.id());
432     countMetric6->set_bucket(FIVE_MINUTES);
433 
434     auto metric5Activation = config3.add_metric_activation();
435     metric5Activation->set_metric_id(metricId5);
436     metric5Activation->set_activation_type(ACTIVATE_IMMEDIATELY);
437     auto metric5ActivationTrigger = metric5Activation->add_event_activation();
438     metric5ActivationTrigger->set_atom_matcher_id(wakelockAcquireMatcher.id());
439     metric5ActivationTrigger->set_ttl_seconds(100);
440 
441     auto metric6Activation = config3.add_metric_activation();
442     metric6Activation->set_metric_id(metricId6);
443     metric6Activation->set_activation_type(ACTIVATE_IMMEDIATELY);
444     auto metric6ActivationTrigger = metric6Activation->add_event_activation();
445     metric6ActivationTrigger->set_atom_matcher_id(wakelockAcquireMatcher.id());
446     metric6ActivationTrigger->set_ttl_seconds(200);
447 
448     ConfigKey cfgKey3(uid, cfgId3);
449 
450     sp<UidMap> m = new UidMap();
451     sp<StatsPullerManager> pullerManager = new StatsPullerManager();
452     sp<AlarmMonitor> anomalyAlarmMonitor;
453     sp<AlarmMonitor> subscriberAlarmMonitor;
454     vector<int64_t> activeConfigsBroadcast;
455 
456     long timeBase1 = 1;
457     int broadcastCount = 0;
458     StatsLogProcessor processor(
459             m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor, timeBase1,
460             [](const ConfigKey& key) { return true; },
461             [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
462                                                              const vector<int64_t>& activeConfigs) {
463                 broadcastCount++;
464                 EXPECT_EQ(broadcastUid, uid);
465                 activeConfigsBroadcast.clear();
466                 activeConfigsBroadcast.insert(activeConfigsBroadcast.end(), activeConfigs.begin(),
467                                               activeConfigs.end());
468                 return true;
469             });
470 
471     processor.OnConfigUpdated(1, cfgKey1, config1);
472     processor.OnConfigUpdated(2, cfgKey2, config2);
473     processor.OnConfigUpdated(3, cfgKey3, config3);
474 
475     ASSERT_EQ(3, processor.mMetricsManagers.size());
476 
477     // Expect the first config and both metrics in it to be active.
478     auto it = processor.mMetricsManagers.find(cfgKey1);
479     EXPECT_TRUE(it != processor.mMetricsManagers.end());
480     auto& metricsManager1 = it->second;
481     EXPECT_TRUE(metricsManager1->isActive());
482 
483     auto metricIt = metricsManager1->mAllMetricProducers.begin();
484     for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
485         if ((*metricIt)->getMetricId() == metricId1) {
486             break;
487         }
488     }
489     EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
490     auto& metricProducer1 = *metricIt;
491     EXPECT_TRUE(metricProducer1->isActive());
492 
493     metricIt = metricsManager1->mAllMetricProducers.begin();
494     for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
495         if ((*metricIt)->getMetricId() == metricId2) {
496             break;
497         }
498     }
499     EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
500     auto& metricProducer2 = *metricIt;
501     EXPECT_TRUE(metricProducer2->isActive());
502 
503     // Expect config 2 to be active. Metric 3 shouldn't be active, metric 4 should be active.
504     it = processor.mMetricsManagers.find(cfgKey2);
505     EXPECT_TRUE(it != processor.mMetricsManagers.end());
506     auto& metricsManager2 = it->second;
507     EXPECT_TRUE(metricsManager2->isActive());
508 
509     metricIt = metricsManager2->mAllMetricProducers.begin();
510     for (; metricIt != metricsManager2->mAllMetricProducers.end(); metricIt++) {
511         if ((*metricIt)->getMetricId() == metricId3) {
512             break;
513         }
514     }
515     EXPECT_TRUE(metricIt != metricsManager2->mAllMetricProducers.end());
516     auto& metricProducer3 = *metricIt;
517     EXPECT_FALSE(metricProducer3->isActive());
518 
519     metricIt = metricsManager2->mAllMetricProducers.begin();
520     for (; metricIt != metricsManager2->mAllMetricProducers.end(); metricIt++) {
521         if ((*metricIt)->getMetricId() == metricId4) {
522             break;
523         }
524     }
525     EXPECT_TRUE(metricIt != metricsManager2->mAllMetricProducers.end());
526     auto& metricProducer4 = *metricIt;
527     EXPECT_TRUE(metricProducer4->isActive());
528 
529     // Expect the third config and both metrics in it to be inactive.
530     it = processor.mMetricsManagers.find(cfgKey3);
531     EXPECT_TRUE(it != processor.mMetricsManagers.end());
532     auto& metricsManager3 = it->second;
533     EXPECT_FALSE(metricsManager3->isActive());
534 
535     metricIt = metricsManager3->mAllMetricProducers.begin();
536     for (; metricIt != metricsManager2->mAllMetricProducers.end(); metricIt++) {
537         if ((*metricIt)->getMetricId() == metricId5) {
538             break;
539         }
540     }
541     EXPECT_TRUE(metricIt != metricsManager3->mAllMetricProducers.end());
542     auto& metricProducer5 = *metricIt;
543     EXPECT_FALSE(metricProducer5->isActive());
544 
545     metricIt = metricsManager3->mAllMetricProducers.begin();
546     for (; metricIt != metricsManager3->mAllMetricProducers.end(); metricIt++) {
547         if ((*metricIt)->getMetricId() == metricId6) {
548             break;
549         }
550     }
551     EXPECT_TRUE(metricIt != metricsManager3->mAllMetricProducers.end());
552     auto& metricProducer6 = *metricIt;
553     EXPECT_FALSE(metricProducer6->isActive());
554 
555     // No broadcast for active configs should have happened yet.
556     EXPECT_EQ(broadcastCount, 0);
557 
558     // Activate all 3 metrics that were not active.
559     std::vector<int> attributionUids = {111};
560     std::vector<string> attributionTags = {"App1"};
561     std::unique_ptr<LogEvent> event =
562             CreateAcquireWakelockEvent(timeBase1 + 100, attributionUids, attributionTags, "wl1");
563     processor.OnLogEvent(event.get());
564 
565     // Assert that all 3 configs are active.
566     EXPECT_TRUE(metricsManager1->isActive());
567     EXPECT_TRUE(metricsManager2->isActive());
568     EXPECT_TRUE(metricsManager3->isActive());
569 
570     // A broadcast should have happened, and all 3 configs should be active in the broadcast.
571     EXPECT_EQ(broadcastCount, 1);
572     ASSERT_EQ(activeConfigsBroadcast.size(), 3);
573     EXPECT_TRUE(std::find(activeConfigsBroadcast.begin(), activeConfigsBroadcast.end(), cfgId1) !=
574                 activeConfigsBroadcast.end());
575     EXPECT_TRUE(std::find(activeConfigsBroadcast.begin(), activeConfigsBroadcast.end(), cfgId2) !=
576                 activeConfigsBroadcast.end());
577     EXPECT_TRUE(std::find(activeConfigsBroadcast.begin(), activeConfigsBroadcast.end(), cfgId3) !=
578                 activeConfigsBroadcast.end());
579 
580     // When we shut down, metrics 3 & 5 have 100ns remaining, metric 6 has 100s + 100ns.
581     int64_t shutDownTime = timeBase1 + 100 * NS_PER_SEC;
582     processor.SaveActiveConfigsToDisk(shutDownTime);
583     const int64_t ttl3 = event->GetElapsedTimestampNs() +
584                          metric3ActivationTrigger->ttl_seconds() * NS_PER_SEC - shutDownTime;
585     const int64_t ttl5 = event->GetElapsedTimestampNs() +
586                          metric5ActivationTrigger->ttl_seconds() * NS_PER_SEC - shutDownTime;
587     const int64_t ttl6 = event->GetElapsedTimestampNs() +
588                          metric6ActivationTrigger->ttl_seconds() * NS_PER_SEC - shutDownTime;
589 
590     // Create a second StatsLogProcessor and push the same 3 configs.
591     long timeBase2 = 1000;
592     sp<StatsLogProcessor> processor2 =
593             CreateStatsLogProcessor(timeBase2, timeBase2, config1, cfgKey1);
594     processor2->OnConfigUpdated(timeBase2, cfgKey2, config2);
595     processor2->OnConfigUpdated(timeBase2, cfgKey3, config3);
596 
597     ASSERT_EQ(3, processor2->mMetricsManagers.size());
598 
599     // First config and both metrics are active.
600     it = processor2->mMetricsManagers.find(cfgKey1);
601     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
602     auto& metricsManager1001 = it->second;
603     EXPECT_TRUE(metricsManager1001->isActive());
604 
605     metricIt = metricsManager1001->mAllMetricProducers.begin();
606     for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
607         if ((*metricIt)->getMetricId() == metricId1) {
608             break;
609         }
610     }
611     EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
612     auto& metricProducer1001 = *metricIt;
613     EXPECT_TRUE(metricProducer1001->isActive());
614 
615     metricIt = metricsManager1001->mAllMetricProducers.begin();
616     for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
617         if ((*metricIt)->getMetricId() == metricId2) {
618             break;
619         }
620     }
621     EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
622     auto& metricProducer1002 = *metricIt;
623     EXPECT_TRUE(metricProducer1002->isActive());
624 
625     // Second config is active. Metric 3 is inactive, metric 4 is active.
626     it = processor2->mMetricsManagers.find(cfgKey2);
627     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
628     auto& metricsManager1002 = it->second;
629     EXPECT_TRUE(metricsManager1002->isActive());
630 
631     metricIt = metricsManager1002->mAllMetricProducers.begin();
632     for (; metricIt != metricsManager1002->mAllMetricProducers.end(); metricIt++) {
633         if ((*metricIt)->getMetricId() == metricId3) {
634             break;
635         }
636     }
637     EXPECT_TRUE(metricIt != metricsManager1002->mAllMetricProducers.end());
638     auto& metricProducer1003 = *metricIt;
639     EXPECT_FALSE(metricProducer1003->isActive());
640 
641     metricIt = metricsManager1002->mAllMetricProducers.begin();
642     for (; metricIt != metricsManager1002->mAllMetricProducers.end(); metricIt++) {
643         if ((*metricIt)->getMetricId() == metricId4) {
644             break;
645         }
646     }
647     EXPECT_TRUE(metricIt != metricsManager1002->mAllMetricProducers.end());
648     auto& metricProducer1004 = *metricIt;
649     EXPECT_TRUE(metricProducer1004->isActive());
650 
651     // Config 3 is inactive. both metrics are inactive.
652     it = processor2->mMetricsManagers.find(cfgKey3);
653     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
654     auto& metricsManager1003 = it->second;
655     EXPECT_FALSE(metricsManager1003->isActive());
656     ASSERT_EQ(2, metricsManager1003->mAllMetricProducers.size());
657 
658     metricIt = metricsManager1003->mAllMetricProducers.begin();
659     for (; metricIt != metricsManager1002->mAllMetricProducers.end(); metricIt++) {
660         if ((*metricIt)->getMetricId() == metricId5) {
661             break;
662         }
663     }
664     EXPECT_TRUE(metricIt != metricsManager1003->mAllMetricProducers.end());
665     auto& metricProducer1005 = *metricIt;
666     EXPECT_FALSE(metricProducer1005->isActive());
667 
668     metricIt = metricsManager1003->mAllMetricProducers.begin();
669     for (; metricIt != metricsManager1003->mAllMetricProducers.end(); metricIt++) {
670         if ((*metricIt)->getMetricId() == metricId6) {
671             break;
672         }
673     }
674     EXPECT_TRUE(metricIt != metricsManager1003->mAllMetricProducers.end());
675     auto& metricProducer1006 = *metricIt;
676     EXPECT_FALSE(metricProducer1006->isActive());
677 
678     // Assert that all 3 metrics with activation are inactive and that the ttls were properly set.
679     EXPECT_FALSE(metricProducer1003->isActive());
680     const auto& activation1003 = metricProducer1003->mEventActivationMap.begin()->second;
681     EXPECT_EQ(100 * NS_PER_SEC, activation1003->ttl_ns);
682     EXPECT_EQ(0, activation1003->start_ns);
683     EXPECT_FALSE(metricProducer1005->isActive());
684     const auto& activation1005 = metricProducer1005->mEventActivationMap.begin()->second;
685     EXPECT_EQ(100 * NS_PER_SEC, activation1005->ttl_ns);
686     EXPECT_EQ(0, activation1005->start_ns);
687     EXPECT_FALSE(metricProducer1006->isActive());
688     const auto& activation1006 = metricProducer1006->mEventActivationMap.begin()->second;
689     EXPECT_EQ(200 * NS_PER_SEC, activation1006->ttl_ns);
690     EXPECT_EQ(0, activation1006->start_ns);
691 
692     processor2->LoadActiveConfigsFromDisk();
693 
694     // After loading activations from disk, assert that all 3 metrics are active.
695     EXPECT_TRUE(metricProducer1003->isActive());
696     EXPECT_EQ(timeBase2 + ttl3 - activation1003->ttl_ns, activation1003->start_ns);
697     EXPECT_TRUE(metricProducer1005->isActive());
698     EXPECT_EQ(timeBase2 + ttl5 - activation1005->ttl_ns, activation1005->start_ns);
699     EXPECT_TRUE(metricProducer1006->isActive());
700     EXPECT_EQ(timeBase2 + ttl6 - activation1006->ttl_ns, activation1003->start_ns);
701 
702     // Make sure no more broadcasts have happened.
703     EXPECT_EQ(broadcastCount, 1);
704 }
705 
TEST(StatsLogProcessorTest,TestActivationOnBoot)706 TEST(StatsLogProcessorTest, TestActivationOnBoot) {
707     int uid = 1111;
708 
709     StatsdConfig config1;
710     config1.set_id(12341);
711     config1.add_allowed_log_source("AID_ROOT");  // LogEvent defaults to UID of root.
712     auto wakelockAcquireMatcher = CreateAcquireWakelockAtomMatcher();
713     *config1.add_atom_matcher() = wakelockAcquireMatcher;
714 
715     long metricId1 = 1234561;
716     long metricId2 = 1234562;
717     auto countMetric1 = config1.add_count_metric();
718     countMetric1->set_id(metricId1);
719     countMetric1->set_what(wakelockAcquireMatcher.id());
720     countMetric1->set_bucket(FIVE_MINUTES);
721 
722     auto countMetric2 = config1.add_count_metric();
723     countMetric2->set_id(metricId2);
724     countMetric2->set_what(wakelockAcquireMatcher.id());
725     countMetric2->set_bucket(FIVE_MINUTES);
726 
727     auto metric1Activation = config1.add_metric_activation();
728     metric1Activation->set_metric_id(metricId1);
729     metric1Activation->set_activation_type(ACTIVATE_ON_BOOT);
730     auto metric1ActivationTrigger = metric1Activation->add_event_activation();
731     metric1ActivationTrigger->set_atom_matcher_id(wakelockAcquireMatcher.id());
732     metric1ActivationTrigger->set_ttl_seconds(100);
733 
734     ConfigKey cfgKey1(uid, 12341);
735     long timeBase1 = 1;
736     sp<StatsLogProcessor> processor =
737             CreateStatsLogProcessor(timeBase1, timeBase1, config1, cfgKey1);
738 
739     ASSERT_EQ(1, processor->mMetricsManagers.size());
740     auto it = processor->mMetricsManagers.find(cfgKey1);
741     EXPECT_TRUE(it != processor->mMetricsManagers.end());
742     auto& metricsManager1 = it->second;
743     EXPECT_TRUE(metricsManager1->isActive());
744 
745     auto metricIt = metricsManager1->mAllMetricProducers.begin();
746     for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
747         if ((*metricIt)->getMetricId() == metricId1) {
748             break;
749         }
750     }
751     EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
752     auto& metricProducer1 = *metricIt;
753     EXPECT_FALSE(metricProducer1->isActive());
754 
755     metricIt = metricsManager1->mAllMetricProducers.begin();
756     for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
757         if ((*metricIt)->getMetricId() == metricId2) {
758             break;
759         }
760     }
761     EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
762     auto& metricProducer2 = *metricIt;
763     EXPECT_TRUE(metricProducer2->isActive());
764 
765     const auto& activation1 = metricProducer1->mEventActivationMap.begin()->second;
766     EXPECT_EQ(100 * NS_PER_SEC, activation1->ttl_ns);
767     EXPECT_EQ(0, activation1->start_ns);
768     EXPECT_EQ(kNotActive, activation1->state);
769 
770     std::vector<int> attributionUids = {111};
771     std::vector<string> attributionTags = {"App1"};
772     std::unique_ptr<LogEvent> event =
773             CreateAcquireWakelockEvent(timeBase1 + 100, attributionUids, attributionTags, "wl1");
774     processor->OnLogEvent(event.get());
775 
776     EXPECT_FALSE(metricProducer1->isActive());
777     EXPECT_EQ(0, activation1->start_ns);
778     EXPECT_EQ(kActiveOnBoot, activation1->state);
779 
780     int64_t shutDownTime = timeBase1 + 100 * NS_PER_SEC;
781     processor->SaveActiveConfigsToDisk(shutDownTime);
782     EXPECT_FALSE(metricProducer1->isActive());
783     const int64_t ttl1 = metric1ActivationTrigger->ttl_seconds() * NS_PER_SEC;
784 
785     long timeBase2 = 1000;
786     sp<StatsLogProcessor> processor2 =
787             CreateStatsLogProcessor(timeBase2, timeBase2, config1, cfgKey1);
788 
789     ASSERT_EQ(1, processor2->mMetricsManagers.size());
790     it = processor2->mMetricsManagers.find(cfgKey1);
791     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
792     auto& metricsManager1001 = it->second;
793     EXPECT_TRUE(metricsManager1001->isActive());
794 
795     metricIt = metricsManager1001->mAllMetricProducers.begin();
796     for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
797         if ((*metricIt)->getMetricId() == metricId1) {
798             break;
799         }
800     }
801     EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
802     auto& metricProducer1001 = *metricIt;
803     EXPECT_FALSE(metricProducer1001->isActive());
804 
805     metricIt = metricsManager1001->mAllMetricProducers.begin();
806     for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
807         if ((*metricIt)->getMetricId() == metricId2) {
808             break;
809         }
810     }
811     EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
812     auto& metricProducer1002 = *metricIt;
813     EXPECT_TRUE(metricProducer1002->isActive());
814 
815     const auto& activation1001 = metricProducer1001->mEventActivationMap.begin()->second;
816     EXPECT_EQ(100 * NS_PER_SEC, activation1001->ttl_ns);
817     EXPECT_EQ(0, activation1001->start_ns);
818     EXPECT_EQ(kNotActive, activation1001->state);
819 
820     processor2->LoadActiveConfigsFromDisk();
821 
822     EXPECT_TRUE(metricProducer1001->isActive());
823     EXPECT_EQ(timeBase2 + ttl1 - activation1001->ttl_ns, activation1001->start_ns);
824     EXPECT_EQ(kActive, activation1001->state);
825 }
826 
TEST(StatsLogProcessorTest,TestActivationOnBootMultipleActivations)827 TEST(StatsLogProcessorTest, TestActivationOnBootMultipleActivations) {
828     int uid = 1111;
829 
830     // Create config with 2 metrics:
831     // Metric 1: Activate on boot with 2 activations
832     // Metric 2: Always active
833     StatsdConfig config1;
834     config1.set_id(12341);
835     config1.add_allowed_log_source("AID_ROOT");  // LogEvent defaults to UID of root.
836     auto wakelockAcquireMatcher = CreateAcquireWakelockAtomMatcher();
837     auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
838     *config1.add_atom_matcher() = wakelockAcquireMatcher;
839     *config1.add_atom_matcher() = screenOnMatcher;
840 
841     long metricId1 = 1234561;
842     long metricId2 = 1234562;
843 
844     auto countMetric1 = config1.add_count_metric();
845     countMetric1->set_id(metricId1);
846     countMetric1->set_what(wakelockAcquireMatcher.id());
847     countMetric1->set_bucket(FIVE_MINUTES);
848 
849     auto countMetric2 = config1.add_count_metric();
850     countMetric2->set_id(metricId2);
851     countMetric2->set_what(wakelockAcquireMatcher.id());
852     countMetric2->set_bucket(FIVE_MINUTES);
853 
854     auto metric1Activation = config1.add_metric_activation();
855     metric1Activation->set_metric_id(metricId1);
856     metric1Activation->set_activation_type(ACTIVATE_ON_BOOT);
857     auto metric1ActivationTrigger1 = metric1Activation->add_event_activation();
858     metric1ActivationTrigger1->set_atom_matcher_id(wakelockAcquireMatcher.id());
859     metric1ActivationTrigger1->set_ttl_seconds(100);
860     auto metric1ActivationTrigger2 = metric1Activation->add_event_activation();
861     metric1ActivationTrigger2->set_atom_matcher_id(screenOnMatcher.id());
862     metric1ActivationTrigger2->set_ttl_seconds(200);
863 
864     ConfigKey cfgKey1(uid, 12341);
865     long timeBase1 = 1;
866     sp<StatsLogProcessor> processor =
867             CreateStatsLogProcessor(timeBase1, timeBase1, config1, cfgKey1);
868 
869     // Metric 1 is not active.
870     // Metric 2 is active.
871     // {{{---------------------------------------------------------------------------
872     ASSERT_EQ(1, processor->mMetricsManagers.size());
873     auto it = processor->mMetricsManagers.find(cfgKey1);
874     EXPECT_TRUE(it != processor->mMetricsManagers.end());
875     auto& metricsManager1 = it->second;
876     EXPECT_TRUE(metricsManager1->isActive());
877 
878     auto metricIt = metricsManager1->mAllMetricProducers.begin();
879     for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
880         if ((*metricIt)->getMetricId() == metricId1) {
881             break;
882         }
883     }
884     EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
885     auto& metricProducer1 = *metricIt;
886     EXPECT_FALSE(metricProducer1->isActive());
887 
888     metricIt = metricsManager1->mAllMetricProducers.begin();
889     for (; metricIt != metricsManager1->mAllMetricProducers.end(); metricIt++) {
890         if ((*metricIt)->getMetricId() == metricId2) {
891             break;
892         }
893     }
894     EXPECT_TRUE(metricIt != metricsManager1->mAllMetricProducers.end());
895     auto& metricProducer2 = *metricIt;
896     EXPECT_TRUE(metricProducer2->isActive());
897 
898     int i = 0;
899     for (; i < metricsManager1->mAllAtomMatchers.size(); i++) {
900         if (metricsManager1->mAllAtomMatchers[i]->getId() ==
901             metric1ActivationTrigger1->atom_matcher_id()) {
902             break;
903         }
904     }
905     const auto& activation1 = metricProducer1->mEventActivationMap.at(i);
906     EXPECT_EQ(100 * NS_PER_SEC, activation1->ttl_ns);
907     EXPECT_EQ(0, activation1->start_ns);
908     EXPECT_EQ(kNotActive, activation1->state);
909 
910     i = 0;
911     for (; i < metricsManager1->mAllAtomMatchers.size(); i++) {
912         if (metricsManager1->mAllAtomMatchers[i]->getId() ==
913             metric1ActivationTrigger2->atom_matcher_id()) {
914             break;
915         }
916     }
917     const auto& activation2 = metricProducer1->mEventActivationMap.at(i);
918     EXPECT_EQ(200 * NS_PER_SEC, activation2->ttl_ns);
919     EXPECT_EQ(0, activation2->start_ns);
920     EXPECT_EQ(kNotActive, activation2->state);
921     // }}}------------------------------------------------------------------------------
922 
923     // Trigger Activation 1 for Metric 1
924     std::vector<int> attributionUids = {111};
925     std::vector<string> attributionTags = {"App1"};
926     std::unique_ptr<LogEvent> event =
927             CreateAcquireWakelockEvent(timeBase1 + 100, attributionUids, attributionTags, "wl1");
928     processor->OnLogEvent(event.get());
929 
930     // Metric 1 is not active; Activation 1 set to kActiveOnBoot
931     // Metric 2 is active.
932     // {{{---------------------------------------------------------------------------
933     EXPECT_FALSE(metricProducer1->isActive());
934     EXPECT_EQ(0, activation1->start_ns);
935     EXPECT_EQ(kActiveOnBoot, activation1->state);
936     EXPECT_EQ(0, activation2->start_ns);
937     EXPECT_EQ(kNotActive, activation2->state);
938 
939     EXPECT_TRUE(metricProducer2->isActive());
940     // }}}-----------------------------------------------------------------------------
941 
942     // Simulate shutdown by saving state to disk
943     int64_t shutDownTime = timeBase1 + 100 * NS_PER_SEC;
944     processor->SaveActiveConfigsToDisk(shutDownTime);
945     EXPECT_FALSE(metricProducer1->isActive());
946     int64_t ttl1 = metric1ActivationTrigger1->ttl_seconds() * NS_PER_SEC;
947 
948     // Simulate device restarted state by creating new instance of StatsLogProcessor with the
949     // same config.
950     long timeBase2 = 1000;
951     sp<StatsLogProcessor> processor2 =
952             CreateStatsLogProcessor(timeBase2, timeBase2, config1, cfgKey1);
953 
954     // Metric 1 is not active.
955     // Metric 2 is active.
956     // {{{---------------------------------------------------------------------------
957     ASSERT_EQ(1, processor2->mMetricsManagers.size());
958     it = processor2->mMetricsManagers.find(cfgKey1);
959     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
960     auto& metricsManager1001 = it->second;
961     EXPECT_TRUE(metricsManager1001->isActive());
962 
963     metricIt = metricsManager1001->mAllMetricProducers.begin();
964     for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
965         if ((*metricIt)->getMetricId() == metricId1) {
966             break;
967         }
968     }
969     EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
970     auto& metricProducer1001 = *metricIt;
971     EXPECT_FALSE(metricProducer1001->isActive());
972 
973     metricIt = metricsManager1001->mAllMetricProducers.begin();
974     for (; metricIt != metricsManager1001->mAllMetricProducers.end(); metricIt++) {
975         if ((*metricIt)->getMetricId() == metricId2) {
976             break;
977         }
978     }
979     EXPECT_TRUE(metricIt != metricsManager1001->mAllMetricProducers.end());
980     auto& metricProducer1002 = *metricIt;
981     EXPECT_TRUE(metricProducer1002->isActive());
982 
983     i = 0;
984     for (; i < metricsManager1001->mAllAtomMatchers.size(); i++) {
985         if (metricsManager1001->mAllAtomMatchers[i]->getId() ==
986             metric1ActivationTrigger1->atom_matcher_id()) {
987             break;
988         }
989     }
990     const auto& activation1001_1 = metricProducer1001->mEventActivationMap.at(i);
991     EXPECT_EQ(100 * NS_PER_SEC, activation1001_1->ttl_ns);
992     EXPECT_EQ(0, activation1001_1->start_ns);
993     EXPECT_EQ(kNotActive, activation1001_1->state);
994 
995     i = 0;
996     for (; i < metricsManager1001->mAllAtomMatchers.size(); i++) {
997         if (metricsManager1001->mAllAtomMatchers[i]->getId() ==
998             metric1ActivationTrigger2->atom_matcher_id()) {
999             break;
1000         }
1001     }
1002 
1003     const auto& activation1001_2 = metricProducer1001->mEventActivationMap.at(i);
1004     EXPECT_EQ(200 * NS_PER_SEC, activation1001_2->ttl_ns);
1005     EXPECT_EQ(0, activation1001_2->start_ns);
1006     EXPECT_EQ(kNotActive, activation1001_2->state);
1007     // }}}-----------------------------------------------------------------------------------
1008 
1009     // Load saved state from disk.
1010     processor2->LoadActiveConfigsFromDisk();
1011 
1012     // Metric 1 active; Activation 1 is active, Activation 2 is not active
1013     // Metric 2 is active.
1014     // {{{---------------------------------------------------------------------------
1015     EXPECT_TRUE(metricProducer1001->isActive());
1016     EXPECT_EQ(timeBase2 + ttl1 - activation1001_1->ttl_ns, activation1001_1->start_ns);
1017     EXPECT_EQ(kActive, activation1001_1->state);
1018     EXPECT_EQ(0, activation1001_2->start_ns);
1019     EXPECT_EQ(kNotActive, activation1001_2->state);
1020 
1021     EXPECT_TRUE(metricProducer1002->isActive());
1022     // }}}--------------------------------------------------------------------------------
1023 
1024     // Trigger Activation 2 for Metric 1.
1025     auto screenOnEvent =
1026             CreateScreenStateChangedEvent(timeBase2 + 200, android::view::DISPLAY_STATE_ON);
1027     processor2->OnLogEvent(screenOnEvent.get());
1028 
1029     // Metric 1 active; Activation 1 is active, Activation 2 is set to kActiveOnBoot
1030     // Metric 2 is active.
1031     // {{{---------------------------------------------------------------------------
1032     EXPECT_TRUE(metricProducer1001->isActive());
1033     EXPECT_EQ(timeBase2 + ttl1 - activation1001_1->ttl_ns, activation1001_1->start_ns);
1034     EXPECT_EQ(kActive, activation1001_1->state);
1035     EXPECT_EQ(0, activation1001_2->start_ns);
1036     EXPECT_EQ(kActiveOnBoot, activation1001_2->state);
1037 
1038     EXPECT_TRUE(metricProducer1002->isActive());
1039     // }}}---------------------------------------------------------------------------
1040 
1041     // Simulate shutdown by saving state to disk
1042     shutDownTime = timeBase2 + 50 * NS_PER_SEC;
1043     processor2->SaveActiveConfigsToDisk(shutDownTime);
1044     EXPECT_TRUE(metricProducer1001->isActive());
1045     EXPECT_TRUE(metricProducer1002->isActive());
1046     ttl1 = timeBase2 + metric1ActivationTrigger1->ttl_seconds() * NS_PER_SEC - shutDownTime;
1047     int64_t ttl2 = metric1ActivationTrigger2->ttl_seconds() * NS_PER_SEC;
1048 
1049     // Simulate device restarted state by creating new instance of StatsLogProcessor with the
1050     // same config.
1051     long timeBase3 = timeBase2 + 120 * NS_PER_SEC;
1052     sp<StatsLogProcessor> processor3 =
1053             CreateStatsLogProcessor(timeBase3, timeBase3, config1, cfgKey1);
1054 
1055     // Metric 1 is not active.
1056     // Metric 2 is active.
1057     // {{{---------------------------------------------------------------------------
1058     ASSERT_EQ(1, processor3->mMetricsManagers.size());
1059     it = processor3->mMetricsManagers.find(cfgKey1);
1060     EXPECT_TRUE(it != processor3->mMetricsManagers.end());
1061     auto& metricsManagerTimeBase3 = it->second;
1062     EXPECT_TRUE(metricsManagerTimeBase3->isActive());
1063 
1064     metricIt = metricsManagerTimeBase3->mAllMetricProducers.begin();
1065     for (; metricIt != metricsManagerTimeBase3->mAllMetricProducers.end(); metricIt++) {
1066         if ((*metricIt)->getMetricId() == metricId1) {
1067             break;
1068         }
1069     }
1070     EXPECT_TRUE(metricIt != metricsManagerTimeBase3->mAllMetricProducers.end());
1071     auto& metricProducerTimeBase3_1 = *metricIt;
1072     EXPECT_FALSE(metricProducerTimeBase3_1->isActive());
1073 
1074     metricIt = metricsManagerTimeBase3->mAllMetricProducers.begin();
1075     for (; metricIt != metricsManagerTimeBase3->mAllMetricProducers.end(); metricIt++) {
1076         if ((*metricIt)->getMetricId() == metricId2) {
1077             break;
1078         }
1079     }
1080     EXPECT_TRUE(metricIt != metricsManagerTimeBase3->mAllMetricProducers.end());
1081     auto& metricProducerTimeBase3_2 = *metricIt;
1082     EXPECT_TRUE(metricProducerTimeBase3_2->isActive());
1083 
1084     i = 0;
1085     for (; i < metricsManagerTimeBase3->mAllAtomMatchers.size(); i++) {
1086         if (metricsManagerTimeBase3->mAllAtomMatchers[i]->getId() ==
1087             metric1ActivationTrigger1->atom_matcher_id()) {
1088             break;
1089         }
1090     }
1091     const auto& activationTimeBase3_1 = metricProducerTimeBase3_1->mEventActivationMap.at(i);
1092     EXPECT_EQ(100 * NS_PER_SEC, activationTimeBase3_1->ttl_ns);
1093     EXPECT_EQ(0, activationTimeBase3_1->start_ns);
1094     EXPECT_EQ(kNotActive, activationTimeBase3_1->state);
1095 
1096     i = 0;
1097     for (; i < metricsManagerTimeBase3->mAllAtomMatchers.size(); i++) {
1098         if (metricsManagerTimeBase3->mAllAtomMatchers[i]->getId() ==
1099             metric1ActivationTrigger2->atom_matcher_id()) {
1100             break;
1101         }
1102     }
1103 
1104     const auto& activationTimeBase3_2 = metricProducerTimeBase3_1->mEventActivationMap.at(i);
1105     EXPECT_EQ(200 * NS_PER_SEC, activationTimeBase3_2->ttl_ns);
1106     EXPECT_EQ(0, activationTimeBase3_2->start_ns);
1107     EXPECT_EQ(kNotActive, activationTimeBase3_2->state);
1108 
1109     EXPECT_TRUE(metricProducerTimeBase3_2->isActive());
1110     // }}}----------------------------------------------------------------------------------
1111 
1112     // Load saved state from disk.
1113     processor3->LoadActiveConfigsFromDisk();
1114 
1115     // Metric 1 active: Activation 1 is active, Activation 2 is active
1116     // Metric 2 is active.
1117     // {{{---------------------------------------------------------------------------
1118     EXPECT_TRUE(metricProducerTimeBase3_1->isActive());
1119     EXPECT_EQ(timeBase3 + ttl1 - activationTimeBase3_1->ttl_ns, activationTimeBase3_1->start_ns);
1120     EXPECT_EQ(kActive, activationTimeBase3_1->state);
1121     EXPECT_EQ(timeBase3 + ttl2 - activationTimeBase3_2->ttl_ns, activationTimeBase3_2->start_ns);
1122     EXPECT_EQ(kActive, activationTimeBase3_2->state);
1123 
1124     EXPECT_TRUE(metricProducerTimeBase3_2->isActive());
1125     // }}}-------------------------------------------------------------------------------
1126 
1127     // Trigger Activation 2 for Metric 1 again.
1128     screenOnEvent = CreateScreenStateChangedEvent(timeBase3 + 100 * NS_PER_SEC,
1129                                                   android::view::DISPLAY_STATE_ON);
1130     processor3->OnLogEvent(screenOnEvent.get());
1131 
1132     // Metric 1 active; Activation 1 is not active, Activation 2 is set to active
1133     // Metric 2 is active.
1134     // {{{---------------------------------------------------------------------------
1135     EXPECT_TRUE(metricProducerTimeBase3_1->isActive());
1136     EXPECT_EQ(kNotActive, activationTimeBase3_1->state);
1137     EXPECT_EQ(timeBase3 + ttl2 - activationTimeBase3_2->ttl_ns, activationTimeBase3_2->start_ns);
1138     EXPECT_EQ(kActive, activationTimeBase3_2->state);
1139 
1140     EXPECT_TRUE(metricProducerTimeBase3_2->isActive());
1141     // }}}---------------------------------------------------------------------------
1142 
1143     // Simulate shutdown by saving state to disk.
1144     shutDownTime = timeBase3 + 500 * NS_PER_SEC;
1145     processor3->SaveActiveConfigsToDisk(shutDownTime);
1146     EXPECT_TRUE(metricProducer1001->isActive());
1147     EXPECT_TRUE(metricProducer1002->isActive());
1148     ttl1 = timeBase3 + ttl1 - shutDownTime;
1149     ttl2 = timeBase3 + metric1ActivationTrigger2->ttl_seconds() * NS_PER_SEC - shutDownTime;
1150 
1151     // Simulate device restarted state by creating new instance of StatsLogProcessor with the
1152     // same config.
1153     long timeBase4 = timeBase3 + 600 * NS_PER_SEC;
1154     sp<StatsLogProcessor> processor4 =
1155             CreateStatsLogProcessor(timeBase4, timeBase4, config1, cfgKey1);
1156 
1157     // Metric 1 is not active.
1158     // Metric 2 is active.
1159     // {{{---------------------------------------------------------------------------
1160     ASSERT_EQ(1, processor4->mMetricsManagers.size());
1161     it = processor4->mMetricsManagers.find(cfgKey1);
1162     EXPECT_TRUE(it != processor4->mMetricsManagers.end());
1163     auto& metricsManagerTimeBase4 = it->second;
1164     EXPECT_TRUE(metricsManagerTimeBase4->isActive());
1165 
1166     metricIt = metricsManagerTimeBase4->mAllMetricProducers.begin();
1167     for (; metricIt != metricsManagerTimeBase4->mAllMetricProducers.end(); metricIt++) {
1168         if ((*metricIt)->getMetricId() == metricId1) {
1169             break;
1170         }
1171     }
1172     EXPECT_TRUE(metricIt != metricsManagerTimeBase4->mAllMetricProducers.end());
1173     auto& metricProducerTimeBase4_1 = *metricIt;
1174     EXPECT_FALSE(metricProducerTimeBase4_1->isActive());
1175 
1176     metricIt = metricsManagerTimeBase4->mAllMetricProducers.begin();
1177     for (; metricIt != metricsManagerTimeBase4->mAllMetricProducers.end(); metricIt++) {
1178         if ((*metricIt)->getMetricId() == metricId2) {
1179             break;
1180         }
1181     }
1182     EXPECT_TRUE(metricIt != metricsManagerTimeBase4->mAllMetricProducers.end());
1183     auto& metricProducerTimeBase4_2 = *metricIt;
1184     EXPECT_TRUE(metricProducerTimeBase4_2->isActive());
1185 
1186     i = 0;
1187     for (; i < metricsManagerTimeBase4->mAllAtomMatchers.size(); i++) {
1188         if (metricsManagerTimeBase4->mAllAtomMatchers[i]->getId() ==
1189             metric1ActivationTrigger1->atom_matcher_id()) {
1190             break;
1191         }
1192     }
1193     const auto& activationTimeBase4_1 = metricProducerTimeBase4_1->mEventActivationMap.at(i);
1194     EXPECT_EQ(100 * NS_PER_SEC, activationTimeBase4_1->ttl_ns);
1195     EXPECT_EQ(0, activationTimeBase4_1->start_ns);
1196     EXPECT_EQ(kNotActive, activationTimeBase4_1->state);
1197 
1198     i = 0;
1199     for (; i < metricsManagerTimeBase4->mAllAtomMatchers.size(); i++) {
1200         if (metricsManagerTimeBase4->mAllAtomMatchers[i]->getId() ==
1201             metric1ActivationTrigger2->atom_matcher_id()) {
1202             break;
1203         }
1204     }
1205 
1206     const auto& activationTimeBase4_2 = metricProducerTimeBase4_1->mEventActivationMap.at(i);
1207     EXPECT_EQ(200 * NS_PER_SEC, activationTimeBase4_2->ttl_ns);
1208     EXPECT_EQ(0, activationTimeBase4_2->start_ns);
1209     EXPECT_EQ(kNotActive, activationTimeBase4_2->state);
1210 
1211     EXPECT_TRUE(metricProducerTimeBase4_2->isActive());
1212     // }}}----------------------------------------------------------------------------------
1213 
1214     // Load saved state from disk.
1215     processor4->LoadActiveConfigsFromDisk();
1216 
1217     // Metric 1 active: Activation 1 is not active, Activation 2 is not active
1218     // Metric 2 is active.
1219     // {{{---------------------------------------------------------------------------
1220     EXPECT_FALSE(metricProducerTimeBase4_1->isActive());
1221     EXPECT_EQ(kNotActive, activationTimeBase4_1->state);
1222     EXPECT_EQ(kNotActive, activationTimeBase4_2->state);
1223 
1224     EXPECT_TRUE(metricProducerTimeBase4_2->isActive());
1225     // }}}-------------------------------------------------------------------------------
1226 }
1227 
TEST(StatsLogProcessorTest,TestActivationOnBootMultipleActivationsDifferentActivationTypes)1228 TEST(StatsLogProcessorTest, TestActivationOnBootMultipleActivationsDifferentActivationTypes) {
1229     int uid = 1111;
1230 
1231     // Create config with 2 metrics:
1232     // Metric 1: Activate on boot with 2 activations
1233     // Metric 2: Always active
1234     StatsdConfig config1;
1235     config1.set_id(12341);
1236     config1.add_allowed_log_source("AID_ROOT");  // LogEvent defaults to UID of root.
1237     auto wakelockAcquireMatcher = CreateAcquireWakelockAtomMatcher();
1238     auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
1239     *config1.add_atom_matcher() = wakelockAcquireMatcher;
1240     *config1.add_atom_matcher() = screenOnMatcher;
1241 
1242     long metricId1 = 1234561;
1243     long metricId2 = 1234562;
1244 
1245     auto countMetric1 = config1.add_count_metric();
1246     countMetric1->set_id(metricId1);
1247     countMetric1->set_what(wakelockAcquireMatcher.id());
1248     countMetric1->set_bucket(FIVE_MINUTES);
1249 
1250     auto countMetric2 = config1.add_count_metric();
1251     countMetric2->set_id(metricId2);
1252     countMetric2->set_what(wakelockAcquireMatcher.id());
1253     countMetric2->set_bucket(FIVE_MINUTES);
1254 
1255     auto metric1Activation = config1.add_metric_activation();
1256     metric1Activation->set_metric_id(metricId1);
1257     metric1Activation->set_activation_type(ACTIVATE_ON_BOOT);
1258     auto metric1ActivationTrigger1 = metric1Activation->add_event_activation();
1259     metric1ActivationTrigger1->set_atom_matcher_id(wakelockAcquireMatcher.id());
1260     metric1ActivationTrigger1->set_ttl_seconds(100);
1261     auto metric1ActivationTrigger2 = metric1Activation->add_event_activation();
1262     metric1ActivationTrigger2->set_atom_matcher_id(screenOnMatcher.id());
1263     metric1ActivationTrigger2->set_ttl_seconds(200);
1264     metric1ActivationTrigger2->set_activation_type(ACTIVATE_IMMEDIATELY);
1265 
1266     ConfigKey cfgKey1(uid, 12341);
1267     long timeBase1 = 1;
1268     sp<StatsLogProcessor> processor1 =
1269             CreateStatsLogProcessor(timeBase1, timeBase1, config1, cfgKey1);
1270 
1271     // Metric 1 is not active.
1272     // Metric 2 is active.
1273     // {{{---------------------------------------------------------------------------
1274     ASSERT_EQ(1, processor1->mMetricsManagers.size());
1275     auto it = processor1->mMetricsManagers.find(cfgKey1);
1276     EXPECT_TRUE(it != processor1->mMetricsManagers.end());
1277     auto& metricsManager1 = it->second;
1278     EXPECT_TRUE(metricsManager1->isActive());
1279 
1280     ASSERT_EQ(metricsManager1->mAllMetricProducers.size(), 2);
1281     // We assume that the index of a MetricProducer within the mAllMetricProducers
1282     // array follows the order in which metrics are added to the config.
1283     auto& metricProducer1_1 = metricsManager1->mAllMetricProducers[0];
1284     EXPECT_EQ(metricProducer1_1->getMetricId(), metricId1);
1285     EXPECT_FALSE(metricProducer1_1->isActive());  // inactive due to associated MetricActivation
1286 
1287     auto& metricProducer1_2 = metricsManager1->mAllMetricProducers[1];
1288     EXPECT_EQ(metricProducer1_2->getMetricId(), metricId2);
1289     EXPECT_TRUE(metricProducer1_2->isActive());
1290 
1291     ASSERT_EQ(metricProducer1_1->mEventActivationMap.size(), 2);
1292     // The key in mEventActivationMap is the index of the associated atom matcher. We assume
1293     // that matchers are indexed in the order that they are added to the config.
1294     const auto& activation1_1_1 = metricProducer1_1->mEventActivationMap.at(0);
1295     EXPECT_EQ(100 * NS_PER_SEC, activation1_1_1->ttl_ns);
1296     EXPECT_EQ(0, activation1_1_1->start_ns);
1297     EXPECT_EQ(kNotActive, activation1_1_1->state);
1298     EXPECT_EQ(ACTIVATE_ON_BOOT, activation1_1_1->activationType);
1299 
1300     const auto& activation1_1_2 = metricProducer1_1->mEventActivationMap.at(1);
1301     EXPECT_EQ(200 * NS_PER_SEC, activation1_1_2->ttl_ns);
1302     EXPECT_EQ(0, activation1_1_2->start_ns);
1303     EXPECT_EQ(kNotActive, activation1_1_2->state);
1304     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation1_1_2->activationType);
1305     // }}}------------------------------------------------------------------------------
1306 
1307     // Trigger Activation 1 for Metric 1
1308     std::vector<int> attributionUids = {111};
1309     std::vector<string> attributionTags = {"App1"};
1310     std::unique_ptr<LogEvent> event =
1311             CreateAcquireWakelockEvent(timeBase1 + 100, attributionUids, attributionTags, "wl1");
1312     processor1->OnLogEvent(event.get());
1313 
1314     // Metric 1 is not active; Activation 1 set to kActiveOnBoot
1315     // Metric 2 is active.
1316     // {{{---------------------------------------------------------------------------
1317     EXPECT_FALSE(metricProducer1_1->isActive());
1318     EXPECT_EQ(0, activation1_1_1->start_ns);
1319     EXPECT_EQ(kActiveOnBoot, activation1_1_1->state);
1320     EXPECT_EQ(0, activation1_1_2->start_ns);
1321     EXPECT_EQ(kNotActive, activation1_1_2->state);
1322 
1323     EXPECT_TRUE(metricProducer1_2->isActive());
1324     // }}}-----------------------------------------------------------------------------
1325 
1326     // Simulate shutdown by saving state to disk
1327     int64_t shutDownTime = timeBase1 + 100 * NS_PER_SEC;
1328     processor1->SaveActiveConfigsToDisk(shutDownTime);
1329     EXPECT_FALSE(metricProducer1_1->isActive());
1330 
1331     // Simulate device restarted state by creating new instance of StatsLogProcessor with the
1332     // same config.
1333     long timeBase2 = 1000;
1334     sp<StatsLogProcessor> processor2 =
1335             CreateStatsLogProcessor(timeBase2, timeBase2, config1, cfgKey1);
1336 
1337     // Metric 1 is not active.
1338     // Metric 2 is active.
1339     // {{{---------------------------------------------------------------------------
1340     ASSERT_EQ(1, processor2->mMetricsManagers.size());
1341     it = processor2->mMetricsManagers.find(cfgKey1);
1342     EXPECT_TRUE(it != processor2->mMetricsManagers.end());
1343     auto& metricsManager2 = it->second;
1344     EXPECT_TRUE(metricsManager2->isActive());
1345 
1346     ASSERT_EQ(metricsManager2->mAllMetricProducers.size(), 2);
1347     // We assume that the index of a MetricProducer within the mAllMetricProducers
1348     // array follows the order in which metrics are added to the config.
1349     auto& metricProducer2_1 = metricsManager2->mAllMetricProducers[0];
1350     EXPECT_EQ(metricProducer2_1->getMetricId(), metricId1);
1351     EXPECT_FALSE(metricProducer2_1->isActive());
1352 
1353     auto& metricProducer2_2 = metricsManager2->mAllMetricProducers[1];
1354     EXPECT_EQ(metricProducer2_2->getMetricId(), metricId2);
1355     EXPECT_TRUE(metricProducer2_2->isActive());
1356 
1357     ASSERT_EQ(metricProducer2_1->mEventActivationMap.size(), 2);
1358     // The key in mEventActivationMap is the index of the associated atom matcher. We assume
1359     // that matchers are indexed in the order that they are added to the config.
1360     const auto& activation2_1_1 = metricProducer2_1->mEventActivationMap.at(0);
1361     EXPECT_EQ(100 * NS_PER_SEC, activation2_1_1->ttl_ns);
1362     EXPECT_EQ(0, activation2_1_1->start_ns);
1363     EXPECT_EQ(kNotActive, activation2_1_1->state);
1364     EXPECT_EQ(ACTIVATE_ON_BOOT, activation2_1_1->activationType);
1365 
1366     const auto& activation2_1_2 = metricProducer2_1->mEventActivationMap.at(1);
1367     EXPECT_EQ(200 * NS_PER_SEC, activation2_1_2->ttl_ns);
1368     EXPECT_EQ(0, activation2_1_2->start_ns);
1369     EXPECT_EQ(kNotActive, activation2_1_2->state);
1370     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation2_1_2->activationType);
1371     // }}}-----------------------------------------------------------------------------------
1372 
1373     // Load saved state from disk.
1374     processor2->LoadActiveConfigsFromDisk();
1375 
1376     // Metric 1 active; Activation 1 is active, Activation 2 is not active
1377     // Metric 2 is active.
1378     // {{{---------------------------------------------------------------------------
1379     EXPECT_TRUE(metricProducer2_1->isActive());
1380     int64_t ttl1 = metric1ActivationTrigger1->ttl_seconds() * NS_PER_SEC;
1381     EXPECT_EQ(timeBase2 + ttl1 - activation2_1_1->ttl_ns, activation2_1_1->start_ns);
1382     EXPECT_EQ(kActive, activation2_1_1->state);
1383     EXPECT_EQ(0, activation2_1_2->start_ns);
1384     EXPECT_EQ(kNotActive, activation2_1_2->state);
1385 
1386     EXPECT_TRUE(metricProducer2_2->isActive());
1387     // }}}--------------------------------------------------------------------------------
1388 
1389     // Trigger Activation 2 for Metric 1.
1390     auto screenOnEvent =
1391             CreateScreenStateChangedEvent(timeBase2 + 200, android::view::DISPLAY_STATE_ON);
1392     processor2->OnLogEvent(screenOnEvent.get());
1393 
1394     // Metric 1 active; Activation 1 is active, Activation 2 is active
1395     // Metric 2 is active.
1396     // {{{---------------------------------------------------------------------------
1397     EXPECT_TRUE(metricProducer2_1->isActive());
1398     EXPECT_EQ(timeBase2 + ttl1 - activation2_1_1->ttl_ns, activation2_1_1->start_ns);
1399     EXPECT_EQ(kActive, activation2_1_1->state);
1400     EXPECT_EQ(screenOnEvent->GetElapsedTimestampNs(), activation2_1_2->start_ns);
1401     EXPECT_EQ(kActive, activation2_1_2->state);
1402 
1403     EXPECT_TRUE(metricProducer2_2->isActive());
1404     // }}}---------------------------------------------------------------------------
1405 
1406     // Simulate shutdown by saving state to disk
1407     shutDownTime = timeBase2 + 50 * NS_PER_SEC;
1408     processor2->SaveActiveConfigsToDisk(shutDownTime);
1409     EXPECT_TRUE(metricProducer2_1->isActive());
1410     EXPECT_TRUE(metricProducer2_2->isActive());
1411     ttl1 -= shutDownTime - timeBase2;
1412     int64_t ttl2 = metric1ActivationTrigger2->ttl_seconds() * NS_PER_SEC -
1413                    (shutDownTime - screenOnEvent->GetElapsedTimestampNs());
1414 
1415     // Simulate device restarted state by creating new instance of StatsLogProcessor with the
1416     // same config.
1417     long timeBase3 = timeBase2 + 120 * NS_PER_SEC;
1418     sp<StatsLogProcessor> processor3 =
1419             CreateStatsLogProcessor(timeBase3, timeBase3, config1, cfgKey1);
1420 
1421     // Metric 1 is not active.
1422     // Metric 2 is active.
1423     // {{{---------------------------------------------------------------------------
1424     ASSERT_EQ(1, processor3->mMetricsManagers.size());
1425     it = processor3->mMetricsManagers.find(cfgKey1);
1426     EXPECT_TRUE(it != processor3->mMetricsManagers.end());
1427     auto& metricsManager3 = it->second;
1428     EXPECT_TRUE(metricsManager3->isActive());
1429 
1430     ASSERT_EQ(metricsManager3->mAllMetricProducers.size(), 2);
1431     // We assume that the index of a MetricProducer within the mAllMetricProducers
1432     // array follows the order in which metrics are added to the config.
1433     auto& metricProducer3_1 = metricsManager3->mAllMetricProducers[0];
1434     EXPECT_EQ(metricProducer3_1->getMetricId(), metricId1);
1435     EXPECT_FALSE(metricProducer3_1->isActive());
1436 
1437     auto& metricProducer3_2 = metricsManager3->mAllMetricProducers[1];
1438     EXPECT_EQ(metricProducer3_2->getMetricId(), metricId2);
1439     EXPECT_TRUE(metricProducer3_2->isActive());
1440 
1441     ASSERT_EQ(metricProducer3_1->mEventActivationMap.size(), 2);
1442     // The key in mEventActivationMap is the index of the associated atom matcher. We assume
1443     // that matchers are indexed in the order that they are added to the config.
1444     const auto& activation3_1_1 = metricProducer3_1->mEventActivationMap.at(0);
1445     EXPECT_EQ(100 * NS_PER_SEC, activation3_1_1->ttl_ns);
1446     EXPECT_EQ(0, activation3_1_1->start_ns);
1447     EXPECT_EQ(kNotActive, activation3_1_1->state);
1448     EXPECT_EQ(ACTIVATE_ON_BOOT, activation3_1_1->activationType);
1449 
1450     const auto& activation3_1_2 = metricProducer3_1->mEventActivationMap.at(1);
1451     EXPECT_EQ(200 * NS_PER_SEC, activation3_1_2->ttl_ns);
1452     EXPECT_EQ(0, activation3_1_2->start_ns);
1453     EXPECT_EQ(kNotActive, activation3_1_2->state);
1454     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation3_1_2->activationType);
1455     // }}}----------------------------------------------------------------------------------
1456 
1457     // Load saved state from disk.
1458     processor3->LoadActiveConfigsFromDisk();
1459 
1460     // Metric 1 active: Activation 1 is active, Activation 2 is active
1461     // Metric 2 is active.
1462     // {{{---------------------------------------------------------------------------
1463     EXPECT_TRUE(metricProducer3_1->isActive());
1464     EXPECT_EQ(timeBase3 + ttl1 - activation3_1_1->ttl_ns, activation3_1_1->start_ns);
1465     EXPECT_EQ(kActive, activation3_1_1->state);
1466     EXPECT_EQ(timeBase3 + ttl2 - activation3_1_2->ttl_ns, activation3_1_2->start_ns);
1467     EXPECT_EQ(kActive, activation3_1_2->state);
1468 
1469     EXPECT_TRUE(metricProducer3_2->isActive());
1470     // }}}-------------------------------------------------------------------------------
1471 
1472     // Trigger Activation 2 for Metric 1 again.
1473     screenOnEvent = CreateScreenStateChangedEvent(timeBase3 + 100 * NS_PER_SEC,
1474                                                   android::view::DISPLAY_STATE_ON);
1475     processor3->OnLogEvent(screenOnEvent.get());
1476 
1477     // Metric 1 active; Activation 1 is inactive (above screenOnEvent causes ttl1 to expire),
1478     //                  Activation 2 is set to active
1479     // Metric 2 is active.
1480     // {{{---------------------------------------------------------------------------
1481     EXPECT_TRUE(metricProducer3_1->isActive());
1482     EXPECT_EQ(kNotActive, activation3_1_1->state);
1483     EXPECT_EQ(screenOnEvent->GetElapsedTimestampNs(), activation3_1_2->start_ns);
1484     EXPECT_EQ(kActive, activation3_1_2->state);
1485 
1486     EXPECT_TRUE(metricProducer3_2->isActive());
1487     // }}}---------------------------------------------------------------------------
1488 }
1489 
TEST(StatsLogProcessorTest,TestActivationsPersistAcrossSystemServerRestart)1490 TEST(StatsLogProcessorTest, TestActivationsPersistAcrossSystemServerRestart) {
1491     int uid = 9876;
1492     long configId = 12341;
1493 
1494     // Create config with 3 metrics:
1495     // Metric 1: Activate on 2 activations, 1 on boot, 1 immediate.
1496     // Metric 2: Activate on 2 activations, 1 on boot, 1 immediate.
1497     // Metric 3: Always active
1498     StatsdConfig config1;
1499     config1.set_id(configId);
1500     config1.add_allowed_log_source("AID_ROOT");  // LogEvent defaults to UID of root.
1501     auto wakelockAcquireMatcher = CreateAcquireWakelockAtomMatcher();
1502     auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
1503     auto jobStartMatcher = CreateStartScheduledJobAtomMatcher();
1504     auto jobFinishMatcher = CreateFinishScheduledJobAtomMatcher();
1505     *config1.add_atom_matcher() = wakelockAcquireMatcher;
1506     *config1.add_atom_matcher() = screenOnMatcher;
1507     *config1.add_atom_matcher() = jobStartMatcher;
1508     *config1.add_atom_matcher() = jobFinishMatcher;
1509 
1510     long metricId1 = 1234561;
1511     long metricId2 = 1234562;
1512     long metricId3 = 1234563;
1513 
1514     auto countMetric1 = config1.add_count_metric();
1515     countMetric1->set_id(metricId1);
1516     countMetric1->set_what(wakelockAcquireMatcher.id());
1517     countMetric1->set_bucket(FIVE_MINUTES);
1518 
1519     auto countMetric2 = config1.add_count_metric();
1520     countMetric2->set_id(metricId2);
1521     countMetric2->set_what(wakelockAcquireMatcher.id());
1522     countMetric2->set_bucket(FIVE_MINUTES);
1523 
1524     auto countMetric3 = config1.add_count_metric();
1525     countMetric3->set_id(metricId3);
1526     countMetric3->set_what(wakelockAcquireMatcher.id());
1527     countMetric3->set_bucket(FIVE_MINUTES);
1528 
1529     // Metric 1 activates on boot for wakelock acquire, immediately for screen on.
1530     auto metric1Activation = config1.add_metric_activation();
1531     metric1Activation->set_metric_id(metricId1);
1532     auto metric1ActivationTrigger1 = metric1Activation->add_event_activation();
1533     metric1ActivationTrigger1->set_atom_matcher_id(wakelockAcquireMatcher.id());
1534     metric1ActivationTrigger1->set_ttl_seconds(100);
1535     metric1ActivationTrigger1->set_activation_type(ACTIVATE_ON_BOOT);
1536     auto metric1ActivationTrigger2 = metric1Activation->add_event_activation();
1537     metric1ActivationTrigger2->set_atom_matcher_id(screenOnMatcher.id());
1538     metric1ActivationTrigger2->set_ttl_seconds(200);
1539     metric1ActivationTrigger2->set_activation_type(ACTIVATE_IMMEDIATELY);
1540 
1541     // Metric 2 activates on boot for scheduled job start, immediately for scheduled job finish.
1542     auto metric2Activation = config1.add_metric_activation();
1543     metric2Activation->set_metric_id(metricId2);
1544     auto metric2ActivationTrigger1 = metric2Activation->add_event_activation();
1545     metric2ActivationTrigger1->set_atom_matcher_id(jobStartMatcher.id());
1546     metric2ActivationTrigger1->set_ttl_seconds(100);
1547     metric2ActivationTrigger1->set_activation_type(ACTIVATE_ON_BOOT);
1548     auto metric2ActivationTrigger2 = metric2Activation->add_event_activation();
1549     metric2ActivationTrigger2->set_atom_matcher_id(jobFinishMatcher.id());
1550     metric2ActivationTrigger2->set_ttl_seconds(200);
1551     metric2ActivationTrigger2->set_activation_type(ACTIVATE_IMMEDIATELY);
1552 
1553     // Send the config.
1554     shared_ptr<StatsService> service = SharedRefBase::make<StatsService>(nullptr, nullptr);
1555     string serialized = config1.SerializeAsString();
1556     service->addConfigurationChecked(uid, configId, {serialized.begin(), serialized.end()});
1557 
1558     // Make sure the config is stored on disk. Otherwise, we will not reset on system server death.
1559     StatsdConfig tmpConfig;
1560     ConfigKey cfgKey1(uid, configId);
1561     EXPECT_TRUE(StorageManager::readConfigFromDisk(cfgKey1, &tmpConfig));
1562 
1563     // Metric 1 is not active.
1564     // Metric 2 is not active.
1565     // Metric 3 is active.
1566     // {{{---------------------------------------------------------------------------
1567     sp<StatsLogProcessor> processor = service->mProcessor;
1568     ASSERT_EQ(1, processor->mMetricsManagers.size());
1569     auto it = processor->mMetricsManagers.find(cfgKey1);
1570     EXPECT_TRUE(it != processor->mMetricsManagers.end());
1571     auto& metricsManager1 = it->second;
1572     EXPECT_TRUE(metricsManager1->isActive());
1573     ASSERT_EQ(3, metricsManager1->mAllMetricProducers.size());
1574 
1575     auto& metricProducer1 = metricsManager1->mAllMetricProducers[0];
1576     EXPECT_EQ(metricId1, metricProducer1->getMetricId());
1577     EXPECT_FALSE(metricProducer1->isActive());
1578 
1579     auto& metricProducer2 = metricsManager1->mAllMetricProducers[1];
1580     EXPECT_EQ(metricId2, metricProducer2->getMetricId());
1581     EXPECT_FALSE(metricProducer2->isActive());
1582 
1583     auto& metricProducer3 = metricsManager1->mAllMetricProducers[2];
1584     EXPECT_EQ(metricId3, metricProducer3->getMetricId());
1585     EXPECT_TRUE(metricProducer3->isActive());
1586 
1587     // Check event activations.
1588     ASSERT_EQ(metricsManager1->mAllAtomMatchers.size(), 4);
1589     EXPECT_EQ(metricsManager1->mAllAtomMatchers[0]->getId(),
1590               metric1ActivationTrigger1->atom_matcher_id());
1591     const auto& activation1 = metricProducer1->mEventActivationMap.at(0);
1592     EXPECT_EQ(100 * NS_PER_SEC, activation1->ttl_ns);
1593     EXPECT_EQ(0, activation1->start_ns);
1594     EXPECT_EQ(kNotActive, activation1->state);
1595     EXPECT_EQ(ACTIVATE_ON_BOOT, activation1->activationType);
1596 
1597     EXPECT_EQ(metricsManager1->mAllAtomMatchers[1]->getId(),
1598               metric1ActivationTrigger2->atom_matcher_id());
1599     const auto& activation2 = metricProducer1->mEventActivationMap.at(1);
1600     EXPECT_EQ(200 * NS_PER_SEC, activation2->ttl_ns);
1601     EXPECT_EQ(0, activation2->start_ns);
1602     EXPECT_EQ(kNotActive, activation2->state);
1603     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation2->activationType);
1604 
1605     EXPECT_EQ(metricsManager1->mAllAtomMatchers[2]->getId(),
1606               metric2ActivationTrigger1->atom_matcher_id());
1607     const auto& activation3 = metricProducer2->mEventActivationMap.at(2);
1608     EXPECT_EQ(100 * NS_PER_SEC, activation3->ttl_ns);
1609     EXPECT_EQ(0, activation3->start_ns);
1610     EXPECT_EQ(kNotActive, activation3->state);
1611     EXPECT_EQ(ACTIVATE_ON_BOOT, activation3->activationType);
1612 
1613     EXPECT_EQ(metricsManager1->mAllAtomMatchers[3]->getId(),
1614               metric2ActivationTrigger2->atom_matcher_id());
1615     const auto& activation4 = metricProducer2->mEventActivationMap.at(3);
1616     EXPECT_EQ(200 * NS_PER_SEC, activation4->ttl_ns);
1617     EXPECT_EQ(0, activation4->start_ns);
1618     EXPECT_EQ(kNotActive, activation4->state);
1619     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation4->activationType);
1620     // }}}------------------------------------------------------------------------------
1621 
1622     // Trigger Activation 1 for Metric 1. Should activate on boot.
1623     // Trigger Activation 4 for Metric 2. Should activate immediately.
1624     int64_t configAddedTimeNs = metricsManager1->mLastReportTimeNs;
1625     std::vector<int> attributionUids = {111};
1626     std::vector<string> attributionTags = {"App1"};
1627     std::unique_ptr<LogEvent> event1 = CreateAcquireWakelockEvent(
1628             1 + configAddedTimeNs, attributionUids, attributionTags, "wl1");
1629     processor->OnLogEvent(event1.get());
1630 
1631     std::unique_ptr<LogEvent> event2 = CreateFinishScheduledJobEvent(
1632             2 + configAddedTimeNs, attributionUids, attributionTags, "finish1");
1633     processor->OnLogEvent(event2.get());
1634 
1635     // Metric 1 is not active; Activation 1 set to kActiveOnBoot
1636     // Metric 2 is active. Activation 4 set to kActive
1637     // Metric 3 is active.
1638     // {{{---------------------------------------------------------------------------
1639     EXPECT_FALSE(metricProducer1->isActive());
1640     EXPECT_EQ(0, activation1->start_ns);
1641     EXPECT_EQ(kActiveOnBoot, activation1->state);
1642     EXPECT_EQ(0, activation2->start_ns);
1643     EXPECT_EQ(kNotActive, activation2->state);
1644 
1645     EXPECT_TRUE(metricProducer2->isActive());
1646     EXPECT_EQ(0, activation3->start_ns);
1647     EXPECT_EQ(kNotActive, activation3->state);
1648     EXPECT_EQ(2 + configAddedTimeNs, activation4->start_ns);
1649     EXPECT_EQ(kActive, activation4->state);
1650 
1651     EXPECT_TRUE(metricProducer3->isActive());
1652     // }}}-----------------------------------------------------------------------------
1653 
1654     // Can't fake time with StatsService.
1655     // Lets get a time close to the system server death time and make sure it's sane.
1656     int64_t approximateSystemServerDeath = getElapsedRealtimeNs();
1657     EXPECT_TRUE(approximateSystemServerDeath > 2 + configAddedTimeNs);
1658     EXPECT_TRUE(approximateSystemServerDeath < NS_PER_SEC + configAddedTimeNs);
1659 
1660     // System server dies.
1661     service->statsCompanionServiceDiedImpl();
1662 
1663     // We should have a new metrics manager. Lets get it and ensure activation status is restored.
1664     // {{{---------------------------------------------------------------------------
1665     ASSERT_EQ(1, processor->mMetricsManagers.size());
1666     it = processor->mMetricsManagers.find(cfgKey1);
1667     EXPECT_TRUE(it != processor->mMetricsManagers.end());
1668     auto& metricsManager2 = it->second;
1669     EXPECT_TRUE(metricsManager2->isActive());
1670     ASSERT_EQ(3, metricsManager2->mAllMetricProducers.size());
1671 
1672     auto& metricProducer1001 = metricsManager2->mAllMetricProducers[0];
1673     EXPECT_EQ(metricId1, metricProducer1001->getMetricId());
1674     EXPECT_FALSE(metricProducer1001->isActive());
1675 
1676     auto& metricProducer1002 = metricsManager2->mAllMetricProducers[1];
1677     EXPECT_EQ(metricId2, metricProducer1002->getMetricId());
1678     EXPECT_TRUE(metricProducer1002->isActive());
1679 
1680     auto& metricProducer1003 = metricsManager2->mAllMetricProducers[2];
1681     EXPECT_EQ(metricId3, metricProducer1003->getMetricId());
1682     EXPECT_TRUE(metricProducer1003->isActive());
1683 
1684     // Check event activations.
1685     // Activation 1 is kActiveOnBoot.
1686     // Activation 2 and 3 are not active.
1687     // Activation 4 is active.
1688     ASSERT_EQ(metricsManager2->mAllAtomMatchers.size(), 4);
1689     EXPECT_EQ(metricsManager2->mAllAtomMatchers[0]->getId(),
1690               metric1ActivationTrigger1->atom_matcher_id());
1691     const auto& activation1001 = metricProducer1001->mEventActivationMap.at(0);
1692     EXPECT_EQ(100 * NS_PER_SEC, activation1001->ttl_ns);
1693     EXPECT_EQ(0, activation1001->start_ns);
1694     EXPECT_EQ(kActiveOnBoot, activation1001->state);
1695     EXPECT_EQ(ACTIVATE_ON_BOOT, activation1001->activationType);
1696 
1697     EXPECT_EQ(metricsManager2->mAllAtomMatchers[1]->getId(),
1698               metric1ActivationTrigger2->atom_matcher_id());
1699     const auto& activation1002 = metricProducer1001->mEventActivationMap.at(1);
1700     EXPECT_EQ(200 * NS_PER_SEC, activation1002->ttl_ns);
1701     EXPECT_EQ(0, activation1002->start_ns);
1702     EXPECT_EQ(kNotActive, activation1002->state);
1703     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation1002->activationType);
1704 
1705     EXPECT_EQ(metricsManager2->mAllAtomMatchers[2]->getId(),
1706               metric2ActivationTrigger1->atom_matcher_id());
1707     const auto& activation1003 = metricProducer1002->mEventActivationMap.at(2);
1708     EXPECT_EQ(100 * NS_PER_SEC, activation1003->ttl_ns);
1709     EXPECT_EQ(0, activation1003->start_ns);
1710     EXPECT_EQ(kNotActive, activation1003->state);
1711     EXPECT_EQ(ACTIVATE_ON_BOOT, activation1003->activationType);
1712 
1713     EXPECT_EQ(metricsManager2->mAllAtomMatchers[3]->getId(),
1714               metric2ActivationTrigger2->atom_matcher_id());
1715     const auto& activation1004 = metricProducer1002->mEventActivationMap.at(3);
1716     EXPECT_EQ(200 * NS_PER_SEC, activation1004->ttl_ns);
1717     EXPECT_EQ(2 + configAddedTimeNs, activation1004->start_ns);
1718     EXPECT_EQ(kActive, activation1004->state);
1719     EXPECT_EQ(ACTIVATE_IMMEDIATELY, activation1004->activationType);
1720     // }}}------------------------------------------------------------------------------
1721 
1722     // Clear the data stored on disk as a result of the system server death.
1723     vector<uint8_t> buffer;
1724     processor->onDumpReport(cfgKey1, configAddedTimeNs + NS_PER_SEC, false, true, ADB_DUMP, FAST,
1725                             &buffer);
1726 }
1727 
TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid,LogHostUid)1728 TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid, LogHostUid) {
1729     int hostUid = 20;
1730     int isolatedUid = 30;
1731     uint64_t eventTimeNs = 12355;
1732     int atomId = 89;
1733     int field1 = 90;
1734     int field2 = 28;
1735     sp<MockUidMap> mockUidMap = makeMockUidMapForOneHost(hostUid, {isolatedUid});
1736     ConfigKey cfgKey;
1737     StatsdConfig config = MakeConfig(false);
1738     sp<StatsLogProcessor> processor =
1739             CreateStatsLogProcessor(1, 1, config, cfgKey, nullptr, 0, mockUidMap);
1740 
1741     shared_ptr<LogEvent> logEvent = makeUidLogEvent(atomId, eventTimeNs, hostUid, field1, field2);
1742 
1743     processor->OnLogEvent(logEvent.get());
1744 
1745     const vector<FieldValue>* actualFieldValues = &logEvent->getValues();
1746     ASSERT_EQ(3, actualFieldValues->size());
1747     EXPECT_EQ(hostUid, actualFieldValues->at(0).mValue.int_value);
1748     EXPECT_EQ(field1, actualFieldValues->at(1).mValue.int_value);
1749     EXPECT_EQ(field2, actualFieldValues->at(2).mValue.int_value);
1750 }
1751 
TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid,LogIsolatedUid)1752 TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid, LogIsolatedUid) {
1753     int hostUid = 20;
1754     int isolatedUid = 30;
1755     uint64_t eventTimeNs = 12355;
1756     int atomId = 89;
1757     int field1 = 90;
1758     int field2 = 28;
1759     sp<MockUidMap> mockUidMap = makeMockUidMapForOneHost(hostUid, {isolatedUid});
1760     ConfigKey cfgKey;
1761     StatsdConfig config = MakeConfig(false);
1762     sp<StatsLogProcessor> processor =
1763             CreateStatsLogProcessor(1, 1, config, cfgKey, nullptr, 0, mockUidMap);
1764 
1765     shared_ptr<LogEvent> logEvent =
1766             makeUidLogEvent(atomId, eventTimeNs, isolatedUid, field1, field2);
1767 
1768     processor->OnLogEvent(logEvent.get());
1769 
1770     const vector<FieldValue>* actualFieldValues = &logEvent->getValues();
1771     ASSERT_EQ(3, actualFieldValues->size());
1772     EXPECT_EQ(hostUid, actualFieldValues->at(0).mValue.int_value);
1773     EXPECT_EQ(field1, actualFieldValues->at(1).mValue.int_value);
1774     EXPECT_EQ(field2, actualFieldValues->at(2).mValue.int_value);
1775 }
1776 
TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid,LogHostUidAttributionChain)1777 TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid, LogHostUidAttributionChain) {
1778     int hostUid = 20;
1779     int isolatedUid = 30;
1780     uint64_t eventTimeNs = 12355;
1781     int atomId = 89;
1782     int field1 = 90;
1783     int field2 = 28;
1784     sp<MockUidMap> mockUidMap = makeMockUidMapForOneHost(hostUid, {isolatedUid});
1785     ConfigKey cfgKey;
1786     StatsdConfig config = MakeConfig(false);
1787     sp<StatsLogProcessor> processor =
1788             CreateStatsLogProcessor(1, 1, config, cfgKey, nullptr, 0, mockUidMap);
1789 
1790     shared_ptr<LogEvent> logEvent = makeAttributionLogEvent(atomId, eventTimeNs, {hostUid, 200},
1791                                                             {"tag1", "tag2"}, field1, field2);
1792 
1793     processor->OnLogEvent(logEvent.get());
1794 
1795     const vector<FieldValue>* actualFieldValues = &logEvent->getValues();
1796     ASSERT_EQ(6, actualFieldValues->size());
1797     EXPECT_EQ(hostUid, actualFieldValues->at(0).mValue.int_value);
1798     EXPECT_EQ("tag1", actualFieldValues->at(1).mValue.str_value);
1799     EXPECT_EQ(200, actualFieldValues->at(2).mValue.int_value);
1800     EXPECT_EQ("tag2", actualFieldValues->at(3).mValue.str_value);
1801     EXPECT_EQ(field1, actualFieldValues->at(4).mValue.int_value);
1802     EXPECT_EQ(field2, actualFieldValues->at(5).mValue.int_value);
1803 }
1804 
TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid,LogIsolatedUidAttributionChain)1805 TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid, LogIsolatedUidAttributionChain) {
1806     int hostUid = 20;
1807     int isolatedUid = 30;
1808     uint64_t eventTimeNs = 12355;
1809     int atomId = 89;
1810     int field1 = 90;
1811     int field2 = 28;
1812     sp<MockUidMap> mockUidMap = makeMockUidMapForOneHost(hostUid, {isolatedUid});
1813     ConfigKey cfgKey;
1814     StatsdConfig config = MakeConfig(false);
1815     sp<StatsLogProcessor> processor =
1816             CreateStatsLogProcessor(1, 1, config, cfgKey, nullptr, 0, mockUidMap);
1817 
1818     shared_ptr<LogEvent> logEvent = makeAttributionLogEvent(atomId, eventTimeNs, {isolatedUid, 200},
1819                                                             {"tag1", "tag2"}, field1, field2);
1820 
1821     processor->OnLogEvent(logEvent.get());
1822 
1823     const vector<FieldValue>* actualFieldValues = &logEvent->getValues();
1824     ASSERT_EQ(6, actualFieldValues->size());
1825     EXPECT_EQ(hostUid, actualFieldValues->at(0).mValue.int_value);
1826     EXPECT_EQ("tag1", actualFieldValues->at(1).mValue.str_value);
1827     EXPECT_EQ(200, actualFieldValues->at(2).mValue.int_value);
1828     EXPECT_EQ("tag2", actualFieldValues->at(3).mValue.str_value);
1829     EXPECT_EQ(field1, actualFieldValues->at(4).mValue.int_value);
1830     EXPECT_EQ(field2, actualFieldValues->at(5).mValue.int_value);
1831 }
1832 
TEST(StatsLogProcessorTest,TestDumpReportWithoutErasingDataDoesNotUpdateTimestamp)1833 TEST(StatsLogProcessorTest, TestDumpReportWithoutErasingDataDoesNotUpdateTimestamp) {
1834     int hostUid = 20;
1835     int isolatedUid = 30;
1836     sp<MockUidMap> mockUidMap = makeMockUidMapForOneHost(hostUid, {isolatedUid});
1837     ConfigKey key(3, 4);
1838 
1839     // TODO: All tests should not persist state on disk. This removes any reports that were present.
1840     ProtoOutputStream proto;
1841     StorageManager::appendConfigMetricsReport(key, &proto, /*erase data=*/true, /*isAdb=*/false);
1842 
1843     StatsdConfig config = MakeConfig(false);
1844     sp<StatsLogProcessor> processor =
1845             CreateStatsLogProcessor(1, 1, config, key, nullptr, 0, mockUidMap);
1846     vector<uint8_t> bytes;
1847 
1848     int64_t dumpTime1Ns = 1 * NS_PER_SEC;
1849     processor->onDumpReport(key, dumpTime1Ns, false /* include_current_bucket */,
1850             true /* erase_data */, ADB_DUMP, FAST, &bytes);
1851 
1852     ConfigMetricsReportList output;
1853     output.ParseFromArray(bytes.data(), bytes.size());
1854     EXPECT_EQ(output.reports_size(), 1);
1855     EXPECT_EQ(output.reports(0).current_report_elapsed_nanos(), dumpTime1Ns);
1856 
1857     int64_t dumpTime2Ns = 5 * NS_PER_SEC;
1858     processor->onDumpReport(key, dumpTime2Ns, false /* include_current_bucket */,
1859             false /* erase_data */, ADB_DUMP, FAST, &bytes);
1860 
1861     // Check that the dump report without clearing data is successful.
1862     output.ParseFromArray(bytes.data(), bytes.size());
1863     EXPECT_EQ(output.reports_size(), 1);
1864     EXPECT_EQ(output.reports(0).current_report_elapsed_nanos(), dumpTime2Ns);
1865     EXPECT_EQ(output.reports(0).last_report_elapsed_nanos(), dumpTime1Ns);
1866 
1867     int64_t dumpTime3Ns = 10 * NS_PER_SEC;
1868     processor->onDumpReport(key, dumpTime3Ns, false /* include_current_bucket */,
1869             true /* erase_data */, ADB_DUMP, FAST, &bytes);
1870 
1871     // Check that the previous dump report that didn't clear data did not overwrite the first dump's
1872     // timestamps.
1873     output.ParseFromArray(bytes.data(), bytes.size());
1874     EXPECT_EQ(output.reports_size(), 1);
1875     EXPECT_EQ(output.reports(0).current_report_elapsed_nanos(), dumpTime3Ns);
1876     EXPECT_EQ(output.reports(0).last_report_elapsed_nanos(), dumpTime1Ns);
1877 
1878 }
1879 
1880 #else
1881 GTEST_LOG_(INFO) << "This test does nothing.\n";
1882 #endif
1883 
1884 }  // namespace statsd
1885 }  // namespace os
1886 }  // namespace android
1887