• 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 #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                               const vector<int64_t>& states = {});
342 
343 CountMetric createCountMetric(const string& name, int64_t what, const optional<int64_t>& condition,
344                               const vector<int64_t>& states);
345 
346 DurationMetric createDurationMetric(const string& name, int64_t what,
347                                     const optional<int64_t>& condition,
348                                     const vector<int64_t>& states);
349 
350 GaugeMetric createGaugeMetric(const string& name, int64_t what,
351                               const GaugeMetric::SamplingType samplingType,
352                               const optional<int64_t>& condition,
353                               const optional<int64_t>& triggerEvent,
354                               const vector<int64_t>& states = {});
355 
356 ValueMetric createValueMetric(const string& name, const AtomMatcher& what, int valueField,
357                               const optional<int64_t>& condition, const vector<int64_t>& states);
358 
359 ValueMetric createValueMetric(const string& name, const AtomMatcher& what,
360                               const vector<int>& valueFields,
361                               const vector<ValueMetric::AggregationType>& aggregationTypes,
362                               const optional<int64_t>& condition, const vector<int64_t>& states);
363 
364 HistogramBinConfig createGeneratedBinConfig(int id, float min, float max, int count,
365                                             HistogramBinConfig::GeneratedBins::Strategy strategy);
366 
367 HistogramBinConfig createExplicitBinConfig(int id, const std::vector<float>& bins);
368 
369 KllMetric createKllMetric(const string& name, const AtomMatcher& what, int kllField,
370                           const optional<int64_t>& condition);
371 
372 Alert createAlert(const string& name, int64_t metricId, int buckets, const int64_t triggerSum);
373 
374 Alarm createAlarm(const string& name, int64_t offsetMillis, int64_t periodMillis);
375 
376 Subscription createSubscription(const string& name, const Subscription_RuleType type,
377                                 const int64_t ruleId);
378 
379 // START: get primary key functions
380 // These functions take in atom field information and create FieldValues which are stored in the
381 // given HashableDimensionKey.
382 void getUidProcessKey(int uid, HashableDimensionKey* key);
383 
384 void getOverlayKey(int uid, string packageName, HashableDimensionKey* key);
385 
386 void getPartialWakelockKey(int uid, const std::string& tag, HashableDimensionKey* key);
387 
388 void getPartialWakelockKey(int uid, HashableDimensionKey* key);
389 // END: get primary key functions
390 
391 void writeAttribution(AStatsEvent* statsEvent, const vector<int>& attributionUids,
392                       const vector<string>& attributionTags);
393 
394 // Builds statsEvent to get buffer that is parsed into logEvent then releases statsEvent.
395 bool parseStatsEventToLogEvent(AStatsEvent* statsEvent, LogEvent* logEvent);
396 
397 AStatsEvent* makeTwoValueStatsEvent(int atomId, int64_t eventTimeNs, int32_t value1,
398                                     int32_t value2);
399 
400 shared_ptr<LogEvent> CreateTwoValueLogEvent(int atomId, int64_t eventTimeNs, int32_t value1,
401                                             int32_t value2);
402 
403 void CreateTwoValueLogEvent(LogEvent* logEvent, int atomId, int64_t eventTimeNs, int32_t value1,
404                             int32_t value2);
405 
406 shared_ptr<LogEvent> CreateThreeValueLogEvent(int atomId, int64_t eventTimeNs, int32_t value1,
407                                               int32_t value2, int32_t value3);
408 
409 void CreateThreeValueLogEvent(LogEvent* logEvent, int atomId, int64_t eventTimeNs, int32_t value1,
410                               int32_t value2, int32_t value3);
411 
412 // The repeated value log event helpers create a log event with two int fields, both
413 // set to the same value. This is useful for testing metrics that are only interested
414 // in the value of the second field but still need the first field to be populated.
415 std::shared_ptr<LogEvent> CreateRepeatedValueLogEvent(int atomId, int64_t eventTimeNs,
416                                                       int32_t value);
417 
418 void CreateRepeatedValueLogEvent(LogEvent* logEvent, int atomId, int64_t eventTimeNs,
419                                  int32_t value);
420 
421 std::shared_ptr<LogEvent> CreateNoValuesLogEvent(int atomId, int64_t eventTimeNs);
422 
423 void CreateNoValuesLogEvent(LogEvent* logEvent, int atomId, int64_t eventTimeNs);
424 
425 AStatsEvent* makeAttributionStatsEvent(int atomId, int64_t eventTimeNs, const vector<int>& uids,
426                                        const vector<string>& tags, int data1, int data2);
427 
428 AStatsEvent* makeUidStatsEvent(int atomId, int64_t eventTimeNs, int uid, int data1, int data2);
429 
430 AStatsEvent* makeUidStatsEvent(int atomId, int64_t eventTimeNs, int uid, int data1,
431                                const vector<int>& data2) __INTRODUCED_IN(__ANDROID_API_T__);
432 
433 std::shared_ptr<LogEvent> makeUidLogEvent(int atomId, int64_t eventTimeNs, int uid, int data1,
434                                           int data2);
435 
436 std::shared_ptr<LogEvent> makeUidLogEvent(int atomId, int64_t eventTimeNs, int uid, int data1,
437                                           const vector<int>& data2)
438         __INTRODUCED_IN(__ANDROID_API_T__);
439 
440 shared_ptr<LogEvent> makeExtraUidsLogEvent(int atomId, int64_t eventTimeNs, int uid1, int data1,
441                                            int data2, const std::vector<int>& extraUids);
442 
443 std::shared_ptr<LogEvent> makeRepeatedUidLogEvent(int atomId, int64_t eventTimeNs,
444                                                   const std::vector<int>& uids)
445         __INTRODUCED_IN(__ANDROID_API_T__);
446 
447 shared_ptr<LogEvent> makeRepeatedUidLogEvent(int atomId, int64_t eventTimeNs,
448                                              const vector<int>& uids, int data1, int data2)
449         __INTRODUCED_IN(__ANDROID_API_T__);
450 
451 shared_ptr<LogEvent> makeRepeatedUidLogEvent(int atomId, int64_t eventTimeNs,
452                                              const vector<int>& uids, int data1,
453                                              const vector<int>& data2)
454         __INTRODUCED_IN(__ANDROID_API_T__);
455 
456 std::shared_ptr<LogEvent> makeAttributionLogEvent(int atomId, int64_t eventTimeNs,
457                                                   const vector<int>& uids,
458                                                   const vector<string>& tags, int data1, int data2);
459 
460 sp<MockUidMap> makeMockUidMapForHosts(const map<int, vector<int>>& hostUidToIsolatedUidsMap);
461 
462 sp<MockUidMap> makeMockUidMapForPackage(const string& pkg, const set<int32_t>& uids);
463 
464 // Create log event for screen state changed.
465 std::unique_ptr<LogEvent> CreateScreenStateChangedEvent(uint64_t timestampNs,
466                                                         const android::view::DisplayStateEnum state,
467                                                         int loggerUid = 0);
468 
469 // Create log event for screen brightness state changed.
470 std::unique_ptr<LogEvent> CreateScreenBrightnessChangedEvent(uint64_t timestampNs, int level);
471 
472 // Create log event when scheduled job starts.
473 std::unique_ptr<LogEvent> CreateStartScheduledJobEvent(uint64_t timestampNs,
474                                                        const vector<int>& attributionUids,
475                                                        const vector<string>& attributionTags,
476                                                        const string& jobName);
477 
478 // Create log event when scheduled job finishes.
479 std::unique_ptr<LogEvent> CreateFinishScheduledJobEvent(uint64_t timestampNs,
480                                                         const vector<int>& attributionUids,
481                                                         const vector<string>& attributionTags,
482                                                         const string& jobName);
483 
484 // Create log event when scheduled job schedules.
485 std::unique_ptr<LogEvent> CreateScheduleScheduledJobEvent(uint64_t timestampNs,
486                                                           const vector<int>& attributionUids,
487                                                           const vector<string>& attributionTags,
488                                                           const string& jobName);
489 
490 // Create log event when battery saver starts.
491 std::unique_ptr<LogEvent> CreateBatterySaverOnEvent(uint64_t timestampNs);
492 // Create log event when battery saver stops.
493 std::unique_ptr<LogEvent> CreateBatterySaverOffEvent(uint64_t timestampNs);
494 
495 // Create log event when battery state changes.
496 std::unique_ptr<LogEvent> CreateBatteryStateChangedEvent(const uint64_t timestampNs,
497                                                          const BatteryPluggedStateEnum state,
498                                                          int32_t uid = AID_ROOT);
499 
500 // Create malformed log event for battery state change.
501 std::unique_ptr<LogEvent> CreateMalformedBatteryStateChangedEvent(const uint64_t timestampNs);
502 
503 std::unique_ptr<LogEvent> CreateActivityForegroundStateChangedEvent(
504         uint64_t timestampNs, const int uid, const string& pkgName, const string& className,
505         const ActivityForegroundStateChanged::State state);
506 
507 // Create log event for app moving to background.
508 std::unique_ptr<LogEvent> CreateMoveToBackgroundEvent(uint64_t timestampNs, int uid);
509 
510 // Create log event for app moving to foreground.
511 std::unique_ptr<LogEvent> CreateMoveToForegroundEvent(uint64_t timestampNs, int uid);
512 
513 // Create log event when the app sync starts.
514 std::unique_ptr<LogEvent> CreateSyncStartEvent(uint64_t timestampNs, const vector<int>& uids,
515                                                const vector<string>& tags, const string& name);
516 
517 // Create log event when the app sync ends.
518 std::unique_ptr<LogEvent> CreateSyncEndEvent(uint64_t timestampNs, const vector<int>& uids,
519                                              const vector<string>& tags, const string& name);
520 
521 // Create log event when the app sync ends.
522 std::unique_ptr<LogEvent> CreateAppCrashEvent(uint64_t timestampNs, int uid);
523 
524 // Create log event for an app crash.
525 std::unique_ptr<LogEvent> CreateAppCrashOccurredEvent(uint64_t timestampNs, int uid);
526 
527 // Create log event for acquiring wakelock.
528 std::unique_ptr<LogEvent> CreateAcquireWakelockEvent(uint64_t timestampNs, const vector<int>& uids,
529                                                      const vector<string>& tags,
530                                                      const string& wakelockName);
531 
532 // Create log event for releasing wakelock.
533 std::unique_ptr<LogEvent> CreateReleaseWakelockEvent(uint64_t timestampNs, const vector<int>& uids,
534                                                      const vector<string>& tags,
535                                                      const string& wakelockName);
536 
537 // Create log event for releasing wakelock.
538 std::unique_ptr<LogEvent> CreateIsolatedUidChangedEvent(uint64_t timestampNs, int hostUid,
539                                                         int isolatedUid, bool is_create);
540 
541 // Create log event for uid process state change.
542 std::unique_ptr<LogEvent> CreateUidProcessStateChangedEvent(
543         uint64_t timestampNs, int uid, const android::app::ProcessStateEnum state);
544 
545 std::unique_ptr<LogEvent> CreateBleScanStateChangedEvent(uint64_t timestampNs,
546                                                          const vector<int>& attributionUids,
547                                                          const vector<string>& attributionTags,
548                                                          const BleScanStateChanged::State state,
549                                                          const bool filtered, const bool firstMatch,
550                                                          const bool opportunistic);
551 
552 std::unique_ptr<LogEvent> CreateOverlayStateChangedEvent(int64_t timestampNs, const int32_t uid,
553                                                          const string& packageName,
554                                                          const bool usingAlertWindow,
555                                                          const OverlayStateChanged::State state);
556 
557 std::unique_ptr<LogEvent> CreateAppStartOccurredEvent(
558         uint64_t timestampNs, int uid, const string& pkg_name,
559         AppStartOccurred::TransitionType type, const string& activity_name,
560         const string& calling_pkg_name, const bool is_instant_app, int64_t activity_start_msec);
561 
562 std::unique_ptr<LogEvent> CreateBleScanResultReceivedEvent(uint64_t timestampNs,
563                                                            const vector<int>& attributionUids,
564                                                            const vector<string>& attributionTags,
565                                                            const int numResults);
566 
567 std::unique_ptr<LogEvent> CreateTestAtomReportedEventVariableRepeatedFields(
568         uint64_t timestampNs, const vector<int>& repeatedIntField,
569         const vector<int64_t>& repeatedLongField, const vector<float>& repeatedFloatField,
570         const vector<string>& repeatedStringField, const bool* repeatedBoolField,
571         const size_t repeatedBoolFieldLength, const vector<int>& repeatedEnumField);
572 
573 std::unique_ptr<LogEvent> CreateTestAtomReportedEventWithPrimitives(
574         uint64_t timestampNs, int intField, long longField, float floatField,
575         const string& stringField, bool boolField, TestAtomReported::State enumField);
576 
577 std::unique_ptr<LogEvent> CreateRestrictedLogEvent(int atomTag, int64_t timestampNs = 0);
578 std::unique_ptr<LogEvent> CreateNonRestrictedLogEvent(int atomTag, int64_t timestampNs = 0);
579 
580 std::unique_ptr<LogEvent> CreatePhoneSignalStrengthChangedEvent(
581         int64_t timestampNs, ::telephony::SignalStrengthEnum state);
582 
583 std::unique_ptr<LogEvent> CreateTestAtomReportedEvent(
584         uint64_t timestampNs, const vector<int>& attributionUids,
585         const vector<string>& attributionTags, int intField, const long longField,
586         const float floatField, const string& stringField, const bool boolField,
587         const TestAtomReported::State enumField, const vector<uint8_t>& bytesField,
588         const vector<int>& repeatedIntField, const vector<int64_t>& repeatedLongField,
589         const vector<float>& repeatedFloatField, const vector<string>& repeatedStringField,
590         const bool* repeatedBoolField, const size_t repeatedBoolFieldLength,
591         const vector<int>& repeatedEnumField);
592 
593 void createStatsEvent(AStatsEvent* statsEvent, uint8_t typeId, uint32_t atomId);
594 
595 void fillStatsEventWithSampleValue(AStatsEvent* statsEvent, uint8_t typeId);
596 
597 SocketLossInfo createSocketLossInfo(int32_t uid, int32_t atomId);
598 
599 // helper API to create STATS_SOCKET_LOSS_REPORTED LogEvent
600 std::unique_ptr<LogEvent> createSocketLossInfoLogEvent(int32_t uid, int32_t lossAtomId)
601         __INTRODUCED_IN(__ANDROID_API_T__);
602 
603 // Create a statsd log event processor upon the start time in seconds, config and key.
604 sp<StatsLogProcessor> CreateStatsLogProcessor(
605         const int64_t timeBaseNs, int64_t currentTimeNs, const StatsdConfig& config,
606         const ConfigKey& key, const shared_ptr<IPullAtomCallback>& puller = nullptr,
607         const int32_t atomTag = 0 /*for puller only*/, const sp<UidMap> = new UidMap(),
608         const shared_ptr<LogEventFilter>& logEventFilter = std::make_shared<LogEventFilter>());
609 
610 sp<NumericValueMetricProducer> createNumericValueMetricProducer(
611         sp<MockStatsPullerManager>& pullerManager, const ValueMetric& metric, const int atomId,
612         bool isPulled, const ConfigKey& configKey, const uint64_t protoHash,
613         const int64_t timeBaseNs, const int64_t startTimeNs, const int logEventMatcherIndex,
614         optional<ConditionState> conditionAfterFirstBucketPrepared = nullopt,
615         vector<int32_t> slicedStateAtoms = {},
616         unordered_map<int, unordered_map<int, int64_t>> stateGroupMap = {},
617         sp<EventMatcherWizard> eventMatcherWizard = nullptr);
618 
619 LogEventFilter::AtomIdSet CreateAtomIdSetDefault();
620 LogEventFilter::AtomIdSet CreateAtomIdSetFromConfig(const StatsdConfig& config);
621 
622 // Util function to sort the log events by timestamp.
623 void sortLogEventsByTimestamp(std::vector<std::unique_ptr<LogEvent>> *events);
624 
625 int64_t StringToId(const string& str);
626 
627 sp<EventMatcherWizard> createEventMatcherWizard(
628         int tagId, int matcherIndex, const std::vector<FieldValueMatcher>& fieldValueMatchers = {});
629 
630 StatsDimensionsValueParcel CreateAttributionUidDimensionsValueParcel(const int atomId,
631                                                                      const int uid);
632 
633 void ValidateUidDimension(const DimensionsValue& value, int atomId, int uid);
634 void ValidateWakelockAttributionUidAndTagDimension(const DimensionsValue& value, int atomId,
635                                                    const int uid, const string& tag);
636 void ValidateUidDimension(const DimensionsValue& value, int node_idx, int atomId, int uid);
637 void ValidateAttributionUidDimension(const DimensionsValue& value, int atomId, int uid);
638 void ValidateAttributionUidAndTagDimension(
639     const DimensionsValue& value, int atomId, int uid, const std::string& tag);
640 void ValidateAttributionUidAndTagDimension(
641     const DimensionsValue& value, int node_idx, int atomId, int uid, const std::string& tag);
642 void ValidateStateValue(const google::protobuf::RepeatedPtrField<StateValue>& stateValues,
643                         int atomId, int64_t value);
644 
645 void ValidateCountBucket(const CountBucketInfo& countBucket, int64_t startTimeNs, int64_t endTimeNs,
646                          int64_t count, int64_t conditionTrueNs = 0);
647 void ValidateDurationBucket(const DurationBucketInfo& bucket, int64_t startTimeNs,
648                             int64_t endTimeNs, int64_t durationNs, int64_t conditionTrueNs = 0);
649 void ValidateGaugeBucketTimes(const GaugeBucketInfo& gaugeBucket, int64_t startTimeNs,
650                               int64_t endTimeNs, vector<int64_t> eventTimesNs);
651 void ValidateValueBucket(const ValueBucketInfo& bucket, int64_t startTimeNs, int64_t endTimeNs,
652                          const vector<int64_t>& values, int64_t conditionTrueNs,
653                          int64_t conditionCorrectionNs);
654 void ValidateKllBucket(const KllBucketInfo& bucket, int64_t startTimeNs, int64_t endTimeNs,
655                        const std::vector<int64_t> sketchSizes, int64_t conditionTrueNs);
656 
657 struct DimensionsPair {
DimensionsPairDimensionsPair658     DimensionsPair(DimensionsValue m1, google::protobuf::RepeatedPtrField<StateValue> m2)
659         : dimInWhat(m1), stateValues(m2){};
660 
661     DimensionsValue dimInWhat;
662     google::protobuf::RepeatedPtrField<StateValue> stateValues;
663 };
664 
665 bool LessThan(const StateValue& s1, const StateValue& s2);
666 bool LessThan(const DimensionsValue& s1, const DimensionsValue& s2);
667 bool LessThan(const DimensionsPair& s1, const DimensionsPair& s2);
668 
669 void backfillStartEndTimestamp(StatsLogReport* report);
670 void backfillStartEndTimestamp(ConfigMetricsReport *config_report);
671 void backfillStartEndTimestamp(ConfigMetricsReportList *config_report_list);
672 
673 void backfillStringInReport(ConfigMetricsReportList *config_report_list);
674 void backfillStringInDimension(const std::map<uint64_t, string>& str_map,
675                                DimensionsValue* dimension);
676 
677 void backfillAggregatedAtoms(ConfigMetricsReportList* config_report_list);
678 void backfillAggregatedAtoms(ConfigMetricsReport* config_report);
679 void backfillAggregatedAtoms(StatsLogReport* report);
680 void backfillAggregatedAtomsInEventMetric(StatsLogReport::EventMetricDataWrapper* wrapper);
681 void backfillAggregatedAtomsInGaugeMetric(StatsLogReport::GaugeMetricDataWrapper* wrapper);
682 
683 vector<pair<Atom, int64_t>> unnestGaugeAtomData(const GaugeBucketInfo& bucketInfo);
684 
685 template <typename T>
backfillStringInDimension(const std::map<uint64_t,string> & str_map,T * metrics)686 void backfillStringInDimension(const std::map<uint64_t, string>& str_map,
687                                T* metrics) {
688     for (int i = 0; i < metrics->data_size(); ++i) {
689         auto data = metrics->mutable_data(i);
690         if (data->has_dimensions_in_what()) {
691             backfillStringInDimension(str_map, data->mutable_dimensions_in_what());
692         }
693     }
694 }
695 
696 void backfillDimensionPath(StatsLogReport* report);
697 void backfillDimensionPath(ConfigMetricsReport* config_report);
698 void backfillDimensionPath(ConfigMetricsReportList* config_report_list);
699 
700 bool backfillDimensionPath(const DimensionsValue& path,
701                            const google::protobuf::RepeatedPtrField<DimensionsValue>& leafValues,
702                            DimensionsValue* dimension);
703 
704 void sortReportsByElapsedTime(ConfigMetricsReportList* configReportList);
705 
706 class FakeSubsystemSleepCallback : public BnPullAtomCallback {
707 public:
708     // Track the number of pulls.
709     int pullNum = 1;
710     Status onPullAtom(int atomTag,
711                       const shared_ptr<IPullAtomResultReceiver>& resultReceiver) override;
712 };
713 
714 class FakeCpuTimeCallback : public BnPullAtomCallback {
715 public:
716     // Track the number of pulls.
717     int pullNum = 1;
718     Status onPullAtom(int atomTag,
719                       const shared_ptr<IPullAtomResultReceiver>& resultReceiver) override;
720 };
721 
722 template <typename T>
backfillDimensionPath(const DimensionsValue & whatPath,T * metricData)723 void backfillDimensionPath(const DimensionsValue& whatPath, T* metricData) {
724     for (int i = 0; i < metricData->data_size(); ++i) {
725         auto data = metricData->mutable_data(i);
726         if (data->dimension_leaf_values_in_what_size() > 0) {
727             backfillDimensionPath(whatPath, data->dimension_leaf_values_in_what(),
728                                   data->mutable_dimensions_in_what());
729             data->clear_dimension_leaf_values_in_what();
730         }
731     }
732 }
733 
734 struct DimensionCompare {
operatorDimensionCompare735     bool operator()(const DimensionsPair& s1, const DimensionsPair& s2) const {
736         return LessThan(s1, s2);
737     }
738 };
739 
740 template <typename T>
sortMetricDataByDimensionsValue(const T & metricData,T * sortedMetricData)741 void sortMetricDataByDimensionsValue(const T& metricData, T* sortedMetricData) {
742     std::map<DimensionsPair, int, DimensionCompare> dimensionIndexMap;
743     for (int i = 0; i < metricData.data_size(); ++i) {
744         dimensionIndexMap.insert(
745                 std::make_pair(DimensionsPair(metricData.data(i).dimensions_in_what(),
746                                               metricData.data(i).slice_by_state()),
747                                i));
748     }
749     for (const auto& itr : dimensionIndexMap) {
750         *sortedMetricData->add_data() = metricData.data(itr.second);
751     }
752 }
753 
754 template <typename T>
sortMetricDataByFirstDimensionLeafValue(const T & metricData,T * sortedMetricData)755 void sortMetricDataByFirstDimensionLeafValue(const T& metricData, T* sortedMetricData) {
756     std::map<DimensionsPair, int, DimensionCompare> dimensionIndexMap;
757     for (int i = 0; i < metricData.data_size(); ++i) {
758         dimensionIndexMap.insert(
759                 std::make_pair(DimensionsPair(metricData.data(i).dimension_leaf_values_in_what()[0],
760                                               metricData.data(i).slice_by_state()),
761                                i));
762     }
763     for (const auto& itr : dimensionIndexMap) {
764         *sortedMetricData->add_data() = metricData.data(itr.second);
765     }
766 }
767 
768 template <typename T>
backfillStartEndTimestampForFullBucket(const int64_t timeBaseNs,int64_t bucketSizeNs,T * bucket)769 void backfillStartEndTimestampForFullBucket(const int64_t timeBaseNs, int64_t bucketSizeNs,
770                                             T* bucket) {
771     bucket->set_start_bucket_elapsed_nanos(timeBaseNs + bucketSizeNs * bucket->bucket_num());
772     bucket->set_end_bucket_elapsed_nanos(
773         timeBaseNs + bucketSizeNs * bucket->bucket_num() + bucketSizeNs);
774     bucket->clear_bucket_num();
775 }
776 
777 template <typename T>
backfillStartEndTimestampForPartialBucket(const int64_t timeBaseNs,T * bucket)778 void backfillStartEndTimestampForPartialBucket(const int64_t timeBaseNs, T* bucket) {
779     if (bucket->has_start_bucket_elapsed_millis()) {
780         bucket->set_start_bucket_elapsed_nanos(
781             MillisToNano(bucket->start_bucket_elapsed_millis()));
782         bucket->clear_start_bucket_elapsed_millis();
783     }
784     if (bucket->has_end_bucket_elapsed_millis()) {
785         bucket->set_end_bucket_elapsed_nanos(
786             MillisToNano(bucket->end_bucket_elapsed_millis()));
787         bucket->clear_end_bucket_elapsed_millis();
788     }
789 }
790 
791 template <typename T>
backfillStartEndTimestampForMetrics(const int64_t timeBaseNs,int64_t bucketSizeNs,T * metrics)792 void backfillStartEndTimestampForMetrics(const int64_t timeBaseNs, int64_t bucketSizeNs,
793                                          T* metrics) {
794     for (int i = 0; i < metrics->data_size(); ++i) {
795         auto data = metrics->mutable_data(i);
796         for (int j = 0; j < data->bucket_info_size(); ++j) {
797             auto bucket = data->mutable_bucket_info(j);
798             if (bucket->has_bucket_num()) {
799                 backfillStartEndTimestampForFullBucket(timeBaseNs, bucketSizeNs, bucket);
800             } else {
801                 backfillStartEndTimestampForPartialBucket(timeBaseNs, bucket);
802             }
803         }
804     }
805 }
806 
807 template <typename T>
backfillStartEndTimestampForSkippedBuckets(const int64_t timeBaseNs,T * metrics)808 void backfillStartEndTimestampForSkippedBuckets(const int64_t timeBaseNs, T* metrics) {
809     for (int i = 0; i < metrics->skipped_size(); ++i) {
810         backfillStartEndTimestampForPartialBucket(timeBaseNs, metrics->mutable_skipped(i));
811     }
812 }
813 
814 template <typename P>
outputStreamToProto(ProtoOutputStream * outputStream,P * proto)815 void outputStreamToProto(ProtoOutputStream* outputStream, P* proto) {
816     vector<uint8_t> bytes;
817     outputStream->serializeToVector(&bytes);
818     proto->ParseFromArray(bytes.data(), bytes.size());
819 }
820 
isAtLeastSFuncTrue()821 inline bool isAtLeastSFuncTrue() {
822     return true;
823 }
824 
isAtLeastSFuncFalse()825 inline bool isAtLeastSFuncFalse() {
826     return false;
827 }
828 
isAtLeastT()829 inline bool isAtLeastT() {
830     const static bool isAtLeastT = android::modules::sdklevel::IsAtLeastT();
831     return isAtLeastT;
832 }
833 
getServerFlagFuncTrue(const std::string & flagNamespace,const std::string & flagName,const std::string & defaultValue)834 inline std::string getServerFlagFuncTrue(const std::string& flagNamespace,
835                                          const std::string& flagName,
836                                          const std::string& defaultValue) {
837     return FLAG_TRUE;
838 }
839 
getServerFlagFuncFalse(const std::string & flagNamespace,const std::string & flagName,const std::string & defaultValue)840 inline std::string getServerFlagFuncFalse(const std::string& flagNamespace,
841                                           const std::string& flagName,
842                                           const std::string& defaultValue) {
843     return FLAG_FALSE;
844 }
845 
846 void writeFlag(const std::string& flagName, const std::string& flagValue);
847 
848 void writeBootFlag(const std::string& flagName, const std::string& flagValue);
849 
850 PackageInfoSnapshot getPackageInfoSnapshot(const sp<UidMap> uidMap);
851 
852 ApplicationInfo createApplicationInfo(int32_t uid, int64_t version, const string& versionString,
853                                       const string& package);
854 
855 PackageInfo buildPackageInfo(const std::string& name, const int32_t uid, int64_t version,
856                              const std::string& versionString,
857                              const std::optional<std::string> installer,
858                              const std::vector<uint8_t>& certHash, const bool deleted,
859                              const bool hashStrings, const optional<uint32_t> installerIndex);
860 
861 std::vector<PackageInfo> buildPackageInfos(
862         const std::vector<string>& names, const std::vector<int32_t>& uids,
863         const std::vector<int64_t>& versions, const std::vector<std::string>& versionStrings,
864         const std::vector<std::string>& installers,
865         const std::vector<std::vector<uint8_t>>& certHashes, const std::vector<uint8_t>& deleted,
866         const std::vector<uint32_t>& installerIndices, const bool hashStrings);
867 
868 template <typename T>
concatenate(const vector<T> & a,const vector<T> & b)869 std::vector<T> concatenate(const vector<T>& a, const vector<T>& b) {
870     vector<T> result(a);
871     result.insert(result.end(), b.begin(), b.end());
872     return result;
873 }
874 
875 StatsdStatsReport getStatsdStatsReport(bool resetStats = false);
876 
877 StatsdStatsReport getStatsdStatsReport(StatsdStats& stats, bool resetStats = false);
878 
879 StatsdStatsReport_PulledAtomStats getPulledAtomStats(int atom_id);
880 
881 template <typename P>
protoToBytes(const P & proto)882 std::vector<uint8_t> protoToBytes(const P& proto) {
883     const size_t byteSize = proto.ByteSizeLong();
884     vector<uint8_t> bytes(byteSize);
885     proto.SerializeToArray(bytes.data(), byteSize);
886     return bytes;
887 }
888 
889 StatsdConfig buildGoodConfig(int configId);
890 
891 StatsdConfig buildGoodConfig(int configId, int alertId);
892 
893 class MockConfigMetadataProvider : public ConfigMetadataProvider {
894 public:
895     MOCK_METHOD(bool, useV2SoftMemoryCalculation, (), (override));
896 };
897 
898 sp<MockConfigMetadataProvider> makeMockConfigMetadataProvider(bool enabled);
899 
900 }  // namespace statsd
901 }  // namespace os
902 }  // namespace android
903