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