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