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