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 #pragma once
16 
17 #include <aidl/android/os/BnPendingIntentRef.h>
18 #include <aidl/android/os/BnPullAtomCallback.h>
19 #include <aidl/android/os/BnStatsQueryCallback.h>
20 #include <aidl/android/os/BnStatsSubscriptionCallback.h>
21 #include <aidl/android/os/IPullAtomCallback.h>
22 #include <aidl/android/os/IPullAtomResultReceiver.h>
23 #include <aidl/android/os/StatsSubscriptionCallbackReason.h>
24 #include <gmock/gmock.h>
25 #include <gtest/gtest.h>
26 
27 #include "sdk_guard_util.h"
28 #include "src/StatsLogProcessor.h"
29 #include "src/StatsService.h"
30 #include "src/flags/FlagProvider.h"
31 #include "src/hash.h"
32 #include "src/logd/LogEvent.h"
33 #include "src/matchers/EventMatcherWizard.h"
34 #include "src/metrics/NumericValueMetricProducer.h"
35 #include "src/packages/UidMap.h"
36 #include "src/stats_log.pb.h"
37 #include "src/stats_log_util.h"
38 #include "src/statsd_config.pb.h"
39 #include "stats_annotations.h"
40 #include "stats_event.h"
41 #include "statslog_statsdtest.h"
42 #include "tests/metrics/metrics_test_helper.h"
43 
44 namespace android {
45 namespace os {
46 namespace statsd {
47 
48 using namespace testing;
49 using ::aidl::android::os::BnPullAtomCallback;
50 using ::aidl::android::os::BnStatsQueryCallback;
51 using ::aidl::android::os::BnStatsSubscriptionCallback;
52 using ::aidl::android::os::IPullAtomCallback;
53 using ::aidl::android::os::IPullAtomResultReceiver;
54 using ::aidl::android::os::StatsSubscriptionCallbackReason;
55 using android::util::ProtoReader;
56 using google::protobuf::RepeatedPtrField;
57 using Status = ::ndk::ScopedAStatus;
58 using PackageInfoSnapshot = UidMapping_PackageInfoSnapshot;
59 using PackageInfo = UidMapping_PackageInfoSnapshot_PackageInfo;
60 using ::ndk::SharedRefBase;
61 
62 // Wrapper for assertion helpers called from tests to keep track of source location of failures.
63 // Example usage:
64 //      static void myTestVerificationHelper(Foo foo) {
65 //          EXPECT_EQ(...);
66 //          ASSERT_EQ(...);
67 //      }
68 //
69 //      TEST_F(MyTest, TestFoo) {
70 //          ...
71 //          TRACE_CALL(myTestVerificationHelper, foo);
72 //          ...
73 //      }
74 //
75 #define TRACE_CALL(function, ...) \
76     do {                          \
77         SCOPED_TRACE("");         \
78         (function)(__VA_ARGS__);  \
79     } while (false)
80 
81 const int SCREEN_STATE_ATOM_ID = util::SCREEN_STATE_CHANGED;
82 const int UID_PROCESS_STATE_ATOM_ID = util::UID_PROCESS_STATE_CHANGED;
83 
84 enum BucketSplitEvent { APP_UPGRADE, BOOT_COMPLETE };
85 
86 class MockUidMap : public UidMap {
87 public:
88     MOCK_METHOD(int, getHostUidOrSelf, (int uid), (const));
89     MOCK_METHOD(std::set<int32_t>, getAppUid, (const string& package), (const));
90 };
91 
92 class BasicMockLogEventFilter : public LogEventFilter {
93 public:
94     MOCK_METHOD(void, setFilteringEnabled, (bool isEnabled), (override));
95     MOCK_METHOD(void, setAtomIds, (AtomIdSet tagIds, ConsumerId consumer), (override));
96 };
97 
98 class MockPendingIntentRef : public aidl::android::os::BnPendingIntentRef {
99 public:
100     MOCK_METHOD1(sendDataBroadcast, Status(int64_t lastReportTimeNs));
101     MOCK_METHOD1(sendActiveConfigsChangedBroadcast, Status(const vector<int64_t>& configIds));
102     MOCK_METHOD1(sendRestrictedMetricsChangedBroadcast, Status(const vector<int64_t>& metricIds));
103     MOCK_METHOD6(sendSubscriberBroadcast,
104                  Status(int64_t configUid, int64_t configId, int64_t subscriptionId,
105                         int64_t subscriptionRuleId, const vector<string>& cookies,
106                         const StatsDimensionsValueParcel& dimensionsValueParcel));
107 };
108 
109 typedef StrictMock<BasicMockLogEventFilter> MockLogEventFilter;
110 
111 class MockStatsQueryCallback : public BnStatsQueryCallback {
112 public:
113     MOCK_METHOD4(sendResults,
114                  Status(const vector<string>& queryData, const vector<string>& columnNames,
115                         const vector<int32_t>& columnTypes, int32_t rowCount));
116     MOCK_METHOD1(sendFailure, Status(const string& in_error));
117 };
118 
119 class MockStatsSubscriptionCallback : public BnStatsSubscriptionCallback {
120 public:
121     MOCK_METHOD(Status, onSubscriptionData,
122                 (StatsSubscriptionCallbackReason in_reason,
123                  const std::vector<uint8_t>& in_subscriptionPayload),
124                 (override));
125 };
126 
127 class StatsServiceConfigTest : public ::testing::Test {
128 protected:
129     shared_ptr<StatsService> service;
130     const int kConfigKey = 789130123;  // Randomly chosen
131     const int kCallingUid = 10100;     // Randomly chosen
132 
SetUp()133     void SetUp() override {
134         service = createStatsService();
135         // Removing config file from data/misc/stats-service and data/misc/stats-data if present
136         ConfigKey configKey(kCallingUid, kConfigKey);
137         service->removeConfiguration(kConfigKey, kCallingUid);
138         service->mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
139                                           false /* include_current_bucket*/, true /* erase_data */,
140                                           ADB_DUMP, NO_TIME_CONSTRAINTS, nullptr);
141     }
142 
TearDown()143     void TearDown() override {
144         // Cleaning up data/misc/stats-service and data/misc/stats-data
145         ConfigKey configKey(kCallingUid, kConfigKey);
146         service->removeConfiguration(kConfigKey, kCallingUid);
147         service->mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
148                                           false /* include_current_bucket*/, true /* erase_data */,
149                                           ADB_DUMP, NO_TIME_CONSTRAINTS, nullptr);
150     }
151 
createStatsService()152     virtual shared_ptr<StatsService> createStatsService() {
153         return SharedRefBase::make<StatsService>(new UidMap(), /* queue */ nullptr,
154                                                  std::make_shared<LogEventFilter>());
155     }
156 
157     bool sendConfig(const StatsdConfig& config);
158 
159     ConfigMetricsReport getReports(sp<StatsLogProcessor> processor, int64_t timestamp,
160                                    bool include_current = false);
161 };
162 
163 static void assertConditionTimer(const ConditionTimer& conditionTimer, bool condition,
164                                  int64_t timerNs, int64_t lastConditionTrueTimestampNs,
165                                  int64_t currentBucketStartDelayNs = 0) {
166     EXPECT_EQ(condition, conditionTimer.mCondition);
167     EXPECT_EQ(timerNs, conditionTimer.mTimerNs);
168     EXPECT_EQ(lastConditionTrueTimestampNs, conditionTimer.mLastConditionChangeTimestampNs);
169     EXPECT_EQ(currentBucketStartDelayNs, conditionTimer.mCurrentBucketStartDelayNs);
170 }
171 
172 // Converts a ProtoOutputStream to a StatsLogReport proto.
173 StatsLogReport outputStreamToProto(ProtoOutputStream* proto);
174 
175 // Create AtomMatcher proto to simply match a specific atom type.
176 AtomMatcher CreateSimpleAtomMatcher(const string& name, int atomId);
177 
178 // Create AtomMatcher proto for temperature atom.
179 AtomMatcher CreateTemperatureAtomMatcher();
180 
181 // Create AtomMatcher proto for scheduled job state changed.
182 AtomMatcher CreateScheduledJobStateChangedAtomMatcher();
183 
184 // Create AtomMatcher proto for starting a scheduled job.
185 AtomMatcher CreateStartScheduledJobAtomMatcher();
186 
187 // Create AtomMatcher proto for a scheduled job is done.
188 AtomMatcher CreateFinishScheduledJobAtomMatcher();
189 
190 // Create AtomMatcher proto for cancelling a scheduled job.
191 AtomMatcher CreateScheduleScheduledJobAtomMatcher();
192 
193 // Create AtomMatcher proto for screen brightness state changed.
194 AtomMatcher CreateScreenBrightnessChangedAtomMatcher();
195 
196 // Create AtomMatcher proto for starting battery save mode.
197 AtomMatcher CreateBatterySaverModeStartAtomMatcher();
198 
199 // Create AtomMatcher proto for stopping battery save mode.
200 AtomMatcher CreateBatterySaverModeStopAtomMatcher();
201 
202 // Create AtomMatcher proto for battery state none mode.
203 AtomMatcher CreateBatteryStateNoneMatcher();
204 
205 // Create AtomMatcher proto for battery state usb mode.
206 AtomMatcher CreateBatteryStateUsbMatcher();
207 
208 // Create AtomMatcher proto for process state changed.
209 AtomMatcher CreateUidProcessStateChangedAtomMatcher();
210 
211 // Create AtomMatcher proto for acquiring wakelock.
212 AtomMatcher CreateAcquireWakelockAtomMatcher();
213 
214 // Create AtomMatcher proto for releasing wakelock.
215 AtomMatcher CreateReleaseWakelockAtomMatcher() ;
216 
217 // Create AtomMatcher proto for screen turned on.
218 AtomMatcher CreateScreenTurnedOnAtomMatcher();
219 
220 // Create AtomMatcher proto for screen turned off.
221 AtomMatcher CreateScreenTurnedOffAtomMatcher();
222 
223 // Create AtomMatcher proto for app sync turned on.
224 AtomMatcher CreateSyncStartAtomMatcher();
225 
226 // Create AtomMatcher proto for app sync turned off.
227 AtomMatcher CreateSyncEndAtomMatcher();
228 
229 // Create AtomMatcher proto for app sync moves to background.
230 AtomMatcher CreateMoveToBackgroundAtomMatcher();
231 
232 // Create AtomMatcher proto for app sync moves to foreground.
233 AtomMatcher CreateMoveToForegroundAtomMatcher();
234 
235 // Create AtomMatcher proto for process crashes
236 AtomMatcher CreateProcessCrashAtomMatcher();
237 
238 // Create AtomMatcher proto for app launches.
239 AtomMatcher CreateAppStartOccurredAtomMatcher();
240 
241 // Create AtomMatcher proto for test atom repeated state.
242 AtomMatcher CreateTestAtomRepeatedStateAtomMatcher(const string& name,
243                                                    TestAtomReported::State state,
244                                                    Position position);
245 
246 // Create AtomMatcher proto for test atom repeated state is off, first position.
247 AtomMatcher CreateTestAtomRepeatedStateFirstOffAtomMatcher();
248 
249 // Create AtomMatcher proto for test atom repeated state is on, first position.
250 AtomMatcher CreateTestAtomRepeatedStateFirstOnAtomMatcher();
251 
252 // Create AtomMatcher proto for test atom repeated state is on, any position.
253 AtomMatcher CreateTestAtomRepeatedStateAnyOnAtomMatcher();
254 
255 // Add an AtomMatcher to a combination AtomMatcher.
256 void addMatcherToMatcherCombination(const AtomMatcher& matcher, AtomMatcher* combinationMatcher);
257 
258 // Create Predicate proto for screen is on.
259 Predicate CreateScreenIsOnPredicate();
260 
261 // Create Predicate proto for screen is off.
262 Predicate CreateScreenIsOffPredicate();
263 
264 // Create Predicate proto for a running scheduled job.
265 Predicate CreateScheduledJobPredicate();
266 
267 // Create Predicate proto for battery saver mode.
268 Predicate CreateBatterySaverModePredicate();
269 
270 // Create Predicate proto for device unplogged mode.
271 Predicate CreateDeviceUnpluggedPredicate();
272 
273 // Create Predicate proto for holding wakelock.
274 Predicate CreateHoldingWakelockPredicate();
275 
276 // Create a Predicate proto for app syncing.
277 Predicate CreateIsSyncingPredicate();
278 
279 // Create a Predicate proto for app is in background.
280 Predicate CreateIsInBackgroundPredicate();
281 
282 // Create a Predicate proto for test atom repeated state field is off.
283 Predicate CreateTestAtomRepeatedStateFirstOffPredicate();
284 
285 // Create State proto for screen state atom.
286 State CreateScreenState();
287 
288 // Create State proto for uid process state atom.
289 State CreateUidProcessState();
290 
291 // Create State proto for overlay state atom.
292 State CreateOverlayState();
293 
294 // Create State proto for screen state atom with on/off map.
295 State CreateScreenStateWithOnOffMap(int64_t screenOnId, int64_t screenOffId);
296 
297 // Create State proto for screen state atom with simple on/off map.
298 State CreateScreenStateWithSimpleOnOffMap(int64_t screenOnId, int64_t screenOffId);
299 
300 // Create StateGroup proto for ScreenState ON group
301 StateMap_StateGroup CreateScreenStateOnGroup(int64_t screenOnId);
302 
303 // Create StateGroup proto for ScreenState OFF group
304 StateMap_StateGroup CreateScreenStateOffGroup(int64_t screenOffId);
305 
306 // Create StateGroup proto for simple ScreenState ON group
307 StateMap_StateGroup CreateScreenStateSimpleOnGroup(int64_t screenOnId);
308 
309 // Create StateGroup proto for simple ScreenState OFF group
310 StateMap_StateGroup CreateScreenStateSimpleOffGroup(int64_t screenOffId);
311 
312 // Create StateMap proto for ScreenState ON/OFF map
313 StateMap CreateScreenStateOnOffMap(int64_t screenOnId, int64_t screenOffId);
314 
315 // Create StateMap proto for simple ScreenState ON/OFF map
316 StateMap CreateScreenStateSimpleOnOffMap(int64_t screenOnId, int64_t screenOffId);
317 
318 // Add a predicate to the predicate combination.
319 void addPredicateToPredicateCombination(const Predicate& predicate, Predicate* combination);
320 
321 // Create dimensions from primitive fields.
322 FieldMatcher CreateDimensions(const int atomId, const std::vector<int>& fields);
323 
324 // Create dimensions from repeated primitive fields.
325 FieldMatcher CreateRepeatedDimensions(const int atomId, const std::vector<int>& fields,
326                                       const std::vector<Position>& positions);
327 
328 // Create dimensions by attribution uid and tag.
329 FieldMatcher CreateAttributionUidAndTagDimensions(const int atomId,
330                                                   const std::vector<Position>& positions);
331 
332 // Create dimensions by attribution uid only.
333 FieldMatcher CreateAttributionUidDimensions(const int atomId,
334                                             const std::vector<Position>& positions);
335 
336 FieldMatcher CreateAttributionUidAndOtherDimensions(const int atomId,
337                                                     const std::vector<Position>& positions,
338                                                     const std::vector<int>& fields);
339 
340 EventMetric createEventMetric(const string& name, int64_t what, const optional<int64_t>& condition);
341 
342 CountMetric createCountMetric(const string& name, int64_t what, const optional<int64_t>& condition,
343                               const vector<int64_t>& states);
344 
345 DurationMetric createDurationMetric(const string& name, int64_t what,
346                                     const optional<int64_t>& condition,
347                                     const vector<int64_t>& states);
348 
349 GaugeMetric createGaugeMetric(const string& name, int64_t what,
350                               const GaugeMetric::SamplingType samplingType,
351                               const optional<int64_t>& condition,
352                               const optional<int64_t>& triggerEvent);
353 
354 ValueMetric createValueMetric(const string& name, const AtomMatcher& what, int valueField,
355                               const optional<int64_t>& condition, const vector<int64_t>& states);
356 
357 ValueMetric createValueMetric(const string& name, const AtomMatcher& what,
358                               const vector<int>& valueFields,
359                               const vector<ValueMetric::AggregationType>& aggregationTypes,
360                               const optional<int64_t>& condition, const vector<int64_t>& states);
361 
362 HistogramBinConfig createGeneratedBinConfig(int id, float min, float max, int count,
363                                             HistogramBinConfig::GeneratedBins::Strategy strategy);
364 
365 HistogramBinConfig createExplicitBinConfig(int id, const std::vector<float>& bins);
366 
367 KllMetric createKllMetric(const string& name, const AtomMatcher& what, int kllField,
368                           const optional<int64_t>& condition);
369 
370 Alert createAlert(const string& name, int64_t metricId, int buckets, const int64_t triggerSum);
371 
372 Alarm createAlarm(const string& name, int64_t offsetMillis, int64_t periodMillis);
373 
374 Subscription createSubscription(const string& name, const Subscription_RuleType type,
375                                 const int64_t ruleId);
376 
377 // START: get primary key functions
378 // These functions take in atom field information and create FieldValues which are stored in the
379 // given HashableDimensionKey.
380 void getUidProcessKey(int uid, HashableDimensionKey* key);
381 
382 void getOverlayKey(int uid, string packageName, HashableDimensionKey* key);
383 
384 void getPartialWakelockKey(int uid, const std::string& tag, HashableDimensionKey* key);
385 
386 void getPartialWakelockKey(int uid, HashableDimensionKey* key);
387 // END: get primary key functions
388 
389 void writeAttribution(AStatsEvent* statsEvent, const vector<int>& attributionUids,
390                       const vector<string>& attributionTags);
391 
392 // Builds statsEvent to get buffer that is parsed into logEvent then releases statsEvent.
393 bool parseStatsEventToLogEvent(AStatsEvent* statsEvent, LogEvent* logEvent);
394 
395 AStatsEvent* makeTwoValueStatsEvent(int atomId, int64_t eventTimeNs, int32_t value1,
396                                     int32_t value2);
397 
398 shared_ptr<LogEvent> CreateTwoValueLogEvent(int atomId, int64_t eventTimeNs, int32_t value1,
399                                             int32_t value2);
400 
401 void CreateTwoValueLogEvent(LogEvent* logEvent, int atomId, int64_t eventTimeNs, int32_t value1,
402                             int32_t value2);
403 
404 shared_ptr<LogEvent> CreateThreeValueLogEvent(int atomId, int64_t eventTimeNs, int32_t value1,
405                                               int32_t value2, int32_t value3);
406 
407 void CreateThreeValueLogEvent(LogEvent* logEvent, int atomId, int64_t eventTimeNs, int32_t value1,
408                               int32_t value2, int32_t value3);
409 
410 // The repeated value log event helpers create a log event with two int fields, both
411 // set to the same value. This is useful for testing metrics that are only interested
412 // in the value of the second field but still need the first field to be populated.
413 std::shared_ptr<LogEvent> CreateRepeatedValueLogEvent(int atomId, int64_t eventTimeNs,
414                                                       int32_t value);
415 
416 void CreateRepeatedValueLogEvent(LogEvent* logEvent, int atomId, int64_t eventTimeNs,
417                                  int32_t value);
418 
419 std::shared_ptr<LogEvent> CreateNoValuesLogEvent(int atomId, int64_t eventTimeNs);
420 
421 void CreateNoValuesLogEvent(LogEvent* logEvent, int atomId, int64_t eventTimeNs);
422 
423 AStatsEvent* makeAttributionStatsEvent(int atomId, int64_t eventTimeNs, const vector<int>& uids,
424                                        const vector<string>& tags, int data1, int data2);
425 
426 AStatsEvent* makeUidStatsEvent(int atomId, int64_t eventTimeNs, int uid, int data1, int data2);
427 
428 AStatsEvent* makeUidStatsEvent(int atomId, int64_t eventTimeNs, int uid, int data1,
429                                const vector<int>& data2) __INTRODUCED_IN(__ANDROID_API_T__);
430 
431 std::shared_ptr<LogEvent> makeUidLogEvent(int atomId, int64_t eventTimeNs, int uid, int data1,
432                                           int data2);
433 
434 std::shared_ptr<LogEvent> makeUidLogEvent(int atomId, int64_t eventTimeNs, int uid, int data1,
435                                           const vector<int>& data2)
436         __INTRODUCED_IN(__ANDROID_API_T__);
437 
438 shared_ptr<LogEvent> makeExtraUidsLogEvent(int atomId, int64_t eventTimeNs, int uid1, int data1,
439                                            int data2, const std::vector<int>& extraUids);
440 
441 std::shared_ptr<LogEvent> makeRepeatedUidLogEvent(int atomId, int64_t eventTimeNs,
442                                                   const std::vector<int>& uids)
443         __INTRODUCED_IN(__ANDROID_API_T__);
444 
445 shared_ptr<LogEvent> makeRepeatedUidLogEvent(int atomId, int64_t eventTimeNs,
446                                              const vector<int>& uids, int data1, int data2)
447         __INTRODUCED_IN(__ANDROID_API_T__);
448 
449 shared_ptr<LogEvent> makeRepeatedUidLogEvent(int atomId, int64_t eventTimeNs,
450                                              const vector<int>& uids, int data1,
451                                              const vector<int>& data2)
452         __INTRODUCED_IN(__ANDROID_API_T__);
453 
454 std::shared_ptr<LogEvent> makeAttributionLogEvent(int atomId, int64_t eventTimeNs,
455                                                   const vector<int>& uids,
456                                                   const vector<string>& tags, int data1, int data2);
457 
458 sp<MockUidMap> makeMockUidMapForHosts(const map<int, vector<int>>& hostUidToIsolatedUidsMap);
459 
460 sp<MockUidMap> makeMockUidMapForPackage(const string& pkg, const set<int32_t>& uids);
461 
462 // Create log event for screen state changed.
463 std::unique_ptr<LogEvent> CreateScreenStateChangedEvent(uint64_t timestampNs,
464                                                         const android::view::DisplayStateEnum state,
465                                                         int loggerUid = 0);
466 
467 // Create log event for screen brightness state changed.
468 std::unique_ptr<LogEvent> CreateScreenBrightnessChangedEvent(uint64_t timestampNs, int level);
469 
470 // Create log event when scheduled job starts.
471 std::unique_ptr<LogEvent> CreateStartScheduledJobEvent(uint64_t timestampNs,
472                                                        const vector<int>& attributionUids,
473                                                        const vector<string>& attributionTags,
474                                                        const string& jobName);
475 
476 // Create log event when scheduled job finishes.
477 std::unique_ptr<LogEvent> CreateFinishScheduledJobEvent(uint64_t timestampNs,
478                                                         const vector<int>& attributionUids,
479                                                         const vector<string>& attributionTags,
480                                                         const string& jobName);
481 
482 // Create log event when scheduled job schedules.
483 std::unique_ptr<LogEvent> CreateScheduleScheduledJobEvent(uint64_t timestampNs,
484                                                           const vector<int>& attributionUids,
485                                                           const vector<string>& attributionTags,
486                                                           const string& jobName);
487 
488 // Create log event when battery saver starts.
489 std::unique_ptr<LogEvent> CreateBatterySaverOnEvent(uint64_t timestampNs);
490 // Create log event when battery saver stops.
491 std::unique_ptr<LogEvent> CreateBatterySaverOffEvent(uint64_t timestampNs);
492 
493 // Create log event when battery state changes.
494 std::unique_ptr<LogEvent> CreateBatteryStateChangedEvent(const uint64_t timestampNs,
495                                                          const BatteryPluggedStateEnum state,
496                                                          int32_t uid = AID_ROOT);
497 
498 // Create malformed log event for battery state change.
499 std::unique_ptr<LogEvent> CreateMalformedBatteryStateChangedEvent(const uint64_t timestampNs);
500 
501 std::unique_ptr<LogEvent> CreateActivityForegroundStateChangedEvent(
502         uint64_t timestampNs, const int uid, const string& pkgName, const string& className,
503         const ActivityForegroundStateChanged::State state);
504 
505 // Create log event for app moving to background.
506 std::unique_ptr<LogEvent> CreateMoveToBackgroundEvent(uint64_t timestampNs, int uid);
507 
508 // Create log event for app moving to foreground.
509 std::unique_ptr<LogEvent> CreateMoveToForegroundEvent(uint64_t timestampNs, int uid);
510 
511 // Create log event when the app sync starts.
512 std::unique_ptr<LogEvent> CreateSyncStartEvent(uint64_t timestampNs, const vector<int>& uids,
513                                                const vector<string>& tags, const string& name);
514 
515 // Create log event when the app sync ends.
516 std::unique_ptr<LogEvent> CreateSyncEndEvent(uint64_t timestampNs, const vector<int>& uids,
517                                              const vector<string>& tags, const string& name);
518 
519 // Create log event when the app sync ends.
520 std::unique_ptr<LogEvent> CreateAppCrashEvent(uint64_t timestampNs, int uid);
521 
522 // Create log event for an app crash.
523 std::unique_ptr<LogEvent> CreateAppCrashOccurredEvent(uint64_t timestampNs, int uid);
524 
525 // Create log event for acquiring wakelock.
526 std::unique_ptr<LogEvent> CreateAcquireWakelockEvent(uint64_t timestampNs, const vector<int>& uids,
527                                                      const vector<string>& tags,
528                                                      const string& wakelockName);
529 
530 // Create log event for releasing wakelock.
531 std::unique_ptr<LogEvent> CreateReleaseWakelockEvent(uint64_t timestampNs, const vector<int>& uids,
532                                                      const vector<string>& tags,
533                                                      const string& wakelockName);
534 
535 // Create log event for releasing wakelock.
536 std::unique_ptr<LogEvent> CreateIsolatedUidChangedEvent(uint64_t timestampNs, int hostUid,
537                                                         int isolatedUid, bool is_create);
538 
539 // Create log event for uid process state change.
540 std::unique_ptr<LogEvent> CreateUidProcessStateChangedEvent(
541         uint64_t timestampNs, int uid, const android::app::ProcessStateEnum state);
542 
543 std::unique_ptr<LogEvent> CreateBleScanStateChangedEvent(uint64_t timestampNs,
544                                                          const vector<int>& attributionUids,
545                                                          const vector<string>& attributionTags,
546                                                          const BleScanStateChanged::State state,
547                                                          const bool filtered, const bool firstMatch,
548                                                          const bool opportunistic);
549 
550 std::unique_ptr<LogEvent> CreateOverlayStateChangedEvent(int64_t timestampNs, const int32_t uid,
551                                                          const string& packageName,
552                                                          const bool usingAlertWindow,
553                                                          const OverlayStateChanged::State state);
554 
555 std::unique_ptr<LogEvent> CreateAppStartOccurredEvent(
556         uint64_t timestampNs, int uid, const string& pkg_name,
557         AppStartOccurred::TransitionType type, const string& activity_name,
558         const string& calling_pkg_name, const bool is_instant_app, int64_t activity_start_msec);
559 
560 std::unique_ptr<LogEvent> CreateBleScanResultReceivedEvent(uint64_t timestampNs,
561                                                            const vector<int>& attributionUids,
562                                                            const vector<string>& attributionTags,
563                                                            const int numResults);
564 
565 std::unique_ptr<LogEvent> CreateTestAtomReportedEventVariableRepeatedFields(
566         uint64_t timestampNs, const vector<int>& repeatedIntField,
567         const vector<int64_t>& repeatedLongField, const vector<float>& repeatedFloatField,
568         const vector<string>& repeatedStringField, const bool* repeatedBoolField,
569         const size_t repeatedBoolFieldLength, const vector<int>& repeatedEnumField);
570 
571 std::unique_ptr<LogEvent> CreateTestAtomReportedEventWithPrimitives(
572         uint64_t timestampNs, int intField, long longField, float floatField,
573         const string& stringField, bool boolField, TestAtomReported::State enumField);
574 
575 std::unique_ptr<LogEvent> CreateRestrictedLogEvent(int atomTag, int64_t timestampNs = 0);
576 std::unique_ptr<LogEvent> CreateNonRestrictedLogEvent(int atomTag, int64_t timestampNs = 0);
577 
578 std::unique_ptr<LogEvent> CreatePhoneSignalStrengthChangedEvent(
579         int64_t timestampNs, ::telephony::SignalStrengthEnum state);
580 
581 std::unique_ptr<LogEvent> CreateTestAtomReportedEvent(
582         uint64_t timestampNs, const vector<int>& attributionUids,
583         const vector<string>& attributionTags, int intField, const long longField,
584         const float floatField, const string& stringField, const bool boolField,
585         const TestAtomReported::State enumField, const vector<uint8_t>& bytesField,
586         const vector<int>& repeatedIntField, const vector<int64_t>& repeatedLongField,
587         const vector<float>& repeatedFloatField, const vector<string>& repeatedStringField,
588         const bool* repeatedBoolField, const size_t repeatedBoolFieldLength,
589         const vector<int>& repeatedEnumField);
590 
591 void createStatsEvent(AStatsEvent* statsEvent, uint8_t typeId, uint32_t atomId);
592 
593 void fillStatsEventWithSampleValue(AStatsEvent* statsEvent, uint8_t typeId);
594 
595 SocketLossInfo createSocketLossInfo(int32_t uid, int32_t atomId);
596 
597 // helper API to create STATS_SOCKET_LOSS_REPORTED LogEvent
598 std::unique_ptr<LogEvent> createSocketLossInfoLogEvent(int32_t uid, int32_t lossAtomId)
599         __INTRODUCED_IN(__ANDROID_API_T__);
600 
601 // Create a statsd log event processor upon the start time in seconds, config and key.
602 sp<StatsLogProcessor> CreateStatsLogProcessor(
603         const int64_t timeBaseNs, int64_t currentTimeNs, const StatsdConfig& config,
604         const ConfigKey& key, const shared_ptr<IPullAtomCallback>& puller = nullptr,
605         const int32_t atomTag = 0 /*for puller only*/, const sp<UidMap> = new UidMap(),
606         const shared_ptr<LogEventFilter>& logEventFilter = std::make_shared<LogEventFilter>());
607 
608 sp<NumericValueMetricProducer> createNumericValueMetricProducer(
609         sp<MockStatsPullerManager>& pullerManager, const ValueMetric& metric, const int atomId,
610         bool isPulled, const ConfigKey& configKey, const uint64_t protoHash,
611         const int64_t timeBaseNs, const int64_t startTimeNs, const int logEventMatcherIndex,
612         optional<ConditionState> conditionAfterFirstBucketPrepared = nullopt,
613         vector<int32_t> slicedStateAtoms = {},
614         unordered_map<int, unordered_map<int, int64_t>> stateGroupMap = {},
615         sp<EventMatcherWizard> eventMatcherWizard = nullptr);
616 
617 LogEventFilter::AtomIdSet CreateAtomIdSetDefault();
618 LogEventFilter::AtomIdSet CreateAtomIdSetFromConfig(const StatsdConfig& config);
619 
620 // Util function to sort the log events by timestamp.
621 void sortLogEventsByTimestamp(std::vector<std::unique_ptr<LogEvent>> *events);
622 
623 int64_t StringToId(const string& str);
624 
625 sp<EventMatcherWizard> createEventMatcherWizard(
626         int tagId, int matcherIndex, const std::vector<FieldValueMatcher>& fieldValueMatchers = {});
627 
628 StatsDimensionsValueParcel CreateAttributionUidDimensionsValueParcel(const int atomId,
629                                                                      const int uid);
630 
631 void ValidateUidDimension(const DimensionsValue& value, int atomId, int uid);
632 void ValidateWakelockAttributionUidAndTagDimension(const DimensionsValue& value, int atomId,
633                                                    const int uid, const string& tag);
634 void ValidateUidDimension(const DimensionsValue& value, int node_idx, int atomId, int uid);
635 void ValidateAttributionUidDimension(const DimensionsValue& value, int atomId, int uid);
636 void ValidateAttributionUidAndTagDimension(
637     const DimensionsValue& value, int atomId, int uid, const std::string& tag);
638 void ValidateAttributionUidAndTagDimension(
639     const DimensionsValue& value, int node_idx, int atomId, int uid, const std::string& tag);
640 void ValidateStateValue(const google::protobuf::RepeatedPtrField<StateValue>& stateValues,
641                         int atomId, int64_t value);
642 
643 void ValidateCountBucket(const CountBucketInfo& countBucket, int64_t startTimeNs, int64_t endTimeNs,
644                          int64_t count, int64_t conditionTrueNs = 0);
645 void ValidateDurationBucket(const DurationBucketInfo& bucket, int64_t startTimeNs,
646                             int64_t endTimeNs, int64_t durationNs, int64_t conditionTrueNs = 0);
647 void ValidateGaugeBucketTimes(const GaugeBucketInfo& gaugeBucket, int64_t startTimeNs,
648                               int64_t endTimeNs, vector<int64_t> eventTimesNs);
649 void ValidateValueBucket(const ValueBucketInfo& bucket, int64_t startTimeNs, int64_t endTimeNs,
650                          const vector<int64_t>& values, int64_t conditionTrueNs,
651                          int64_t conditionCorrectionNs);
652 void ValidateKllBucket(const KllBucketInfo& bucket, int64_t startTimeNs, int64_t endTimeNs,
653                        const std::vector<int64_t> sketchSizes, int64_t conditionTrueNs);
654 
655 struct DimensionsPair {
DimensionsPairDimensionsPair656     DimensionsPair(DimensionsValue m1, google::protobuf::RepeatedPtrField<StateValue> m2)
657         : dimInWhat(m1), stateValues(m2){};
658 
659     DimensionsValue dimInWhat;
660     google::protobuf::RepeatedPtrField<StateValue> stateValues;
661 };
662 
663 bool LessThan(const StateValue& s1, const StateValue& s2);
664 bool LessThan(const DimensionsValue& s1, const DimensionsValue& s2);
665 bool LessThan(const DimensionsPair& s1, const DimensionsPair& s2);
666 
667 void backfillStartEndTimestamp(StatsLogReport* report);
668 void backfillStartEndTimestamp(ConfigMetricsReport *config_report);
669 void backfillStartEndTimestamp(ConfigMetricsReportList *config_report_list);
670 
671 void backfillStringInReport(ConfigMetricsReportList *config_report_list);
672 void backfillStringInDimension(const std::map<uint64_t, string>& str_map,
673                                DimensionsValue* dimension);
674 
675 void backfillAggregatedAtoms(ConfigMetricsReportList* config_report_list);
676 void backfillAggregatedAtoms(ConfigMetricsReport* config_report);
677 void backfillAggregatedAtoms(StatsLogReport* report);
678 void backfillAggregatedAtomsInEventMetric(StatsLogReport::EventMetricDataWrapper* wrapper);
679 void backfillAggregatedAtomsInGaugeMetric(StatsLogReport::GaugeMetricDataWrapper* wrapper);
680 
681 vector<pair<Atom, int64_t>> unnestGaugeAtomData(const GaugeBucketInfo& bucketInfo);
682 
683 template <typename T>
backfillStringInDimension(const std::map<uint64_t,string> & str_map,T * metrics)684 void backfillStringInDimension(const std::map<uint64_t, string>& str_map,
685                                T* metrics) {
686     for (int i = 0; i < metrics->data_size(); ++i) {
687         auto data = metrics->mutable_data(i);
688         if (data->has_dimensions_in_what()) {
689             backfillStringInDimension(str_map, data->mutable_dimensions_in_what());
690         }
691     }
692 }
693 
694 void backfillDimensionPath(StatsLogReport* report);
695 void backfillDimensionPath(ConfigMetricsReport* config_report);
696 void backfillDimensionPath(ConfigMetricsReportList* config_report_list);
697 
698 bool backfillDimensionPath(const DimensionsValue& path,
699                            const google::protobuf::RepeatedPtrField<DimensionsValue>& leafValues,
700                            DimensionsValue* dimension);
701 
702 void sortReportsByElapsedTime(ConfigMetricsReportList* configReportList);
703 
704 class FakeSubsystemSleepCallback : public BnPullAtomCallback {
705 public:
706     // Track the number of pulls.
707     int pullNum = 1;
708     Status onPullAtom(int atomTag,
709                       const shared_ptr<IPullAtomResultReceiver>& resultReceiver) override;
710 };
711 
712 template <typename T>
backfillDimensionPath(const DimensionsValue & whatPath,T * metricData)713 void backfillDimensionPath(const DimensionsValue& whatPath, T* metricData) {
714     for (int i = 0; i < metricData->data_size(); ++i) {
715         auto data = metricData->mutable_data(i);
716         if (data->dimension_leaf_values_in_what_size() > 0) {
717             backfillDimensionPath(whatPath, data->dimension_leaf_values_in_what(),
718                                   data->mutable_dimensions_in_what());
719             data->clear_dimension_leaf_values_in_what();
720         }
721     }
722 }
723 
724 struct DimensionCompare {
operatorDimensionCompare725     bool operator()(const DimensionsPair& s1, const DimensionsPair& s2) const {
726         return LessThan(s1, s2);
727     }
728 };
729 
730 template <typename T>
sortMetricDataByDimensionsValue(const T & metricData,T * sortedMetricData)731 void sortMetricDataByDimensionsValue(const T& metricData, T* sortedMetricData) {
732     std::map<DimensionsPair, int, DimensionCompare> dimensionIndexMap;
733     for (int i = 0; i < metricData.data_size(); ++i) {
734         dimensionIndexMap.insert(
735                 std::make_pair(DimensionsPair(metricData.data(i).dimensions_in_what(),
736                                               metricData.data(i).slice_by_state()),
737                                i));
738     }
739     for (const auto& itr : dimensionIndexMap) {
740         *sortedMetricData->add_data() = metricData.data(itr.second);
741     }
742 }
743 
744 template <typename T>
sortMetricDataByFirstDimensionLeafValue(const T & metricData,T * sortedMetricData)745 void sortMetricDataByFirstDimensionLeafValue(const T& metricData, T* sortedMetricData) {
746     std::map<DimensionsPair, int, DimensionCompare> dimensionIndexMap;
747     for (int i = 0; i < metricData.data_size(); ++i) {
748         dimensionIndexMap.insert(
749                 std::make_pair(DimensionsPair(metricData.data(i).dimension_leaf_values_in_what()[0],
750                                               metricData.data(i).slice_by_state()),
751                                i));
752     }
753     for (const auto& itr : dimensionIndexMap) {
754         *sortedMetricData->add_data() = metricData.data(itr.second);
755     }
756 }
757 
758 template <typename T>
backfillStartEndTimestampForFullBucket(const int64_t timeBaseNs,int64_t bucketSizeNs,T * bucket)759 void backfillStartEndTimestampForFullBucket(const int64_t timeBaseNs, int64_t bucketSizeNs,
760                                             T* bucket) {
761     bucket->set_start_bucket_elapsed_nanos(timeBaseNs + bucketSizeNs * bucket->bucket_num());
762     bucket->set_end_bucket_elapsed_nanos(
763         timeBaseNs + bucketSizeNs * bucket->bucket_num() + bucketSizeNs);
764     bucket->clear_bucket_num();
765 }
766 
767 template <typename T>
backfillStartEndTimestampForPartialBucket(const int64_t timeBaseNs,T * bucket)768 void backfillStartEndTimestampForPartialBucket(const int64_t timeBaseNs, T* bucket) {
769     if (bucket->has_start_bucket_elapsed_millis()) {
770         bucket->set_start_bucket_elapsed_nanos(
771             MillisToNano(bucket->start_bucket_elapsed_millis()));
772         bucket->clear_start_bucket_elapsed_millis();
773     }
774     if (bucket->has_end_bucket_elapsed_millis()) {
775         bucket->set_end_bucket_elapsed_nanos(
776             MillisToNano(bucket->end_bucket_elapsed_millis()));
777         bucket->clear_end_bucket_elapsed_millis();
778     }
779 }
780 
781 template <typename T>
backfillStartEndTimestampForMetrics(const int64_t timeBaseNs,int64_t bucketSizeNs,T * metrics)782 void backfillStartEndTimestampForMetrics(const int64_t timeBaseNs, int64_t bucketSizeNs,
783                                          T* metrics) {
784     for (int i = 0; i < metrics->data_size(); ++i) {
785         auto data = metrics->mutable_data(i);
786         for (int j = 0; j < data->bucket_info_size(); ++j) {
787             auto bucket = data->mutable_bucket_info(j);
788             if (bucket->has_bucket_num()) {
789                 backfillStartEndTimestampForFullBucket(timeBaseNs, bucketSizeNs, bucket);
790             } else {
791                 backfillStartEndTimestampForPartialBucket(timeBaseNs, bucket);
792             }
793         }
794     }
795 }
796 
797 template <typename T>
backfillStartEndTimestampForSkippedBuckets(const int64_t timeBaseNs,T * metrics)798 void backfillStartEndTimestampForSkippedBuckets(const int64_t timeBaseNs, T* metrics) {
799     for (int i = 0; i < metrics->skipped_size(); ++i) {
800         backfillStartEndTimestampForPartialBucket(timeBaseNs, metrics->mutable_skipped(i));
801     }
802 }
803 
804 template <typename P>
outputStreamToProto(ProtoOutputStream * outputStream,P * proto)805 void outputStreamToProto(ProtoOutputStream* outputStream, P* proto) {
806     vector<uint8_t> bytes;
807     outputStream->serializeToVector(&bytes);
808     proto->ParseFromArray(bytes.data(), bytes.size());
809 }
810 
isAtLeastSFuncTrue()811 inline bool isAtLeastSFuncTrue() {
812     return true;
813 }
814 
isAtLeastSFuncFalse()815 inline bool isAtLeastSFuncFalse() {
816     return false;
817 }
818 
isAtLeastT()819 inline bool isAtLeastT() {
820     const static bool isAtLeastT = android::modules::sdklevel::IsAtLeastT();
821     return isAtLeastT;
822 }
823 
getServerFlagFuncTrue(const std::string & flagNamespace,const std::string & flagName,const std::string & defaultValue)824 inline std::string getServerFlagFuncTrue(const std::string& flagNamespace,
825                                          const std::string& flagName,
826                                          const std::string& defaultValue) {
827     return FLAG_TRUE;
828 }
829 
getServerFlagFuncFalse(const std::string & flagNamespace,const std::string & flagName,const std::string & defaultValue)830 inline std::string getServerFlagFuncFalse(const std::string& flagNamespace,
831                                           const std::string& flagName,
832                                           const std::string& defaultValue) {
833     return FLAG_FALSE;
834 }
835 
836 void writeFlag(const std::string& flagName, const std::string& flagValue);
837 
838 void writeBootFlag(const std::string& flagName, const std::string& flagValue);
839 
840 PackageInfoSnapshot getPackageInfoSnapshot(const sp<UidMap> uidMap);
841 
842 ApplicationInfo createApplicationInfo(int32_t uid, int64_t version, const string& versionString,
843                                       const string& package);
844 
845 PackageInfo buildPackageInfo(const std::string& name, const int32_t uid, int64_t version,
846                              const std::string& versionString,
847                              const std::optional<std::string> installer,
848                              const std::vector<uint8_t>& certHash, const bool deleted,
849                              const bool hashStrings, const optional<uint32_t> installerIndex);
850 
851 std::vector<PackageInfo> buildPackageInfos(
852         const std::vector<string>& names, const std::vector<int32_t>& uids,
853         const std::vector<int64_t>& versions, const std::vector<std::string>& versionStrings,
854         const std::vector<std::string>& installers,
855         const std::vector<std::vector<uint8_t>>& certHashes, const std::vector<uint8_t>& deleted,
856         const std::vector<uint32_t>& installerIndices, const bool hashStrings);
857 
858 template <typename T>
concatenate(const vector<T> & a,const vector<T> & b)859 std::vector<T> concatenate(const vector<T>& a, const vector<T>& b) {
860     vector<T> result(a);
861     result.insert(result.end(), b.begin(), b.end());
862     return result;
863 }
864 
865 StatsdStatsReport getStatsdStatsReport(bool resetStats = false);
866 
867 StatsdStatsReport getStatsdStatsReport(StatsdStats& stats, bool resetStats = false);
868 
869 StatsdStatsReport_PulledAtomStats getPulledAtomStats(int atom_id);
870 
871 template <typename P>
protoToBytes(const P & proto)872 std::vector<uint8_t> protoToBytes(const P& proto) {
873     const size_t byteSize = proto.ByteSizeLong();
874     vector<uint8_t> bytes(byteSize);
875     proto.SerializeToArray(bytes.data(), byteSize);
876     return bytes;
877 }
878 
879 StatsdConfig buildGoodConfig(int configId);
880 
881 StatsdConfig buildGoodConfig(int configId, int alertId);
882 
883 class MockConfigMetadataProvider : public ConfigMetadataProvider {
884 public:
885     MOCK_METHOD(bool, useV2SoftMemoryCalculation, (), (override));
886 };
887 
888 sp<MockConfigMetadataProvider> makeMockConfigMetadataProvider(bool enabled);
889 
890 }  // namespace statsd
891 }  // namespace os
892 }  // namespace android
893