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