diff options
21 files changed, 156 insertions, 155 deletions
diff --git a/apex/Android.bp b/apex/Android.bp index 543627fd..0bad0aca 100644 --- a/apex/Android.bp +++ b/apex/Android.bp @@ -75,6 +75,7 @@ sdk { "com.android.os.statsd", ], native_shared_libs: [ + "libstatspull", "libstatssocket", ], } diff --git a/lib/libkll/Android.bp b/lib/libkll/Android.bp index c2a5542a..5f05fb7d 100644 --- a/lib/libkll/Android.bp +++ b/lib/libkll/Android.bp @@ -36,6 +36,7 @@ cc_library { "libkll-protos", ], shared_libs: [ + "liblog", "libprotobuf-cpp-lite", ], cflags: [ @@ -54,6 +55,7 @@ cc_library { cc_test { name: "libkll_test", + host_supported: true, tidy_timeout_srcs: [ "tests/sampler_test.cpp", ], @@ -67,6 +69,7 @@ cc_test { "libkll-protos", ], shared_libs: [ + "liblog", "libprotobuf-cpp-lite", ], test_suites: ["general-tests"], diff --git a/lib/libkll/compactor_stack.cpp b/lib/libkll/compactor_stack.cpp index 9ffb0440..0262d009 100644 --- a/lib/libkll/compactor_stack.cpp +++ b/lib/libkll/compactor_stack.cpp @@ -15,6 +15,10 @@ */ #include "compactor_stack.h" +#define LOG_TAG "libkll" + +#include <log/log.h> + #include <vector> #include "random_generator.h" @@ -114,6 +118,7 @@ void CompactorStack::AddLevel() { } void CompactorStack::CompactStack() { + int initial_num_items_in_compactors = num_items_in_compactors_; while (num_items_in_compactors_ >= overall_capacity_) { for (size_t i = 0; i < compactors_.size(); i++) { if (!compactors_[i].empty() && @@ -124,6 +129,20 @@ void CompactorStack::CompactStack() { } } } + // TODO(b/237694338): Remove the temporary infinite loop detection code + if (num_items_in_compactors_ >= initial_num_items_in_compactors) { + // The loop above didn't do anything in terms of reducing the number of items. + // To prevent an infinite loop, crash now. + ALOGI("num_items_in_compactors_=%d, compactors_.size()=%zu, overall_capacity_=%d", + num_items_in_compactors_, compactors_.size(), overall_capacity_); + for (size_t i = 0; i < compactors_.size(); i++) { + const std::vector<int64_t>& compactor = compactors_[i]; + ALOGI("compactors_[%zu].size()=%zu, TargetCapacityAtLevel(i)=%d", i, + compactor.size(), TargetCapacityAtLevel(i)); + } + LOG_ALWAYS_FATAL("Detected infinite loop in %s ", __func__); + } + initial_num_items_in_compactors = num_items_in_compactors_; } } diff --git a/lib/libstatspull/Android.bp b/lib/libstatspull/Android.bp index 0d6a7868..f8d2ff88 100644 --- a/lib/libstatspull/Android.bp +++ b/lib/libstatspull/Android.bp @@ -84,11 +84,6 @@ cc_library { min_sdk_version: "30", stl: "libc++_static", - - // TODO(b/151102177): Enable it when the build error is fixed. - header_abi_checker: { - enabled: false, - }, } cc_library_headers { @@ -145,6 +140,7 @@ cc_test { "-Wno-unused-variable", "-Wno-unused-function", "-Wno-unused-parameter", + "-Wno-deprecated-declarations", ], require_root: true, min_sdk_version: "30", diff --git a/statsd/Android.bp b/statsd/Android.bp index 17b67818..8b34c4e0 100644 --- a/statsd/Android.bp +++ b/statsd/Android.bp @@ -21,6 +21,10 @@ package { cc_defaults { name: "statsd_defaults", + cflags: [ + "-Wno-deprecated-declarations", + ], + srcs: [ "src/active_config_list.proto", "src/anomaly/AlarmMonitor.cpp", @@ -266,7 +270,6 @@ cc_test { "-Wno-unused-function", "-Wno-unused-parameter", "-Wno-unused-variable", - "-Wno-deprecated-declarations", ], require_root: true, @@ -430,7 +433,6 @@ cc_benchmark { "-Wno-unused-parameter", "-Wno-unused-variable", "-Wno-unused-function", - "-Wno-deprecated-declarations", // Bug: http://b/29823425 Disable -Wvarargs for Clang update to r271374 "-Wno-varargs", diff --git a/statsd/src/StatsService.cpp b/statsd/src/StatsService.cpp index eee9f51e..56229499 100644 --- a/statsd/src/StatsService.cpp +++ b/statsd/src/StatsService.cpp @@ -114,7 +114,7 @@ StatsService::StatsService(const sp<UidMap>& uidMap, shared_ptr<LogEventQueue> q StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged(); } })), - mEventQueue(queue), + mEventQueue(std::move(queue)), mBootCompleteTrigger({kBootCompleteTag, kUidMapReceivedTag, kAllPullersRegisteredTag}, [this]() { mProcessor->onStatsdInitCompleted(getElapsedRealtimeNs()); }), mStatsCompanionServiceDeathRecipient( diff --git a/statsd/src/flags/FlagProvider.h b/statsd/src/flags/FlagProvider.h index e948911f..7e11febe 100644 --- a/statsd/src/flags/FlagProvider.h +++ b/statsd/src/flags/FlagProvider.h @@ -37,8 +37,6 @@ using IsAtLeastSFunc = std::function<bool()>; const std::string STATSD_NATIVE_NAMESPACE = "statsd_native"; const std::string STATSD_NATIVE_BOOT_NAMESPACE = "statsd_native_boot"; -const std::string OPTIMIZATION_ATOM_MATCHER_MAP_FLAG = "optimization_atom_matcher_map"; - const std::string LIMIT_PULL_FLAG = "limit_pull"; const std::string FLAG_TRUE = "true"; @@ -129,7 +127,6 @@ private: FRIEND_TEST(FlagProviderTest_SPlus, TestGetFlagBoolServerFlagEmptyDefaultTrue); FRIEND_TEST(FlagProviderTest_SPlus_RealValues, TestGetBootFlagBoolServerFlagTrue); FRIEND_TEST(FlagProviderTest_SPlus_RealValues, TestGetBootFlagBoolServerFlagFalse); - FRIEND_TEST(MetricsManagerTest_SPlus, TestAtomMatcherOptimizationEnabledFlag); }; } // namespace statsd diff --git a/statsd/src/logd/LogEvent.cpp b/statsd/src/logd/LogEvent.cpp index 9a56a12f..f1129379 100644 --- a/statsd/src/logd/LogEvent.cpp +++ b/statsd/src/logd/LogEvent.cpp @@ -413,37 +413,61 @@ void LogEvent::parseAnnotations(uint8_t numAnnotations, std::optional<uint8_t> n } } -// This parsing logic is tied to the encoding scheme used in StatsEvent.java and -// stats_event.c -bool LogEvent::parseBuffer(uint8_t* buf, size_t len) { - mBuf = buf; - mRemainingLen = (uint32_t)len; - - int32_t pos[] = {1, 1, 1}; - bool last[] = {false, false, false}; - +uint8_t LogEvent::parseHeader() { // Beginning of buffer is OBJECT_TYPE | NUM_FIELDS | TIMESTAMP | ATOM_ID uint8_t typeInfo = readNextValue<uint8_t>(); - if (getTypeId(typeInfo) != OBJECT_TYPE) mValid = false; + if (getTypeId(typeInfo) != OBJECT_TYPE) { + mValid = false; + return 0; + } uint8_t numElements = readNextValue<uint8_t>(); - if (numElements < 2 || numElements > INT8_MAX) mValid = false; + if (numElements < 2 || numElements > INT8_MAX) { + mValid = false; + return 0; + } typeInfo = readNextValue<uint8_t>(); - if (getTypeId(typeInfo) != INT64_TYPE) mValid = false; + if (getTypeId(typeInfo) != INT64_TYPE) { + mValid = false; + return 0; + } mElapsedTimestampNs = readNextValue<int64_t>(); numElements--; typeInfo = readNextValue<uint8_t>(); - if (getTypeId(typeInfo) != INT32_TYPE) mValid = false; + if (getTypeId(typeInfo) != INT32_TYPE) { + mValid = false; + return 0; + } mTagId = readNextValue<int32_t>(); numElements--; + parseAnnotations(getNumAnnotations(typeInfo)); // atom-level annotations + return numElements; +} + +// This parsing logic is tied to the encoding scheme used in StatsEvent.java and +// stats_event.c +bool LogEvent::parseBuffer(const uint8_t* buf, size_t len, bool fetchHeaderOnly) { + mBuf = buf; + mRemainingLen = (uint32_t)len; + + const uint8_t numElements = parseHeader(); + + if (!mValid || fetchHeaderOnly) { + mBuf = nullptr; + return mValid; + } + + int32_t pos[] = {1, 1, 1}; + bool last[] = {false, false, false}; + for (pos[0] = 1; pos[0] <= numElements && mValid; pos[0]++) { last[0] = (pos[0] == numElements); - typeInfo = readNextValue<uint8_t>(); + uint8_t typeInfo = readNextValue<uint8_t>(); uint8_t typeId = getTypeId(typeInfo); switch (typeId) { diff --git a/statsd/src/logd/LogEvent.h b/statsd/src/logd/LogEvent.h index 88dd9b70..c59cc73e 100644 --- a/statsd/src/logd/LogEvent.h +++ b/statsd/src/logd/LogEvent.h @@ -88,10 +88,12 @@ public: * \param buf a buffer that begins at the start of the serialized atom (it * should not include the android_log_header_t or the StatsEventTag) * \param len size of the buffer + * \param fetchHeaderOnly force to parse only event header with atomId,timestamp + * and atom level annotations * * \return success of the initialization */ - bool parseBuffer(uint8_t* buf, size_t len); + bool parseBuffer(const uint8_t* buf, size_t len, bool fetchHeaderOnly = false); // Constructs a BinaryPushStateChanged LogEvent from API call. explicit LogEvent(const std::string& trainName, int64_t trainVersionCode, bool requiresStaging, @@ -235,6 +237,12 @@ public: LogEvent(const LogEvent&) = default; private: + /** + * @brief Parses atom header which consists of atom id, timestamp + * and atom level annotations + * @return amount of fields on the atom level + */ + uint8_t parseHeader(); void parseInt32(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations); void parseInt64(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations); void parseString(int32_t* pos, int32_t depth, bool* last, uint8_t numAnnotations); @@ -264,7 +272,7 @@ private: * parseBuffer. There are no guarantees about the state of these variables * before/after. */ - uint8_t* mBuf; + const uint8_t* mBuf; uint32_t mRemainingLen; // number of valid bytes left in the buffer being parsed bool mValid = true; // stores whether the event we received from the socket is valid diff --git a/statsd/src/main.cpp b/statsd/src/main.cpp index 02dbbe84..367ab733 100644 --- a/statsd/src/main.cpp +++ b/statsd/src/main.cpp @@ -76,8 +76,7 @@ int main(int /*argc*/, char** /*argv*/) { std::make_shared<LogEventQueue>(4000 /*buffer limit. Buffer is NOT pre-allocated*/); // Initialize boot flags - FlagProvider::getInstance().initBootFlags( - {OPTIMIZATION_ATOM_MATCHER_MAP_FLAG, LIMIT_PULL_FLAG}); + FlagProvider::getInstance().initBootFlags({LIMIT_PULL_FLAG}); sp<UidMap> uidMap = UidMap::getInstance(); diff --git a/statsd/src/metrics/MetricsManager.cpp b/statsd/src/metrics/MetricsManager.cpp index 156d7c21..361cb1a8 100644 --- a/statsd/src/metrics/MetricsManager.cpp +++ b/statsd/src/metrics/MetricsManager.cpp @@ -76,9 +76,7 @@ MetricsManager::MetricsManager(const ConfigKey& key, const StatsdConfig& config, mPullerManager(pullerManager), mWhitelistedAtomIds(config.whitelisted_atom_ids().begin(), config.whitelisted_atom_ids().end()), - mShouldPersistHistory(config.persist_locally()), - mAtomMatcherOptimizationEnabled(FlagProvider::getInstance().getBootFlagBool( - OPTIMIZATION_ATOM_MATCHER_MAP_FLAG, FLAG_FALSE)) { + mShouldPersistHistory(config.persist_locally()) { // Init the ttl end timestamp. refreshTtl(timeBaseNs); @@ -578,16 +576,9 @@ void MetricsManager::onLogEvent(const LogEvent& event) { vector<MatchingState> matcherCache(mAllAtomMatchingTrackers.size(), MatchingState::kNotComputed); - if (mAtomMatcherOptimizationEnabled) { - for (const auto& matcherIndex : matchersIt->second) { - mAllAtomMatchingTrackers[matcherIndex]->onLogEvent(event, mAllAtomMatchingTrackers, - matcherCache); - } - } else { - // Evaluate all atom matchers. - for (auto& matcher : mAllAtomMatchingTrackers) { - matcher->onLogEvent(event, mAllAtomMatchingTrackers, matcherCache); - } + for (const auto& matcherIndex : matchersIt->second) { + mAllAtomMatchingTrackers[matcherIndex]->onLogEvent(event, mAllAtomMatchingTrackers, + matcherCache); } // Set of metrics that received an activation cancellation. diff --git a/statsd/src/metrics/MetricsManager.h b/statsd/src/metrics/MetricsManager.h index 527efd9b..5b9731ed 100644 --- a/statsd/src/metrics/MetricsManager.h +++ b/statsd/src/metrics/MetricsManager.h @@ -217,8 +217,6 @@ private: bool mShouldPersistHistory; - const bool mAtomMatcherOptimizationEnabled; - // All event tags that are interesting to config metrics matchers. std::unordered_map<int, std::vector<int>> mTagIdsToMatchersMap; @@ -354,7 +352,6 @@ private: FRIEND_TEST(MetricsManagerTest, TestLogSources); FRIEND_TEST(MetricsManagerTest, TestLogSourcesOnConfigUpdate); - FRIEND_TEST(MetricsManagerTest_SPlus, TestAtomMatcherOptimizationEnabledFlag); FRIEND_TEST(MetricsManagerUtilTest, TestSampledMetrics); FRIEND_TEST(StatsLogProcessorTest, TestActiveConfigMetricDiskWriteRead); diff --git a/statsd/src/socket/StatsSocketListener.cpp b/statsd/src/socket/StatsSocketListener.cpp index 7b465735..3b3db1a0 100755..100644 --- a/statsd/src/socket/StatsSocketListener.cpp +++ b/statsd/src/socket/StatsSocketListener.cpp @@ -37,7 +37,7 @@ namespace os { namespace statsd { StatsSocketListener::StatsSocketListener(std::shared_ptr<LogEventQueue> queue) - : SocketListener(getLogSocket(), false /*start listen*/), mQueue(queue) { + : SocketListener(getLogSocket(), false /*start listen*/), mQueue(std::move(queue)) { } StatsSocketListener::~StatsSocketListener() { diff --git a/statsd/src/state/StateTracker.cpp b/statsd/src/state/StateTracker.cpp index ebba22a1..0feba421 100644 --- a/statsd/src/state/StateTracker.cpp +++ b/statsd/src/state/StateTracker.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#define STATSD_DEBUG true // STOPSHIP if true +#define STATSD_DEBUG false // STOPSHIP if true #include "Log.h" #include "stats_util.h" diff --git a/statsd/tests/LogEvent_test.cpp b/statsd/tests/LogEvent_test.cpp index d87b20bc..f0d090da 100644 --- a/statsd/tests/LogEvent_test.cpp +++ b/statsd/tests/LogEvent_test.cpp @@ -192,6 +192,31 @@ TEST(LogEventTest, TestPrimitiveParsing) { AStatsEvent_release(event); } +TEST(LogEventTest, TestFetchHeaderOnly) { + AStatsEvent* event = AStatsEvent_obtain(); + AStatsEvent_setAtomId(event, 100); + AStatsEvent_writeInt32(event, 10); + AStatsEvent_writeInt64(event, 0x123456789); + AStatsEvent_writeFloat(event, 2.0); + AStatsEvent_writeBool(event, true); + AStatsEvent_build(event); + + size_t size; + const uint8_t* buf = AStatsEvent_getBuffer(event, &size); + + LogEvent logEvent(/*uid=*/1000, /*pid=*/1001); + EXPECT_TRUE(logEvent.parseBuffer(buf, size, /*fetchHeaderOnly=*/true)); + + AStatsEvent_release(event); + + EXPECT_EQ(100, logEvent.GetTagId()); + EXPECT_EQ(1000, logEvent.GetUid()); + EXPECT_EQ(1001, logEvent.GetPid()); + EXPECT_FALSE(logEvent.hasAttributionChain()); + + ASSERT_EQ(logEvent.getValues().size(), 0); +} + TEST(LogEventTest, TestStringAndByteArrayParsing) { AStatsEvent* event = AStatsEvent_obtain(); AStatsEvent_setAtomId(event, 100); @@ -589,8 +614,7 @@ TEST(LogEventTest, TestEmptyArray) { EXPECT_EQ(1000, logEvent.GetUid()); EXPECT_EQ(1001, logEvent.GetPid()); - const vector<FieldValue>& values = logEvent.getValues(); - ASSERT_EQ(0, values.size()); + ASSERT_EQ(logEvent.getValues().size(), 0); AStatsEvent_release(event); } diff --git a/statsd/tests/MetricsManager_test.cpp b/statsd/tests/MetricsManager_test.cpp index 9650f2d6..73e3d3ce 100644 --- a/statsd/tests/MetricsManager_test.cpp +++ b/statsd/tests/MetricsManager_test.cpp @@ -265,73 +265,6 @@ TEST(MetricsManagerTest, TestLogSourcesOnConfigUpdate) { UnorderedElementsAreArray(unionSet({defaultPullUids, app2Uids, {AID_ADB}}))); } -struct MetricsManagerServerFlagParam { - string flagValue; - string label; -}; - -class MetricsManagerTest_SPlus - : public ::testing::Test, - public ::testing::WithParamInterface<MetricsManagerServerFlagParam> { -protected: - void SetUp() override { - if (shouldSkipTest()) { - GTEST_SKIP() << skipReason(); - } - - originalFlagValue = FlagProvider::getInstance().getFlagString( - OPTIMIZATION_ATOM_MATCHER_MAP_FLAG, FLAG_EMPTY); - } - - bool shouldSkipTest() const { - return !IsAtLeastS(); - } - - string skipReason() const { - return "Skipping MetricsManagerTest_SPlus because device is not S+"; - } - - void TearDown() override { - if (originalFlagValue) { - writeFlag(OPTIMIZATION_ATOM_MATCHER_MAP_FLAG, originalFlagValue.value()); - } - } - - std::optional<string> originalFlagValue; -}; - -INSTANTIATE_TEST_SUITE_P( - MetricsManagerTest_SPlus, MetricsManagerTest_SPlus, - testing::ValuesIn<MetricsManagerServerFlagParam>({ - // Server flag values - {FLAG_TRUE, "ServerFlagTrue"}, - {FLAG_FALSE, "ServerFlagFalse"}, - }), - [](const testing::TestParamInfo<MetricsManagerTest_SPlus::ParamType>& info) { - return info.param.label; - }); - -TEST_P(MetricsManagerTest_SPlus, TestAtomMatcherOptimizationEnabledFlag) { - FlagProvider::getInstance().overrideFlag(OPTIMIZATION_ATOM_MATCHER_MAP_FLAG, - GetParam().flagValue, - /*isBootFlag=*/true); - - sp<UidMap> uidMap; - sp<StatsPullerManager> pullerManager = new StatsPullerManager(); - sp<AlarmMonitor> anomalyAlarmMonitor; - sp<AlarmMonitor> periodicAlarmMonitor; - - StatsdConfig config = buildGoodConfig(); - MetricsManager metricsManager(kConfigKey, config, timeBaseSec, timeBaseSec, uidMap, - pullerManager, anomalyAlarmMonitor, periodicAlarmMonitor); - - if (GetParam().flagValue == FLAG_TRUE) { - EXPECT_TRUE(metricsManager.mAtomMatcherOptimizationEnabled); - } else { - EXPECT_FALSE(metricsManager.mAtomMatcherOptimizationEnabled); - } -} - TEST(MetricsManagerTest, TestCheckLogCredentialsWhitelistedAtom) { sp<UidMap> uidMap; sp<StatsPullerManager> pullerManager = new StatsPullerManager(); diff --git a/statsd/tests/StatsLogProcessor_test.cpp b/statsd/tests/StatsLogProcessor_test.cpp index 32f091f7..019584e3 100644 --- a/statsd/tests/StatsLogProcessor_test.cpp +++ b/statsd/tests/StatsLogProcessor_test.cpp @@ -66,22 +66,7 @@ public: MOCK_METHOD1(dropData, void(const int64_t dropTimeNs)); }; -// Setup for test fixture. -class StatsLogProcessorTest : public testing::TestWithParam<string> { - void SetUp() override { - FlagProvider::getInstance().overrideFlag(OPTIMIZATION_ATOM_MATCHER_MAP_FLAG, GetParam(), - /*isBootFlag=*/true); - } - - void TearDown() override { - FlagProvider::getInstance().resetOverrides(); - } -}; - -INSTANTIATE_TEST_SUITE_P(OptimizationAtomMatcher, StatsLogProcessorTest, - testing::Values(FLAG_FALSE, FLAG_TRUE)); - -TEST_P(StatsLogProcessorTest, TestRateLimitByteSize) { +TEST(StatsLogProcessorTest, TestRateLimitByteSize) { sp<UidMap> m = new UidMap(); sp<StatsPullerManager> pullerManager = new StatsPullerManager(); sp<AlarmMonitor> anomalyAlarmMonitor; @@ -102,7 +87,7 @@ TEST_P(StatsLogProcessorTest, TestRateLimitByteSize) { p.flushIfNecessaryLocked(key, mockMetricsManager); } -TEST_P(StatsLogProcessorTest, TestRateLimitBroadcast) { +TEST(StatsLogProcessorTest, TestRateLimitBroadcast) { sp<UidMap> m = new UidMap(); sp<StatsPullerManager> pullerManager = new StatsPullerManager(); sp<AlarmMonitor> anomalyAlarmMonitor; @@ -134,7 +119,7 @@ TEST_P(StatsLogProcessorTest, TestRateLimitBroadcast) { // EXPECT_EQ(1, broadcastCount); } -TEST_P(StatsLogProcessorTest, TestDropWhenByteSizeTooLarge) { +TEST(StatsLogProcessorTest, TestDropWhenByteSizeTooLarge) { sp<UidMap> m = new UidMap(); sp<StatsPullerManager> pullerManager = new StatsPullerManager(); sp<AlarmMonitor> anomalyAlarmMonitor; @@ -176,7 +161,7 @@ StatsdConfig MakeConfig(bool includeMetric) { return config; } -TEST_P(StatsLogProcessorTest, TestUidMapHasSnapshot) { +TEST(StatsLogProcessorTest, TestUidMapHasSnapshot) { // Setup simple config key corresponding to empty config. sp<UidMap> m = new UidMap(); sp<StatsPullerManager> pullerManager = new StatsPullerManager(); @@ -208,7 +193,7 @@ TEST_P(StatsLogProcessorTest, TestUidMapHasSnapshot) { ASSERT_EQ(2, uidmap.snapshots(0).package_info_size()); } -TEST_P(StatsLogProcessorTest, TestEmptyConfigHasNoUidMap) { +TEST(StatsLogProcessorTest, TestEmptyConfigHasNoUidMap) { // Setup simple config key corresponding to empty config. sp<UidMap> m = new UidMap(); sp<StatsPullerManager> pullerManager = new StatsPullerManager(); @@ -238,7 +223,7 @@ TEST_P(StatsLogProcessorTest, TestEmptyConfigHasNoUidMap) { EXPECT_FALSE(output.reports(0).has_uid_map()); } -TEST_P(StatsLogProcessorTest, TestReportIncludesSubConfig) { +TEST(StatsLogProcessorTest, TestReportIncludesSubConfig) { // Setup simple config key corresponding to empty config. sp<UidMap> m = new UidMap(); sp<StatsPullerManager> pullerManager = new StatsPullerManager(); @@ -272,7 +257,7 @@ TEST_P(StatsLogProcessorTest, TestReportIncludesSubConfig) { EXPECT_EQ(2, report.annotation(0).field_int32()); } -TEST_P(StatsLogProcessorTest, TestOnDumpReportEraseData) { +TEST(StatsLogProcessorTest, TestOnDumpReportEraseData) { // Setup a simple config. StatsdConfig config; config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root. @@ -320,7 +305,7 @@ TEST_P(StatsLogProcessorTest, TestOnDumpReportEraseData) { EXPECT_TRUE(noData); } -TEST_P(StatsLogProcessorTest, TestPullUidProviderSetOnConfigUpdate) { +TEST(StatsLogProcessorTest, TestPullUidProviderSetOnConfigUpdate) { // Setup simple config key corresponding to empty config. sp<UidMap> m = new UidMap(); sp<StatsPullerManager> pullerManager = new StatsPullerManager(); @@ -343,7 +328,7 @@ TEST_P(StatsLogProcessorTest, TestPullUidProviderSetOnConfigUpdate) { EXPECT_EQ(pullerManager->mPullUidProviders.find(key), pullerManager->mPullUidProviders.end()); } -TEST_P(StatsLogProcessorTest, InvalidConfigRemoved) { +TEST(StatsLogProcessorTest, InvalidConfigRemoved) { // Setup simple config key corresponding to empty config. sp<UidMap> m = new UidMap(); sp<StatsPullerManager> pullerManager = new StatsPullerManager(); @@ -381,7 +366,7 @@ TEST_P(StatsLogProcessorTest, InvalidConfigRemoved) { StorageManager::deleteSuffixedFiles(STATS_DATA_DIR, suffix.c_str()); } -TEST_P(StatsLogProcessorTest, TestActiveConfigMetricDiskWriteRead) { +TEST(StatsLogProcessorTest, TestActiveConfigMetricDiskWriteRead) { int uid = 1111; // Setup a simple config, no activation @@ -726,7 +711,7 @@ TEST_P(StatsLogProcessorTest, TestActiveConfigMetricDiskWriteRead) { EXPECT_EQ(broadcastCount, 1); } -TEST_P(StatsLogProcessorTest, TestActivationOnBoot) { +TEST(StatsLogProcessorTest, TestActivationOnBoot) { int uid = 1111; StatsdConfig config1; @@ -847,7 +832,7 @@ TEST_P(StatsLogProcessorTest, TestActivationOnBoot) { EXPECT_EQ(kActive, activation1001->state); } -TEST_P(StatsLogProcessorTest, TestActivationOnBootMultipleActivations) { +TEST(StatsLogProcessorTest, TestActivationOnBootMultipleActivations) { int uid = 1111; // Create config with 2 metrics: @@ -1248,7 +1233,7 @@ TEST_P(StatsLogProcessorTest, TestActivationOnBootMultipleActivations) { // }}}------------------------------------------------------------------------------- } -TEST_P(StatsLogProcessorTest, TestActivationOnBootMultipleActivationsDifferentActivationTypes) { +TEST(StatsLogProcessorTest, TestActivationOnBootMultipleActivationsDifferentActivationTypes) { int uid = 1111; // Create config with 2 metrics: @@ -1510,7 +1495,7 @@ TEST_P(StatsLogProcessorTest, TestActivationOnBootMultipleActivationsDifferentAc // }}}--------------------------------------------------------------------------- } -TEST_P(StatsLogProcessorTest, TestActivationsPersistAcrossSystemServerRestart) { +TEST(StatsLogProcessorTest, TestActivationsPersistAcrossSystemServerRestart) { int uid = 9876; long configId = 12341; @@ -1975,7 +1960,7 @@ TEST(StatsLogProcessorTest_mapIsolatedUidToHostUid, LogRepeatedUidField) { EXPECT_EQ(hostUid1, actualFieldValues->at(3).mValue.int_value); } -TEST_P(StatsLogProcessorTest, TestDumpReportWithoutErasingDataDoesNotUpdateTimestamp) { +TEST(StatsLogProcessorTest, TestDumpReportWithoutErasingDataDoesNotUpdateTimestamp) { int hostUid = 20; int isolatedUid = 30; sp<MockUidMap> mockUidMap = makeMockUidMapForHosts({{hostUid, {isolatedUid}}}); diff --git a/statsd/tools/localtools/src/com/android/statsd/shelltools/testdrive/TestDrive.java b/statsd/tools/localtools/src/com/android/statsd/shelltools/testdrive/TestDrive.java index dae2e9b4..2e2be666 100644 --- a/statsd/tools/localtools/src/com/android/statsd/shelltools/testdrive/TestDrive.java +++ b/statsd/tools/localtools/src/com/android/statsd/shelltools/testdrive/TestDrive.java @@ -144,8 +144,8 @@ public class TestDrive { LOGGER.severe("\tPath is absolute or relative to current dir or to ANDROID_BUILD_TOP"); LOGGER.severe("-terse"); LOGGER.severe("\tTerse output format."); - LOGGER.severe("-p additional_allowed_package"); - LOGGER.severe("\tAllows collection atoms from an additional package"); + LOGGER.severe("-p additional_allowed_packages_csv"); + LOGGER.severe("\tAllows collection atoms from an additional packages"); LOGGER.severe("-s DEVICE_SERIAL_NUMBER"); LOGGER.severe("\tDevice serial number to use for adb communication"); LOGGER.severe("-e"); @@ -178,7 +178,8 @@ public class TestDrive { LOGGER.info("Terse output format."); mDumper = new TerseDumper(); } else if (remaining_args >= 3 && arg.equals("-p")) { - configuration.mAdditionalAllowedPackage = args[++first_arg]; + Collections.addAll(configuration.mAdditionalAllowedPackages, + args[++first_arg].split(",")); } else if (remaining_args >= 3 && arg.equals("-i")) { mProtoIncludes.add(args[++first_arg]); } else if (remaining_args >= 3 && arg.equals("-s")) { @@ -278,7 +279,7 @@ public class TestDrive { @VisibleForTesting Set<Integer> mPulledAtoms = new TreeSet<>(); @VisibleForTesting - String mAdditionalAllowedPackage = null; + ArrayList<String> mAdditionalAllowedPackages = new ArrayList<>(); private final Set<Long> mTrackedMetrics = new HashSet<>(); private final String mAndroidBuildTop = System.getenv("ANDROID_BUILD_TOP"); @@ -564,9 +565,7 @@ public class TestDrive { private StatsdConfig.Builder baseBuilder() { ArrayList<String> allowedSources = new ArrayList<>(); Collections.addAll(allowedSources, ALLOWED_LOG_SOURCES); - if (mAdditionalAllowedPackage != null) { - allowedSources.add(mAdditionalAllowedPackage); - } + allowedSources.addAll(mAdditionalAllowedPackages); return StatsdConfig.newBuilder() .addAllAllowedLogSource(allowedSources) .addAllDefaultPullPackages(Arrays.asList(DEFAULT_PULL_SOURCES)) diff --git a/tests/src/android/cts/statsd/alert/AnomalyDetectionTests.java b/tests/src/android/cts/statsd/alert/AnomalyDetectionTests.java index f08a553e..ea47cc31 100644 --- a/tests/src/android/cts/statsd/alert/AnomalyDetectionTests.java +++ b/tests/src/android/cts/statsd/alert/AnomalyDetectionTests.java @@ -64,19 +64,34 @@ public class AnomalyDetectionTests extends AtomTestCase { private static final int ANOMALY_EVENT_ID = 101; private static final int INCIDENTD_SECTION = -1; + private boolean defaultSystemTracingConfigurationHasChanged = false; + @Override protected void setUp() throws Exception { super.setUp(); if (!INCIDENTD_TESTS_ENABLED) { CLog.w(TAG, TAG + " anomaly tests are disabled by a flag. Change flag to true to run"); } + if (PERFETTO_TESTS_ENABLED) { + // Default Android configuration can only change for device type that doesn't require SystemTracingEnabled + // by default in CDD. + String chars = getDevice().getProperty("ro.build.characteristics"); + if (!isSystemTracingEnabled() && chars.contains("automotive")) { + enableSystemTracing(); + defaultSystemTracingConfigurationHasChanged = true; + } + } } @Override protected void tearDown() throws Exception { super.tearDown(); if (PERFETTO_TESTS_ENABLED) { - //Deadline to finish trace collection + // Disable SystemTracing if previously enabled at test setUp() + if (defaultSystemTracingConfigurationHasChanged) { + disableSystemTracing(); + } + // Deadline to finish trace collection final long deadLine = System.currentTimeMillis() + 10000; while (isSystemTracingEnabled()) { if (System.currentTimeMillis() > deadLine) { diff --git a/tests/src/android/cts/statsd/atom/AtomTestCase.java b/tests/src/android/cts/statsd/atom/AtomTestCase.java index 83ca2a27..fc37543e 100644 --- a/tests/src/android/cts/statsd/atom/AtomTestCase.java +++ b/tests/src/android/cts/statsd/atom/AtomTestCase.java @@ -245,6 +245,14 @@ public class AtomTestCase extends BaseTestCase { + " cat " + path + " ; else echo -1 ; fi"); } + protected void enableSystemTracing() throws Exception { + getDevice().executeShellCommand("setprop persist.traced.enable 1"); + } + + protected void disableSystemTracing() throws Exception { + getDevice().executeShellCommand("setprop persist.traced.enable 0"); + } + /** * Determines whether perfetto enabled the kernel ftrace tracer. */ diff --git a/tests/src/android/cts/statsd/metric/MetricActivationTests.java b/tests/src/android/cts/statsd/metric/MetricActivationTests.java index 2273ae41..8e796cf9 100644 --- a/tests/src/android/cts/statsd/metric/MetricActivationTests.java +++ b/tests/src/android/cts/statsd/metric/MetricActivationTests.java @@ -494,12 +494,12 @@ public class MetricActivationTests extends DeviceAtomTestCase { // Metric 2 Activation 1: 0 seconds // Metric 2 Activation 2: 0 seconds rebootDeviceAndWaitUntilReady(); + Thread.sleep(3_000L); // Metric 1 event ignored. // Metric 2 event ignored. // Seventh logged event for Metric 3. logAllMetrics(); - Thread.sleep(500L); ConfigMetricsReportList reportList = getReportList(); List<ConfigMetricsReport> reports = getSortedConfigMetricsReports(reportList); |