summaryrefslogtreecommitdiff
path: root/cmds
diff options
context:
space:
mode:
Diffstat (limited to 'cmds')
-rw-r--r--cmds/bmgr/TEST_MAPPING11
-rw-r--r--cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java103
-rw-r--r--cmds/bootanimation/BootAnimation.cpp42
-rw-r--r--cmds/idmap2/idmap2/Scan.cpp3
-rw-r--r--cmds/idmap2/idmap2d/Idmap2Service.h9
-rw-r--r--cmds/idmap2/include/idmap2/BinaryStreamVisitor.h11
-rw-r--r--cmds/idmap2/include/idmap2/PrettyPrintVisitor.h11
-rw-r--r--cmds/idmap2/include/idmap2/RawPrintVisitor.h11
-rw-r--r--cmds/idmap2/tests/TestHelpers.h4
-rw-r--r--cmds/incident/main.cpp58
-rw-r--r--cmds/incidentd/src/IncidentService.cpp79
-rw-r--r--cmds/incidentd/src/IncidentService.h4
-rw-r--r--cmds/incidentd/src/main.cpp3
-rw-r--r--cmds/locksettings/TEST_MAPPING15
-rw-r--r--cmds/statsd/Android.bp28
-rw-r--r--cmds/statsd/OWNERS1
-rw-r--r--cmds/statsd/src/FieldValue.cpp14
-rw-r--r--cmds/statsd/src/FieldValue.h1
-rw-r--r--cmds/statsd/src/anomaly/AnomalyTracker.cpp3
-rw-r--r--cmds/statsd/src/atoms.proto377
-rw-r--r--cmds/statsd/src/condition/CombinationConditionTracker.cpp29
-rw-r--r--cmds/statsd/src/condition/CombinationConditionTracker.h11
-rw-r--r--cmds/statsd/src/condition/ConditionTracker.h17
-rw-r--r--cmds/statsd/src/condition/ConditionWizard.cpp20
-rw-r--r--cmds/statsd/src/condition/ConditionWizard.h10
-rw-r--r--cmds/statsd/src/condition/SimpleConditionTracker.cpp77
-rw-r--r--cmds/statsd/src/condition/SimpleConditionTracker.h11
-rw-r--r--cmds/statsd/src/condition/StateConditionTracker.cpp (renamed from cmds/statsd/src/condition/StateTracker.cpp)51
-rw-r--r--cmds/statsd/src/condition/StateConditionTracker.h (renamed from cmds/statsd/src/condition/StateTracker.h)30
-rw-r--r--cmds/statsd/src/external/GpuStatsPuller.cpp1
-rw-r--r--cmds/statsd/src/matchers/matcher_util.cpp2
-rw-r--r--cmds/statsd/src/metrics/CountMetricProducer.cpp17
-rw-r--r--cmds/statsd/src/metrics/DurationMetricProducer.cpp235
-rw-r--r--cmds/statsd/src/metrics/GaugeMetricProducer.cpp16
-rw-r--r--cmds/statsd/src/metrics/MetricProducer.cpp22
-rw-r--r--cmds/statsd/src/metrics/MetricProducer.h6
-rw-r--r--cmds/statsd/src/metrics/MetricsManager.h11
-rw-r--r--cmds/statsd/src/metrics/ValueMetricProducer.cpp16
-rw-r--r--cmds/statsd/src/metrics/duration_helper/DurationTracker.h6
-rw-r--r--cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.cpp22
-rw-r--r--cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.h2
-rw-r--r--cmds/statsd/src/metrics/duration_helper/OringDurationTracker.cpp30
-rw-r--r--cmds/statsd/src/metrics/duration_helper/OringDurationTracker.h2
-rw-r--r--cmds/statsd/src/metrics/metrics_manager_util.cpp16
-rw-r--r--cmds/statsd/src/metrics/metrics_manager_util.h2
-rw-r--r--cmds/statsd/src/stats_log.proto22
-rw-r--r--cmds/statsd/src/statsd_config.proto8
-rw-r--r--cmds/statsd/tests/LogEntryMatcher_test.cpp40
-rw-r--r--cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp55
-rw-r--r--cmds/statsd/tests/condition/StateConditionTracker_test.cpp (renamed from cmds/statsd/tests/condition/StateTracker_test.cpp)6
-rw-r--r--cmds/statsd/tests/e2e/DimensionInCondition_e2e_combination_AND_cond_test.cpp961
-rw-r--r--cmds/statsd/tests/e2e/DimensionInCondition_e2e_combination_OR_cond_test.cpp816
-rw-r--r--cmds/statsd/tests/e2e/DimensionInCondition_e2e_simple_cond_test.cpp814
-rw-r--r--cmds/statsd/tests/external/GpuStatsPuller_test.cpp5
-rw-r--r--cmds/statsd/tests/metrics/CountMetricProducer_test.cpp4
-rw-r--r--cmds/statsd/tests/metrics/EventMetricProducer_test.cpp4
-rw-r--r--cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp15
-rw-r--r--cmds/statsd/tests/metrics/MaxDurationTracker_test.cpp26
-rw-r--r--cmds/statsd/tests/metrics/OringDurationTracker_test.cpp45
-rw-r--r--cmds/statsd/tests/metrics/metrics_test_helper.h8
-rw-r--r--cmds/statsd/tools/dogfood/Android.bp37
-rw-r--r--cmds/statsd/tools/dogfood/AndroidManifest.xml43
-rw-r--r--cmds/statsd/tools/dogfood/res/drawable-hdpi/ic_launcher.pngbin7783 -> 0 bytes
-rw-r--r--cmds/statsd/tools/dogfood/res/drawable-mdpi/ic_launcher.pngbin3760 -> 0 bytes
-rw-r--r--cmds/statsd/tools/dogfood/res/drawable-xhdpi/ic_launcher.pngbin12356 -> 0 bytes
-rw-r--r--cmds/statsd/tools/dogfood/res/drawable-xxhdpi/ic_launcher.pngbin24780 -> 0 bytes
-rw-r--r--cmds/statsd/tools/dogfood/res/layout/activity_main.xml162
-rw-r--r--cmds/statsd/tools/dogfood/res/raw/statsd_baseline_config109
-rw-r--r--cmds/statsd/tools/dogfood/res/values/strings.xml57
-rw-r--r--cmds/statsd/tools/dogfood/src/com/android/statsd/dogfood/DisplayProtoUtils.java158
-rw-r--r--cmds/statsd/tools/dogfood/src/com/android/statsd/dogfood/MainActivity.java361
-rw-r--r--cmds/statsd/tools/loadtest/Android.bp37
-rw-r--r--cmds/statsd/tools/loadtest/AndroidManifest.xml44
-rw-r--r--cmds/statsd/tools/loadtest/res/drawable-hdpi/ic_launcher.pngbin7783 -> 0 bytes
-rw-r--r--cmds/statsd/tools/loadtest/res/drawable-mdpi/ic_launcher.pngbin3760 -> 0 bytes
-rw-r--r--cmds/statsd/tools/loadtest/res/drawable-xhdpi/ic_launcher.pngbin12356 -> 0 bytes
-rw-r--r--cmds/statsd/tools/loadtest/res/drawable-xxhdpi/ic_launcher.pngbin24780 -> 0 bytes
-rw-r--r--cmds/statsd/tools/loadtest/res/layout/activity_loadtest.xml208
-rw-r--r--cmds/statsd/tools/loadtest/res/layout/spinner_item.xml10
-rwxr-xr-xcmds/statsd/tools/loadtest/res/raw/loadtest_configbin2087 -> 0 bytes
-rw-r--r--cmds/statsd/tools/loadtest/res/values/integers.xml24
-rw-r--r--cmds/statsd/tools/loadtest/res/values/strings.xml36
-rwxr-xr-xcmds/statsd/tools/loadtest/run_loadtest.sh99
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/BatteryDataRecorder.java56
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/BatteryStatsParser.java113
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/ConfigFactory.java314
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/DisplayProtoUtils.java169
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/LoadtestActivity.java756
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/MemInfoParser.java69
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/MemoryDataRecorder.java53
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/NumericalWatcher.java70
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/PerfData.java116
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/PerfDataRecorder.java174
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/PerfParser.java27
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/SequencePusher.java165
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/StatsdStatsRecorder.java62
-rw-r--r--cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/ValidationRecorder.java93
97 files changed, 858 insertions, 7043 deletions
diff --git a/cmds/bmgr/TEST_MAPPING b/cmds/bmgr/TEST_MAPPING
new file mode 100644
index 000000000000..7c0e79e7692d
--- /dev/null
+++ b/cmds/bmgr/TEST_MAPPING
@@ -0,0 +1,11 @@
+{
+ "presubmit": [
+ ],
+ "postsubmit": [
+ ],
+ "imports": [
+ {
+ "path": "frameworks/base/services/backup"
+ }
+ ]
+}
diff --git a/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java b/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java
index 680ccfc57ddf..ed717c491467 100644
--- a/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java
+++ b/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java
@@ -64,6 +64,10 @@ public class Bmgr {
private static final String BMGR_NOT_RUNNING_ERR =
"Error: Could not access the Backup Manager. Is the system running?";
+ private static final String BMGR_NOT_ACTIVATED_FOR_USER =
+ "Error: Backup Manager is not activated for user ";
+ private static final String BMGR_ERR_NO_RESTORESESSION_FOR_USER =
+ "Error: Could not get restore session for user ";
private static final String TRANSPORT_NOT_RUNNING_ERR =
"Error: Could not access the backup transport. Is the system running?";
private static final String PM_NOT_RUNNING_ERR =
@@ -121,6 +125,11 @@ public class Bmgr {
return;
}
+ if ("autorestore".equals(op)) {
+ doAutoRestore(userId);
+ return;
+ }
+
if ("enabled".equals(op)) {
doEnabled(userId);
return;
@@ -190,21 +199,45 @@ public class Bmgr {
showUsage();
}
- boolean isBackupActive(@UserIdInt int userId) {
+ private void handleRemoteException(RemoteException e) {
+ System.err.println(e.toString());
+ System.err.println(BMGR_NOT_RUNNING_ERR);
+ }
+
+ private boolean isBackupActive(@UserIdInt int userId) {
try {
if (!mBmgr.isBackupServiceActive(userId)) {
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ System.err.println(BMGR_NOT_ACTIVATED_FOR_USER + userId);
return false;
}
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
return false;
}
return true;
}
+ private void doAutoRestore(int userId) {
+ String arg = nextArg();
+ if (arg == null) {
+ showUsage();
+ return;
+ }
+
+ try {
+ boolean enable = Boolean.parseBoolean(arg);
+ mBmgr.setAutoRestore(enable);
+ System.out.println(
+ "Auto restore is now "
+ + (enable ? "enabled" : "disabled")
+ + " for user "
+ + userId);
+ } catch (RemoteException e) {
+ handleRemoteException(e);
+ }
+ }
+
private String activatedToString(boolean activated) {
return activated ? "activated" : "deactivated";
}
@@ -214,8 +247,7 @@ public class Bmgr {
System.out.println("Backup Manager currently "
+ activatedToString(mBmgr.isBackupServiceActive(userId)));
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -230,8 +262,7 @@ public class Bmgr {
System.out.println("Backup Manager currently "
+ enableToString(isEnabled));
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -250,8 +281,7 @@ public class Bmgr {
showUsage();
return;
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -259,8 +289,7 @@ public class Bmgr {
try {
mBmgr.backupNowForUser(userId);
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -274,8 +303,7 @@ public class Bmgr {
try {
mBmgr.dataChangedForUser(userId, pkg);
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -292,8 +320,7 @@ public class Bmgr {
mBmgr.fullTransportBackupForUser(
userId, allPkgs.toArray(new String[allPkgs.size()]));
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
}
@@ -421,8 +448,7 @@ public class Bmgr {
try {
filteredPackages = mBmgr.filterAppsEligibleForBackupForUser(userId, packages);
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
backupNowPackages(userId, Arrays.asList(filteredPackages), nonIncrementalBackup,
monitorState);
@@ -455,8 +481,7 @@ public class Bmgr {
System.err.println("Unable to run backup");
}
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -506,8 +531,7 @@ public class Bmgr {
try {
mBmgr.cancelBackupsForUser(userId);
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
return;
}
@@ -537,8 +561,7 @@ public class Bmgr {
}
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -569,8 +592,7 @@ public class Bmgr {
}
});
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
return;
}
@@ -598,8 +620,7 @@ public class Bmgr {
mBmgr.clearBackupDataForUser(userId, transport, pkg);
System.out.println("Wiped backup data for " + pkg + " on " + transport);
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -632,8 +653,7 @@ public class Bmgr {
observer.waitForCompletion(30*1000L);
System.out.println("Initialization result: " + observer.result);
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -648,7 +668,7 @@ public class Bmgr {
try {
mRestore = mBmgr.beginRestoreSessionForUser(userId, null, null);
if (mRestore == null) {
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ System.err.println(BMGR_ERR_NO_RESTORESESSION_FOR_USER + userId);
return;
}
@@ -658,8 +678,7 @@ public class Bmgr {
mRestore.endRestoreSession();
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -686,8 +705,7 @@ public class Bmgr {
System.out.println(pad + t);
}
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -805,7 +823,7 @@ public class Bmgr {
boolean didRestore = false;
mRestore = mBmgr.beginRestoreSessionForUser(userId, null, null);
if (mRestore == null) {
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ System.err.println(BMGR_ERR_NO_RESTORESESSION_FOR_USER + userId);
return;
}
RestoreSet[] sets = null;
@@ -851,8 +869,7 @@ public class Bmgr {
System.out.println("done");
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -865,8 +882,7 @@ public class Bmgr {
}
}
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -886,8 +902,7 @@ public class Bmgr {
+ " for user "
+ userId);
} catch (RemoteException e) {
- System.err.println(e.toString());
- System.err.println(BMGR_NOT_RUNNING_ERR);
+ handleRemoteException(e);
}
}
@@ -928,6 +943,7 @@ public class Bmgr {
System.err.println(" bmgr init TRANSPORT...");
System.err.println(" bmgr activate BOOL");
System.err.println(" bmgr activated");
+ System.err.println(" bmgr autorestore BOOL");
System.err.println("");
System.err.println("The '--user' option specifies the user on which the operation is run.");
System.err.println("It must be the first argument before the operation.");
@@ -1002,6 +1018,9 @@ public class Bmgr {
System.err.println("");
System.err.println("The 'activated' command reports the current activated/deactivated");
System.err.println("state of the backup mechanism.");
+ System.err.println("");
+ System.err.println("The 'autorestore' command enables or disables automatic restore when");
+ System.err.println("a new package is installed.");
}
private static class BackupMonitor extends IBackupManagerMonitor.Stub {
diff --git a/cmds/bootanimation/BootAnimation.cpp b/cmds/bootanimation/BootAnimation.cpp
index db384baff4d7..e1cb7ca6a697 100644
--- a/cmds/bootanimation/BootAnimation.cpp
+++ b/cmds/bootanimation/BootAnimation.cpp
@@ -288,6 +288,48 @@ status_t BootAnimation::readyToRun() {
dinfo.w, dinfo.h, PIXEL_FORMAT_RGB_565);
SurfaceComposerClient::Transaction t;
+
+ // this guest property specifies multi-display IDs to show the boot animation
+ // multiple ids can be set with comma (,) as separator, for example:
+ // setprop boot.animation.displays 19260422155234049,19261083906282754
+ Vector<uint64_t> physicalDisplayIds;
+ char displayValue[PROPERTY_VALUE_MAX] = "";
+ property_get("boot.animation.displays", displayValue, "");
+ bool isValid = displayValue[0] != '\0';
+ if (isValid) {
+ char *p = displayValue;
+ while (*p) {
+ if (!isdigit(*p) && *p != ',') {
+ isValid = false;
+ break;
+ }
+ p ++;
+ }
+ if (!isValid)
+ SLOGE("Invalid syntax for the value of system prop: boot.animation.displays");
+ }
+ if (isValid) {
+ std::istringstream stream(displayValue);
+ for (PhysicalDisplayId id; stream >> id; ) {
+ physicalDisplayIds.add(id);
+ if (stream.peek() == ',')
+ stream.ignore();
+ }
+
+ // In the case of multi-display, boot animation shows on the specified displays
+ // in addition to the primary display
+ auto ids = SurfaceComposerClient::getPhysicalDisplayIds();
+ constexpr uint32_t LAYER_STACK = 0;
+ for (auto id : physicalDisplayIds) {
+ if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
+ sp<IBinder> token = SurfaceComposerClient::getPhysicalDisplayToken(id);
+ if (token != nullptr)
+ t.setDisplayLayerStack(token, LAYER_STACK);
+ }
+ }
+ t.setLayerStack(control, LAYER_STACK);
+ }
+
t.setLayer(control, 0x40000000)
.apply();
diff --git a/cmds/idmap2/idmap2/Scan.cpp b/cmds/idmap2/idmap2/Scan.cpp
index cfac5f31e2e6..053b7bc9afa3 100644
--- a/cmds/idmap2/idmap2/Scan.cpp
+++ b/cmds/idmap2/idmap2/Scan.cpp
@@ -98,13 +98,16 @@ Result<std::unique_ptr<std::vector<std::string>>> FindApkFiles(const std::vector
}
std::vector<std::string> PoliciesForPath(const std::string& apk_path) {
+ // clang-format off
static const std::vector<std::pair<std::string, std::string>> values = {
{"/odm/", kPolicyOdm},
{"/oem/", kPolicyOem},
{"/product/", kPolicyProduct},
{"/system/", kPolicySystem},
+ {"/system_ext/", kPolicySystem},
{"/vendor/", kPolicyVendor},
};
+ // clang-format on
std::vector<std::string> fulfilled_policies = {kPolicyPublic};
for (auto const& pair : values) {
diff --git a/cmds/idmap2/idmap2d/Idmap2Service.h b/cmds/idmap2/idmap2d/Idmap2Service.h
index 1aab0598449b..94d2af49260c 100644
--- a/cmds/idmap2/idmap2d/Idmap2Service.h
+++ b/cmds/idmap2/idmap2d/Idmap2Service.h
@@ -34,18 +34,19 @@ class Idmap2Service : public BinderService<Idmap2Service>, public BnIdmap2 {
}
binder::Status getIdmapPath(const std::string& overlay_apk_path, int32_t user_id,
- std::string* _aidl_return);
+ std::string* _aidl_return) override;
binder::Status removeIdmap(const std::string& overlay_apk_path, int32_t user_id,
- bool* _aidl_return);
+ bool* _aidl_return) override;
binder::Status verifyIdmap(const std::string& overlay_apk_path, int32_t fulfilled_policies,
- bool enforce_overlayable, int32_t user_id, bool* _aidl_return);
+ bool enforce_overlayable, int32_t user_id,
+ bool* _aidl_return) override;
binder::Status createIdmap(const std::string& target_apk_path,
const std::string& overlay_apk_path, int32_t fulfilled_policies,
bool enforce_overlayable, int32_t user_id,
- std::unique_ptr<std::string>* _aidl_return);
+ std::unique_ptr<std::string>* _aidl_return) override;
};
} // namespace android::os
diff --git a/cmds/idmap2/include/idmap2/BinaryStreamVisitor.h b/cmds/idmap2/include/idmap2/BinaryStreamVisitor.h
index 2c3e9d321881..1a0d4438f1b3 100644
--- a/cmds/idmap2/include/idmap2/BinaryStreamVisitor.h
+++ b/cmds/idmap2/include/idmap2/BinaryStreamVisitor.h
@@ -29,11 +29,12 @@ class BinaryStreamVisitor : public Visitor {
public:
explicit BinaryStreamVisitor(std::ostream& stream) : stream_(stream) {
}
- virtual void visit(const Idmap& idmap);
- virtual void visit(const IdmapHeader& header);
- virtual void visit(const IdmapData& data);
- virtual void visit(const IdmapData::Header& header);
- virtual void visit(const IdmapData::TypeEntry& type_entry);
+ ~BinaryStreamVisitor() override = default;
+ void visit(const Idmap& idmap) override;
+ void visit(const IdmapHeader& header) override;
+ void visit(const IdmapData& data) override;
+ void visit(const IdmapData::Header& header) override;
+ void visit(const IdmapData::TypeEntry& type_entry) override;
private:
void Write16(uint16_t value);
diff --git a/cmds/idmap2/include/idmap2/PrettyPrintVisitor.h b/cmds/idmap2/include/idmap2/PrettyPrintVisitor.h
index 5111bb2eaab2..f0f141a3757c 100644
--- a/cmds/idmap2/include/idmap2/PrettyPrintVisitor.h
+++ b/cmds/idmap2/include/idmap2/PrettyPrintVisitor.h
@@ -33,11 +33,12 @@ class PrettyPrintVisitor : public Visitor {
public:
explicit PrettyPrintVisitor(std::ostream& stream) : stream_(stream) {
}
- virtual void visit(const Idmap& idmap);
- virtual void visit(const IdmapHeader& header);
- virtual void visit(const IdmapData& data);
- virtual void visit(const IdmapData::Header& header);
- virtual void visit(const IdmapData::TypeEntry& type_entry);
+ ~PrettyPrintVisitor() override = default;
+ void visit(const Idmap& idmap) override;
+ void visit(const IdmapHeader& header) override;
+ void visit(const IdmapData& data) override;
+ void visit(const IdmapData::Header& header) override;
+ void visit(const IdmapData::TypeEntry& type_entry) override;
private:
std::ostream& stream_;
diff --git a/cmds/idmap2/include/idmap2/RawPrintVisitor.h b/cmds/idmap2/include/idmap2/RawPrintVisitor.h
index 2e543d4fabdd..cd3897109a32 100644
--- a/cmds/idmap2/include/idmap2/RawPrintVisitor.h
+++ b/cmds/idmap2/include/idmap2/RawPrintVisitor.h
@@ -34,11 +34,12 @@ class RawPrintVisitor : public Visitor {
public:
explicit RawPrintVisitor(std::ostream& stream) : stream_(stream), offset_(0) {
}
- virtual void visit(const Idmap& idmap);
- virtual void visit(const IdmapHeader& header);
- virtual void visit(const IdmapData& data);
- virtual void visit(const IdmapData::Header& header);
- virtual void visit(const IdmapData::TypeEntry& type_entry);
+ ~RawPrintVisitor() override = default;
+ void visit(const Idmap& idmap) override;
+ void visit(const IdmapHeader& header) override;
+ void visit(const IdmapData& data) override;
+ void visit(const IdmapData::Header& header) override;
+ void visit(const IdmapData::TypeEntry& type_entry) override;
private:
void print(uint16_t value, const char* fmt, ...);
diff --git a/cmds/idmap2/tests/TestHelpers.h b/cmds/idmap2/tests/TestHelpers.h
index adea3293534d..a7c2f284e7c5 100644
--- a/cmds/idmap2/tests/TestHelpers.h
+++ b/cmds/idmap2/tests/TestHelpers.h
@@ -123,7 +123,7 @@ std::string GetTestDataPath();
class Idmap2Tests : public testing::Test {
protected:
- virtual void SetUp() {
+ void SetUp() override {
#ifdef __ANDROID__
tmp_dir_path_ = "/data/local/tmp/idmap2-tests-XXXXXX";
#else
@@ -136,7 +136,7 @@ class Idmap2Tests : public testing::Test {
idmap_path_ = tmp_dir_path_ + "/a.idmap";
}
- virtual void TearDown() {
+ void TearDown() override {
EXPECT_EQ(rmdir(tmp_dir_path_.c_str()), 0)
<< "Failed to remove temporary directory " << tmp_dir_path_ << ": " << strerror(errno);
}
diff --git a/cmds/incident/main.cpp b/cmds/incident/main.cpp
index dfb4f994b866..6c3d19715c2e 100644
--- a/cmds/incident/main.cpp
+++ b/cmds/incident/main.cpp
@@ -198,6 +198,26 @@ parse_receiver_arg(const string& arg, string* pkg, string* cls)
}
// ================================================================================
+static int
+stream_output(const int read_fd, const int write_fd) {
+ while (true) {
+ uint8_t buf[4096];
+ ssize_t amt = TEMP_FAILURE_RETRY(read(read_fd, buf, sizeof(buf)));
+ if (amt < 0) {
+ break;
+ } else if (amt == 0) {
+ break;
+ }
+
+ ssize_t wamt = TEMP_FAILURE_RETRY(write(write_fd, buf, amt));
+ if (wamt != amt) {
+ return errno;
+ }
+ }
+ return 0;
+}
+
+// ================================================================================
static void
usage(FILE* out)
{
@@ -208,11 +228,13 @@ usage(FILE* out)
fprintf(out, "OPTIONS\n");
fprintf(out, " -l list available sections\n");
fprintf(out, " -p privacy spec, LOCAL, EXPLICIT or AUTOMATIC. Default AUTOMATIC.\n");
+ fprintf(out, " -r REASON human readable description of why the report is taken.\n");
fprintf(out, "\n");
fprintf(out, "and one of these destinations:\n");
fprintf(out, " -b (default) print the report to stdout (in proto format)\n");
fprintf(out, " -d send the report into dropbox\n");
- fprintf(out, " -r REASON human readable description of why the report is taken.\n");
+ fprintf(out, " -u print a full report to stdout for dumpstate to zip as a bug\n");
+ fprintf(out, " report. SECTION is ignored. Should only be called by dumpstate.\n");
fprintf(out, " -s PKG/CLS send broadcast to the broadcast receiver.\n");
fprintf(out, "\n");
fprintf(out, " SECTION the field numbers of the incident report fields to include\n");
@@ -224,14 +246,14 @@ main(int argc, char** argv)
{
Status status;
IncidentReportArgs args;
- enum { DEST_UNSET, DEST_DROPBOX, DEST_STDOUT, DEST_BROADCAST } destination = DEST_UNSET;
+ enum { DEST_UNSET, DEST_DROPBOX, DEST_STDOUT, DEST_BROADCAST, DEST_DUMPSTATE } destination = DEST_UNSET;
int privacyPolicy = PRIVACY_POLICY_AUTOMATIC;
string reason;
string receiverArg;
// Parse the args
int opt;
- while ((opt = getopt(argc, argv, "bhdlp:r:s:")) != -1) {
+ while ((opt = getopt(argc, argv, "bhdlp:r:s:u")) != -1) {
switch (opt) {
case 'h':
usage(stdout);
@@ -253,6 +275,13 @@ main(int argc, char** argv)
}
destination = DEST_DROPBOX;
break;
+ case 'u':
+ if (!(destination == DEST_UNSET || destination == DEST_DUMPSTATE)) {
+ usage(stderr);
+ return 1;
+ }
+ destination = DEST_DUMPSTATE;
+ break;
case 'p':
privacyPolicy = get_privacy_policy(optarg);
break;
@@ -355,21 +384,16 @@ main(int argc, char** argv)
// Wait for the result and print out the data they send.
//IPCThreadState::self()->joinThreadPool();
-
- while (true) {
- uint8_t buf[4096];
- ssize_t amt = TEMP_FAILURE_RETRY(read(fds[0], buf, sizeof(buf)));
- if (amt < 0) {
- break;
- } else if (amt == 0) {
- break;
- }
-
- ssize_t wamt = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, buf, amt));
- if (wamt != amt) {
- return errno;
- }
+ return stream_output(fds[0], STDOUT_FILENO);
+ } else if (destination == DEST_DUMPSTATE) {
+ // Call into the service
+ sp<StatusListener> listener(new StatusListener());
+ status = service->reportIncidentToDumpstate(writeEnd, listener);
+ if (!status.isOk()) {
+ fprintf(stderr, "reportIncident returned \"%s\"\n", status.toString8().string());
+ return 1;
}
+ return stream_output(fds[0], STDOUT_FILENO);
} else {
status = service->reportIncident(args);
if (!status.isOk()) {
diff --git a/cmds/incidentd/src/IncidentService.cpp b/cmds/incidentd/src/IncidentService.cpp
index a52726396b53..999936bda1d3 100644
--- a/cmds/incidentd/src/IncidentService.cpp
+++ b/cmds/incidentd/src/IncidentService.cpp
@@ -46,12 +46,11 @@ enum {
#define DEFAULT_BYTES_SIZE_LIMIT (96 * 1024 * 1024) // 96MB
#define DEFAULT_REFACTORY_PERIOD_MS (24 * 60 * 60 * 1000) // 1 Day
-// Skip these sections for dumpstate only. Dumpstate allows 10s max for each service to dump.
+// Skip these sections (for dumpstate only)
// Skip logs (1100 - 1108) and traces (1200 - 1202) because they are already in the bug report.
-// Skip 3018 because it takes too long.
-#define SKIPPED_SECTIONS { 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, /* Logs */ \
- 1200, 1201, 1202, /* Native, hal, java traces */ \
- 3018 /* "meminfo -a --proto" */ }
+#define SKIPPED_DUMPSTATE_SECTIONS { \
+ 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, /* Logs */ \
+ 1200, 1201, 1202, /* Native, hal, java traces */ }
namespace android {
namespace os {
@@ -307,6 +306,39 @@ Status IncidentService::reportIncidentToStream(const IncidentReportArgs& args,
return Status::ok();
}
+Status IncidentService::reportIncidentToDumpstate(const unique_fd& stream,
+ const sp<IIncidentReportStatusListener>& listener) {
+ uid_t caller = IPCThreadState::self()->getCallingUid();
+ if (caller != AID_ROOT && caller != AID_SHELL) {
+ ALOGW("Calling uid %d does not have permission: only ROOT or SHELL allowed", caller);
+ return Status::fromExceptionCode(Status::EX_SECURITY, "Only ROOT or SHELL allowed");
+ }
+
+ ALOGD("Stream incident report to dumpstate");
+ IncidentReportArgs incidentArgs;
+ // Privacy policy for dumpstate incident reports is always EXPLICIT.
+ incidentArgs.setPrivacyPolicy(PRIVACY_POLICY_EXPLICIT);
+
+ int skipped[] = SKIPPED_DUMPSTATE_SECTIONS;
+ for (const Section** section = SECTION_LIST; *section; section++) {
+ const int id = (*section)->id;
+ if (std::find(std::begin(skipped), std::end(skipped), id) == std::end(skipped)
+ && !section_requires_specific_mention(id)) {
+ incidentArgs.addSection(id);
+ }
+ }
+
+ // The ReportRequest takes ownership of the fd, so we need to dup it.
+ int fd = dup(stream.get());
+ if (fd < 0) {
+ return Status::fromStatusT(-errno);
+ }
+
+ mHandler->scheduleStreamingReport(incidentArgs, listener, fd);
+
+ return Status::ok();
+}
+
Status IncidentService::systemRunning() {
if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
return Status::fromExceptionCode(Status::EX_SECURITY,
@@ -551,43 +583,6 @@ status_t IncidentService::cmd_privacy(FILE* in, FILE* out, FILE* err, Vector<Str
return NO_ERROR;
}
-status_t IncidentService::dump(int fd, const Vector<String16>& args) {
- if (std::find(args.begin(), args.end(), String16("--proto")) == args.end()) {
- ALOGD("Skip dumping incident. Only proto format is supported.");
- dprintf(fd, "Incident dump only supports proto version.\n");
- return NO_ERROR;
- }
-
- ALOGD("Dump incident proto");
- IncidentReportArgs incidentArgs;
- incidentArgs.setPrivacyPolicy(PRIVACY_POLICY_EXPLICIT);
- int skipped[] = SKIPPED_SECTIONS;
- for (const Section** section = SECTION_LIST; *section; section++) {
- const int id = (*section)->id;
- if (std::find(std::begin(skipped), std::end(skipped), id) == std::end(skipped)
- && !section_requires_specific_mention(id)) {
- incidentArgs.addSection(id);
- }
- }
-
- if (!checkIncidentPermissions(incidentArgs).isOk()) {
- return PERMISSION_DENIED;
- }
-
- // The ReportRequest takes ownership of the fd, so we need to dup it.
- int fd1 = dup(fd);
- if (fd1 < 0) {
- return -errno;
- }
-
- // TODO: Remove this. Someone even dumpstate, wanting to get an incident report
- // should use the API. That will take making dumpstated call the API, which is a
- // good thing. It also means it won't be subject to the timeout.
- mHandler->scheduleStreamingReport(incidentArgs, NULL, fd1);
-
- return NO_ERROR;
-}
-
} // namespace incidentd
} // namespace os
} // namespace android
diff --git a/cmds/incidentd/src/IncidentService.h b/cmds/incidentd/src/IncidentService.h
index 6481321bbd69..fb013d0bf92d 100644
--- a/cmds/incidentd/src/IncidentService.h
+++ b/cmds/incidentd/src/IncidentService.h
@@ -123,6 +123,9 @@ public:
const sp<IIncidentReportStatusListener>& listener,
const unique_fd& stream);
+ virtual Status reportIncidentToDumpstate(const unique_fd& stream,
+ const sp<IIncidentReportStatusListener>& listener);
+
virtual Status systemRunning();
virtual Status getIncidentReportList(const String16& pkg, const String16& cls,
@@ -140,7 +143,6 @@ public:
virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply,
uint32_t flags) override;
virtual status_t command(FILE* in, FILE* out, FILE* err, Vector<String8>& args);
- virtual status_t dump(int fd, const Vector<String16>& args);
private:
sp<WorkDirectory> mWorkDirectory;
diff --git a/cmds/incidentd/src/main.cpp b/cmds/incidentd/src/main.cpp
index 098d74ecd786..494882336611 100644
--- a/cmds/incidentd/src/main.cpp
+++ b/cmds/incidentd/src/main.cpp
@@ -45,8 +45,7 @@ int main(int /*argc*/, char** /*argv*/) {
// Create the service
sp<IncidentService> service = new IncidentService(looper);
- if (defaultServiceManager()->addService(String16("incident"), service, false,
- IServiceManager::DUMP_FLAG_PRIORITY_NORMAL | IServiceManager::DUMP_FLAG_PROTO) != 0) {
+ if (defaultServiceManager()->addService(String16("incident"), service) != 0) {
ALOGE("Failed to add service");
return -1;
}
diff --git a/cmds/locksettings/TEST_MAPPING b/cmds/locksettings/TEST_MAPPING
new file mode 100644
index 000000000000..c1cba5f7f22d
--- /dev/null
+++ b/cmds/locksettings/TEST_MAPPING
@@ -0,0 +1,15 @@
+{
+ "presubmit": [
+ {
+ "name": "CtsDevicePolicyManagerTestCases",
+ "options": [
+ {
+ "include-annotation": "com.android.cts.devicepolicy.annotations.LockSettingsTest"
+ },
+ {
+ "exclude-annotation": "android.platform.test.annotations.FlakyTest"
+ }
+ ]
+ }
+ ]
+}
diff --git a/cmds/statsd/Android.bp b/cmds/statsd/Android.bp
index 6df0a8e14f6a..c9a4b3ba6368 100644
--- a/cmds/statsd/Android.bp
+++ b/cmds/statsd/Android.bp
@@ -65,7 +65,7 @@ cc_defaults {
"src/condition/condition_util.cpp",
"src/condition/SimpleConditionTracker.cpp",
"src/condition/ConditionWizard.cpp",
- "src/condition/StateTracker.cpp",
+ "src/condition/StateConditionTracker.cpp",
"src/config/ConfigKey.cpp",
"src/config/ConfigListener.cpp",
"src/config/ConfigManager.cpp",
@@ -129,17 +129,12 @@ cc_defaults {
"libservices",
"libprotoutil",
"libstatslog",
- "libhardware",
- "libhardware_legacy",
"libhidlbase",
- "libhidltransport",
- "libhwbinder",
"android.frameworks.stats@1.0",
"android.hardware.health@2.0",
"android.hardware.power@1.0",
"android.hardware.power@1.1",
"android.hardware.power.stats@1.0",
- "libpackagelistparser",
"libsysutils",
"libcutils",
],
@@ -209,6 +204,10 @@ cc_test {
],
srcs: [
+ // atom_field_options.proto needs field_options.proto, but that is
+ // not included in libprotobuf-cpp-lite, so compile it here.
+ ":libprotobuf-internal-protos",
+
"src/atom_field_options.proto",
"src/atoms.proto",
"src/stats_log.proto",
@@ -232,7 +231,7 @@ cc_test {
"tests/FieldValue_test.cpp",
"tests/condition/CombinationConditionTracker_test.cpp",
"tests/condition/SimpleConditionTracker_test.cpp",
- "tests/condition/StateTracker_test.cpp",
+ "tests/condition/StateConditionTracker_test.cpp",
"tests/condition/ConditionTimer_test.cpp",
"tests/metrics/OringDurationTracker_test.cpp",
"tests/metrics/MaxDurationTracker_test.cpp",
@@ -253,9 +252,6 @@ cc_test {
"tests/e2e/GaugeMetric_e2e_push_test.cpp",
"tests/e2e/GaugeMetric_e2e_pull_test.cpp",
"tests/e2e/ValueMetric_pull_e2e_test.cpp",
- "tests/e2e/DimensionInCondition_e2e_combination_AND_cond_test.cpp",
- "tests/e2e/DimensionInCondition_e2e_combination_OR_cond_test.cpp",
- "tests/e2e/DimensionInCondition_e2e_simple_cond_test.cpp",
"tests/e2e/Anomaly_count_e2e_test.cpp",
"tests/e2e/Anomaly_duration_sum_e2e_test.cpp",
"tests/e2e/ConfigTtl_e2e_test.cpp",
@@ -270,11 +266,11 @@ cc_test {
],
proto: {
- type: "full",
+ type: "lite",
include_dirs: ["external/protobuf/src"],
},
- shared_libs: ["libprotobuf-cpp-full"],
+ shared_libs: ["libprotobuf-cpp-lite"],
}
@@ -287,6 +283,10 @@ cc_benchmark {
defaults: ["statsd_defaults"],
srcs: [
+ // atom_field_options.proto needs field_options.proto, but that is
+ // not included in libprotobuf-cpp-lite, so compile it here.
+ ":libprotobuf-internal-protos",
+
"src/atom_field_options.proto",
"src/atoms.proto",
"src/stats_log.proto",
@@ -301,7 +301,7 @@ cc_benchmark {
],
proto: {
- type: "full",
+ type: "lite",
include_dirs: ["external/protobuf/src"],
},
@@ -323,7 +323,7 @@ cc_benchmark {
shared_libs: [
"libgtest_prod",
"libstatslog",
- "libprotobuf-cpp-full",
+ "libprotobuf-cpp-lite",
],
}
diff --git a/cmds/statsd/OWNERS b/cmds/statsd/OWNERS
index 380e499a5abf..04464ce02b4f 100644
--- a/cmds/statsd/OWNERS
+++ b/cmds/statsd/OWNERS
@@ -3,5 +3,6 @@ joeo@google.com
jtnguyen@google.com
muhammadq@google.com
singhtejinder@google.com
+tsaichristine@google.com
yaochen@google.com
yro@google.com
diff --git a/cmds/statsd/src/FieldValue.cpp b/cmds/statsd/src/FieldValue.cpp
index 13f5c8ae5fd8..1185127ab805 100644
--- a/cmds/statsd/src/FieldValue.cpp
+++ b/cmds/statsd/src/FieldValue.cpp
@@ -149,6 +149,18 @@ bool isAttributionUidField(const Field& field, const Value& value) {
return false;
}
+bool isUidField(const Field& field, const Value& value) {
+ auto it = android::util::AtomsInfo::kAtomsWithUidField.find(field.getTag());
+
+ if (it != android::util::AtomsInfo::kAtomsWithUidField.end()) {
+ int uidField = it->second;
+ return field.getDepth() == 0 && field.getPosAtDepth(0) == uidField &&
+ value.getType() == INT;
+ }
+
+ return false;
+}
+
Value::Value(const Value& from) {
type = from.getType();
switch (type) {
@@ -464,4 +476,4 @@ bool HasPositionALL(const FieldMatcher& matcher) {
} // namespace statsd
} // namespace os
-} // namespace android \ No newline at end of file
+} // namespace android
diff --git a/cmds/statsd/src/FieldValue.h b/cmds/statsd/src/FieldValue.h
index 6729e052b5ee..0e033e06c203 100644
--- a/cmds/statsd/src/FieldValue.h
+++ b/cmds/statsd/src/FieldValue.h
@@ -392,6 +392,7 @@ int getUidIfExists(const FieldValue& value);
void translateFieldMatcher(const FieldMatcher& matcher, std::vector<Matcher>* output);
bool isAttributionUidField(const Field& field, const Value& value);
+bool isUidField(const Field& field, const Value& value);
bool equalDimensions(const std::vector<Matcher>& dimension_a,
const std::vector<Matcher>& dimension_b);
diff --git a/cmds/statsd/src/anomaly/AnomalyTracker.cpp b/cmds/statsd/src/anomaly/AnomalyTracker.cpp
index d1dcb5df7838..7ace44eef564 100644
--- a/cmds/statsd/src/anomaly/AnomalyTracker.cpp
+++ b/cmds/statsd/src/anomaly/AnomalyTracker.cpp
@@ -24,6 +24,7 @@
#include "subscriber/IncidentdReporter.h"
#include "subscriber/SubscriberReporter.h"
+#include <inttypes.h>
#include <statslog.h>
#include <time.h>
@@ -224,7 +225,7 @@ void AnomalyTracker::declareAnomaly(const int64_t& timestampNs, int64_t metricId
}
if (!mSubscriptions.empty()) {
- ALOGI("An anomaly (%lld) %s has occurred! Informing subscribers.",
+ ALOGI("An anomaly (%" PRId64 ") %s has occurred! Informing subscribers.",
mAlert.id(), key.toString().c_str());
informSubscribers(key, metricId, metricValue);
} else {
diff --git a/cmds/statsd/src/atoms.proto b/cmds/statsd/src/atoms.proto
index e7cce068cf5f..ae751ce6d7ab 100644
--- a/cmds/statsd/src/atoms.proto
+++ b/cmds/statsd/src/atoms.proto
@@ -56,6 +56,8 @@ import "frameworks/base/core/proto/android/telecomm/enums.proto";
import "frameworks/base/core/proto/android/telephony/enums.proto";
import "frameworks/base/core/proto/android/view/enums.proto";
import "frameworks/base/core/proto/android/wifi/enums.proto";
+import "frameworks/base/core/proto/android/stats/textclassifier/textclassifier_enums.proto";
+import "frameworks/base/core/proto/android/stats/otaupdate/updateengine_enums.proto";
/**
* The master atom class. This message defines all of the available
@@ -295,6 +297,7 @@ message Atom {
MediametricsMediadrmReported mediametrics_mediadrm_reported = 198;
MediametricsNuPlayerReported mediametrics_nuplayer_reported = 199;
MediametricsRecorderReported mediametrics_recorder_reported = 200;
+ MediametricsDrmManagerReported mediametrics_drmmanager_reported = 201;
CarPowerStateChanged car_power_state_changed = 203;
GarageModeInfo garage_mode_info = 204;
TestAtomReported test_atom_reported = 205 [(log_from_module) = "cts"];
@@ -319,12 +322,23 @@ message Atom {
217 [(log_from_module) = "permissioncontroller"];
PermissionAppsFragmentViewed permission_apps_fragment_viewed =
218 [(log_from_module) = "permissioncontroller"];
+ TextSelectionEvent text_selection_event =
+ 219 [(log_from_module) = "textclassifier"];
+ TextLinkifyEvent text_linkify_event =
+ 220 [(log_from_module) = "textclassifier"];
+ ConversationActionsEvent conversation_actions_event =
+ 221 [(log_from_module) = "textclassifier"];
+ LanguageDetectionEvent language_detection_event =
+ 222 [(log_from_module) = "textclassifier"];
ExclusionRectStateChanged exclusion_rect_state_changed = 223;
BackGesture back_gesture_reported_reported = 224;
+ UpdateEngineUpdateAttemptReported update_engine_update_attempt_reported = 225;
+ UpdateEngineSuccessfulUpdateReported update_engine_successful_update_reported = 226;
+ CameraActionEvent camera_action_event = 227;
}
// Pulled events will start at field 10000.
- // Next: 10062
+ // Next: 10064
oneof pulled {
WifiBytesTransfer wifi_bytes_transfer = 10000;
WifiBytesTransferByFgBg wifi_bytes_transfer_by_fg_bg = 10001;
@@ -388,6 +402,8 @@ message Atom {
CoolingDevice cooling_device = 10059;
AppOps app_ops = 10060;
ProcessSystemIonHeapSize process_system_ion_heap_size = 10061;
+ SurfaceflingerStatsGlobalInfo surfaceflinger_stats_global_info = 10062;
+ SurfaceflingerStatsLayerInfo surfaceflinger_stats_layer_info = 10063;
}
// DO NOT USE field numbers above 100,000 in AOSP.
@@ -5924,7 +5940,8 @@ message BubbleUIChanged {
optional bool is_ongoing = 10;
// Whether the bubble is produced by an app running in foreground.
- optional bool is_foreground = 11;
+ // This is deprecated and the value should be ignored.
+ optional bool is_foreground = 11 [deprecated = true];
}
/**
@@ -6192,6 +6209,41 @@ message MediametricsNuPlayerReported {
}
/**
+ * Track Legacy DRM usage
+ * Logged from
+ * frameworks/av/drm/drmserver/DrmManager.cpp
+ */
+message MediametricsDrmManagerReported {
+ optional int64 timestamp_nanos = 1;
+ optional string package_name = 2;
+ optional int64 package_version_code = 3;
+ optional int64 media_apex_version = 4;
+
+ enum Method {
+ METHOD_NOT_FOUND = -1;
+ GET_CONSTRAINTS = 0;
+ GET_METADATA = 1;
+ CAN_HANDLE = 2;
+ PROCESS_DRM_INFO = 3;
+ ACQUIRE_DRM_INFO = 4;
+ SAVE_RIGHTS = 5;
+ GET_ORIGINAL_MIME_TYPE = 6;
+ GET_DRM_OBJECT_TYPE = 7;
+ CHECK_RIGHTS_STATUS = 8;
+ REMOVE_RIGHTS = 9;
+ REMOVE_ALL_RIGHTS = 10;
+ OPEN_CONVERT_SESSION = 11;
+ OPEN_DECRYPT_SESSION = 12;
+ }
+
+ // plugin_id+description inform which Legacy DRM plugins are still in use on device
+ optional string plugin_id = 5;
+ optional string description = 6;
+ optional Method method = 7;
+ optional string mime_types = 8;
+}
+
+/**
* State of a dangerous permission requested by a package
*/
message DangerousPermissionState {
@@ -6400,6 +6452,9 @@ message GpuStatsAppInfo {
// CPU Vulkan implementation is in use.
optional bool cpu_vulkan_in_use = 6;
+
+ // App is not doing pre-rotation correctly.
+ optional bool false_prerotation = 7;
}
/*
@@ -6503,8 +6558,14 @@ message CoolingDevice {
* Logged from the Intelligence mainline module.
*/
message IntelligenceEventReported {
+ // The event type.
optional android.stats.intelligence.EventType event_id = 1;
+ // Success, failure.
optional android.stats.intelligence.Status status = 2;
+ // How many times the event occured (to report a batch of high frequency events).
+ optional int32 count = 3;
+ // How long the event took (sum of durations if count > 1)
+ optional int64 duration_millis = 4;
}
/**
@@ -6818,3 +6879,315 @@ message PermissionAppsFragmentViewed {
}
optional Category category = 6;
}
+
+/**
+ * Logs when there is a smart selection related event.
+ * See frameworks/base/core/java/android/view/textclassifier/TextClassifierEvent.java
+ * Logged from: TextClassifierEventLogger.java
+ */
+message TextSelectionEvent {
+ // A session ID.
+ optional string session_id = 1;
+
+ // Event type of this event.
+ optional android.stats.textclassifier.EventType event_type = 2;
+
+ // Name of the model that is involved in this event.
+ optional string model_name = 3;
+
+ // Type of widget that was involved in triggering this event.
+ optional android.stats.textclassifier.WidgetType widget_type = 4;
+
+ // Index of this event in a session.
+ optional int32 event_index = 5;
+
+ // Entity type that is involved.
+ optional string entity_type = 6;
+
+ // Relative word index of the start of the selection.
+ optional int32 relative_word_start_index = 7;
+
+ // Relative word (exclusive) index of the end of the selection.
+ optional int32 relative_word_end_index = 8;
+
+ // Relative word index of the start of the smart selection.
+ optional int32 relative_suggested_word_start_index = 9;
+
+ // Relative word (exclusive) index of the end of the smart selection.
+ optional int32 relative_suggested_word_end_index = 10;
+
+ // Name of source package.
+ optional string package_name = 11;
+}
+
+/**
+ * Logs when there is a smart linkify related event.
+ * See frameworks/base/core/java/android/view/textclassifier/TextClassifierEvent.java
+ * Logged from: TextClassifierEventLogger.java
+ */
+message TextLinkifyEvent {
+ // A session ID.
+ optional string session_id = 1;
+
+ // Event type of this event.
+ optional android.stats.textclassifier.EventType event_type = 2;
+
+ // Name of the model that is involved in this event.
+ optional string model_name = 3;
+
+ // Type of widget that was involved in triggering this event.
+ optional android.stats.textclassifier.WidgetType widget_type = 4;
+
+ // Index of this event in a session.
+ optional int32 event_index = 5;
+
+ // Entity type that is involved.
+ optional string entity_type = 6;
+
+ // Number of links detected.
+ optional int32 num_links = 7;
+
+ // The total length of all links.
+ optional int32 linked_text_length = 8;
+
+ // Length of input text.
+ optional int32 text_length = 9;
+
+ // Time spent on generating links in ms.
+ optional int64 latency_millis = 10;
+
+ // Name of source package.
+ optional string package_name = 11;
+}
+
+/**
+ * Logs when there is a conversation actions related event.
+ * See frameworks/base/core/java/android/view/textclassifier/TextClassifierEvent.java
+ * Logged from: TextClassifierEventLogger.java
+ */
+message ConversationActionsEvent {
+ // A session ID.
+ optional string session_id = 1;
+
+ // Event type of this event.
+ optional android.stats.textclassifier.EventType event_type = 2;
+
+ // Name of the model that is involved in this event.
+ optional string model_name = 3;
+
+ // Type of widget that was involved in triggering this event.
+ optional android.stats.textclassifier.WidgetType widget_type = 4;
+
+ // The first entity type that is involved.
+ optional string first_entity_type = 5;
+
+ // The second entity type that is involved.
+ optional string second_entity_type = 6;
+
+ // The third entity type that is involved.
+ optional string third_entity_type = 7;
+
+ // The score of the first entity type.
+ optional float score = 8;
+
+ // Name of source package.
+ optional string package_name = 9;
+}
+
+/**
+ * Logs when there is a language detection related event.
+ * See frameworks/base/core/java/android/view/textclassifier/TextClassifierEvent.java
+ * Logged from: TextClassifierEventLogger.java
+ */
+message LanguageDetectionEvent {
+ // A session ID.
+ optional string session_id = 1;
+
+ // Event type of this event.
+ optional android.stats.textclassifier.EventType event_type = 2;
+
+ // Name of the model that is involved in this event.
+ optional string model_name = 3;
+
+ // Type of widget that was involved in triggering this event.
+ optional android.stats.textclassifier.WidgetType widget_type = 4;
+
+ // Detected language.
+ optional string language_tag = 5;
+
+ // Score of the detected language.
+ optional float score = 6;
+
+ // Position of this action.
+ optional int32 action_index = 7;
+
+ // Name of source package.
+ optional string package_name = 8;
+}
+
+/**
+ * Information about an OTA update attempt by update_engine.
+ * Logged from platform/system/update_engine/metrics_reporter_android.cc
+ */
+message UpdateEngineUpdateAttemptReported {
+ // The number of attempts for the update engine to apply a given payload.
+ optional int32 attempt_number = 1;
+
+ optional android.stats.otaupdate.PayloadType payload_type = 2;
+
+ // The total time in minutes for the update engine to apply a given payload.
+ // The time is calculated by calling clock_gettime() / CLOCK_BOOTTIME; and
+ // it's increased when the system is sleeping.
+ optional int32 duration_boottime_in_minutes = 3;
+
+ // The total time in minutes for the update engine to apply a given payload.
+ // The time is calculated by calling clock_gettime() / CLOCK_MONOTONIC_RAW;
+ // and it's not increased when the system is sleeping.
+ optional int32 duration_monotonic_in_minutes = 4;
+
+ // The size of the payload in MiBs.
+ optional int32 payload_size_mib = 5;
+
+ // The attempt result reported by the update engine for an OTA update.
+ optional android.stats.otaupdate.AttemptResult attempt_result = 6;
+
+ // The error code reported by the update engine after an OTA update attempt
+ // on A/B devices.
+ optional android.stats.otaupdate.ErrorCode error_code = 7;
+
+ // The build fingerprint of the source system. The value is read from a
+ // system property when the device takes the update. e.g.
+ // Android/aosp_sailfish/sailfish:10/QP1A.190425.004/5507117:userdebug/test-keys
+ optional string source_fingerprint = 8;
+}
+
+/**
+ * Information about all the attempts the device make before finishing the
+ * successful update.
+ * Logged from platform/system/update_engine/metrics_reporter_android.cc
+ */
+message UpdateEngineSuccessfulUpdateReported {
+ // The number of attempts for the update engine to apply the payload for a
+ // successful update.
+ optional int32 attempt_count = 1;
+
+ optional android.stats.otaupdate.PayloadType payload_type = 2;
+
+ optional int32 payload_size_mib = 3;
+
+ // The total number of bytes downloaded by update_engine since the last
+ // successful update.
+ optional int32 total_bytes_downloaded_mib = 4;
+
+ // The ratio in percentage of the over-downloaded bytes compared to the
+ // total bytes needed to successfully install the update. e.g. 200 if we
+ // download 200MiB in total for a 100MiB package.
+ optional int32 download_overhead_percentage = 5;
+
+ // The total time in minutes for the update engine to apply the payload for a
+ // successful update.
+ optional int32 total_duration_minutes = 6;
+
+ // The number of reboot of the device during a successful update.
+ optional int32 reboot_count = 7;
+}
+
+/**
+ * Global display pipeline metrics reported by SurfaceFlinger.
+ * Pulled from:
+ * frameworks/native/services/surfaceflinger/TimeStats/TimeStats.cpp
+ */
+message SurfaceflingerStatsGlobalInfo {
+ // Total number of frames presented during the tracing period
+ optional int64 total_frames = 1;
+ // Total number of frames missed
+ optional int64 missed_frames = 2;
+ // Total number of frames that fell back to client composition
+ optional int64 client_composition_frames = 3;
+ // Total time the display was turned on
+ optional int64 display_on_millis = 4;
+ // Total time that was spent performing animations.
+ // This is derived from the present-to-present layer histogram
+ optional int64 animation_millis = 5;
+}
+
+/**
+ * Per-layer display pipeline metrics reported by SurfaceFlinger.
+ * The number of layers uploaded will be restricted due to size limitations.
+ * Pulled from:
+ * frameworks/native/services/surfaceflinger/TimeStats/TimeStats.cpp
+ */
+message SurfaceflingerStatsLayerInfo {
+ // The layer for this set of metrics
+ // For now we can infer that the package name is included in the layer
+ // name.
+ optional string layer_name = 1;
+ // Total number of frames presented
+ optional int64 total_frames = 2;
+ // Total number of dropped frames while latching a buffer for this layer.
+ optional int64 dropped_frames = 3;
+ // Set of timings measured between successive presentation timestamps.
+ optional FrameTimingHistogram present_to_present = 4
+ [(android.os.statsd.log_mode) = MODE_BYTES];
+ // Set of timings measured from when an app queued a buffer for
+ // presentation, until the buffer was actually presented to the
+ // display.
+ optional FrameTimingHistogram post_to_present = 5
+ [(android.os.statsd.log_mode) = MODE_BYTES];
+ // Set of timings measured from when a buffer is ready to be presented,
+ // until the buffer was actually presented to the display.
+ optional FrameTimingHistogram acquire_to_present = 6
+ [(android.os.statsd.log_mode) = MODE_BYTES];
+ // Set of timings measured from when a buffer was latched by
+ // SurfaceFlinger, until the buffer was presented to the display
+ optional FrameTimingHistogram latch_to_present = 7
+ [(android.os.statsd.log_mode) = MODE_BYTES];
+ // Set of timings measured from the desired presentation to the actual
+ // presentation time
+ optional FrameTimingHistogram desired_to_present = 8
+ [(android.os.statsd.log_mode) = MODE_BYTES];
+ // Set of timings measured from when an app queued a buffer for
+ // presentation, until the buffer was ready to be presented.
+ optional FrameTimingHistogram post_to_acquire = 9
+ [(android.os.statsd.log_mode) = MODE_BYTES];
+}
+
+/**
+ * Histogram of frame counts bucketed by time in milliseconds.
+ * Because of size limitations, we hard-cap the number of buckets, with
+ * buckets for corresponding to larger milliseconds being less precise.
+ */
+message FrameTimingHistogram {
+ // Timings in milliseconds that describes a set of histogram buckets
+ repeated int32 time_millis_buckets = 1;
+ // Number of frames that match to each time_millis, i.e. the bucket
+ // contents
+ // It's required that len(time_millis) == len(frame_count)
+ repeated int64 frame_counts = 2;
+}
+
+
+/**
+ * Information about camera facing and API level usage.
+ * Logged from:
+ * frameworks/base/services/core/java/com/android/server/camera/CameraServiceProxy.java
+ */
+message CameraActionEvent {
+ // Camera session duration
+ optional int64 duration = 1;
+
+ // Camera API level used
+ optional int32 api_level = 2;
+
+ // Name of client package
+ optional string package_name = 3;
+
+ // Camera facing
+ enum Facing {
+ UNKNOWN = 0;
+ BACK = 1;
+ FRONT = 2;
+ EXTERNAL = 3;
+ }
+ optional Facing facing = 4;
+}
diff --git a/cmds/statsd/src/condition/CombinationConditionTracker.cpp b/cmds/statsd/src/condition/CombinationConditionTracker.cpp
index 60a4b236df11..52a1269798ca 100644
--- a/cmds/statsd/src/condition/CombinationConditionTracker.cpp
+++ b/cmds/statsd/src/condition/CombinationConditionTracker.cpp
@@ -110,20 +110,14 @@ bool CombinationConditionTracker::init(const vector<Predicate>& allConditionConf
void CombinationConditionTracker::isConditionMet(
const ConditionKey& conditionParameters, const vector<sp<ConditionTracker>>& allConditions,
- const std::vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
const bool isPartialLink,
- vector<ConditionState>& conditionCache,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const {
+ vector<ConditionState>& conditionCache) const {
// So far, this is fine as there is at most one child having sliced output.
for (const int childIndex : mChildren) {
if (conditionCache[childIndex] == ConditionState::kNotEvaluated) {
allConditions[childIndex]->isConditionMet(conditionParameters, allConditions,
- dimensionFields,
- isSubOutputDimensionFields,
isPartialLink,
- conditionCache,
- dimensionsKeySet);
+ conditionCache);
}
}
conditionCache[mIndex] =
@@ -178,25 +172,6 @@ void CombinationConditionTracker::evaluateCondition(
}
}
-ConditionState CombinationConditionTracker::getMetConditionDimension(
- const std::vector<sp<ConditionTracker>>& allConditions,
- const std::vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const {
- vector<ConditionState> conditionCache(allConditions.size(), ConditionState::kNotEvaluated);
- // So far, this is fine as there is at most one child having sliced output.
- for (const int childIndex : mChildren) {
- conditionCache[childIndex] = conditionCache[childIndex] |
- allConditions[childIndex]->getMetConditionDimension(
- allConditions, dimensionFields, isSubOutputDimensionFields, dimensionsKeySet);
- }
- evaluateCombinationCondition(mChildren, mLogicalOperation, conditionCache);
- if (conditionCache[mIndex] == ConditionState::kTrue && dimensionsKeySet.empty()) {
- dimensionsKeySet.insert(DEFAULT_DIMENSION_KEY);
- }
- return conditionCache[mIndex];
-}
-
bool CombinationConditionTracker::equalOutputDimensions(
const std::vector<sp<ConditionTracker>>& allConditions,
const vector<Matcher>& dimensions) const {
diff --git a/cmds/statsd/src/condition/CombinationConditionTracker.h b/cmds/statsd/src/condition/CombinationConditionTracker.h
index 481cb200d8e6..e3d860127780 100644
--- a/cmds/statsd/src/condition/CombinationConditionTracker.h
+++ b/cmds/statsd/src/condition/CombinationConditionTracker.h
@@ -43,17 +43,8 @@ public:
void isConditionMet(const ConditionKey& conditionParameters,
const std::vector<sp<ConditionTracker>>& allConditions,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
const bool isPartialLink,
- std::vector<ConditionState>& conditionCache,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const override;
-
- ConditionState getMetConditionDimension(
- const std::vector<sp<ConditionTracker>>& allConditions,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const override;
+ std::vector<ConditionState>& conditionCache) const override;
// Only one child predicate can have dimension.
const std::set<HashableDimensionKey>* getChangedToTrueDimensions(
diff --git a/cmds/statsd/src/condition/ConditionTracker.h b/cmds/statsd/src/condition/ConditionTracker.h
index 1f4266b61cdf..e94ea6586f05 100644
--- a/cmds/statsd/src/condition/ConditionTracker.h
+++ b/cmds/statsd/src/condition/ConditionTracker.h
@@ -84,29 +84,14 @@ public:
// condition.
// [allConditions]: all condition trackers. This is needed because the condition evaluation is
// done recursively
- // [dimensionFields]: the needed dimension fields which should be all or subset of the condition
- // tracker output dimension.
- // [isSubOutputDimensionFields]: true if the needed dimension fields which is strictly subset of
- // the condition tracker output dimension.
// [isPartialLink]: true if the link specified by 'conditionParameters' contains all the fields
// in the condition tracker output dimension.
// [conditionCache]: the cache holding the condition evaluation values.
- // [dimensionsKeySet]: the dimensions where the sliced condition is true. For combination
- // condition, it assumes that only one child predicate is sliced.
virtual void isConditionMet(
const ConditionKey& conditionParameters,
const std::vector<sp<ConditionTracker>>& allConditions,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
const bool isPartialLink,
- std::vector<ConditionState>& conditionCache,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const = 0;
-
- virtual ConditionState getMetConditionDimension(
- const std::vector<sp<ConditionTracker>>& allConditions,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const = 0;
+ std::vector<ConditionState>& conditionCache) const = 0;
// return the list of LogMatchingTracker index that this ConditionTracker uses.
virtual const std::set<int>& getLogTrackerIndex() const {
diff --git a/cmds/statsd/src/condition/ConditionWizard.cpp b/cmds/statsd/src/condition/ConditionWizard.cpp
index 23a9d371145e..4f44a69ba980 100644
--- a/cmds/statsd/src/condition/ConditionWizard.cpp
+++ b/cmds/statsd/src/condition/ConditionWizard.cpp
@@ -25,27 +25,15 @@ using std::string;
using std::vector;
ConditionState ConditionWizard::query(const int index, const ConditionKey& parameters,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
- const bool isPartialLink,
- std::unordered_set<HashableDimensionKey>* dimensionKeySet) {
+ const bool isPartialLink) {
vector<ConditionState> cache(mAllConditions.size(), ConditionState::kNotEvaluated);
mAllConditions[index]->isConditionMet(
- parameters, mAllConditions, dimensionFields, isSubOutputDimensionFields, isPartialLink,
- cache, *dimensionKeySet);
+ parameters, mAllConditions, isPartialLink,
+ cache);
return cache[index];
}
-ConditionState ConditionWizard::getMetConditionDimension(
- const int index, const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
- std::unordered_set<HashableDimensionKey>* dimensionsKeySet) const {
- return mAllConditions[index]->getMetConditionDimension(mAllConditions, dimensionFields,
- isSubOutputDimensionFields,
- *dimensionsKeySet);
-}
-
const set<HashableDimensionKey>* ConditionWizard::getChangedToTrueDimensions(
const int index) const {
return mAllConditions[index]->getChangedToTrueDimensions(mAllConditions);
@@ -82,4 +70,4 @@ bool ConditionWizard::equalOutputDimensions(const int index, const vector<Matche
} // namespace statsd
} // namespace os
-} // namespace android \ No newline at end of file
+} // namespace android
diff --git a/cmds/statsd/src/condition/ConditionWizard.h b/cmds/statsd/src/condition/ConditionWizard.h
index 2c8814772839..892647910d9f 100644
--- a/cmds/statsd/src/condition/ConditionWizard.h
+++ b/cmds/statsd/src/condition/ConditionWizard.h
@@ -40,15 +40,7 @@ public:
// The ConditionTracker at [conditionIndex] can be a CombinationConditionTracker. In this case,
// the conditionParameters contains the parameters for it's children SimpleConditionTrackers.
virtual ConditionState query(const int conditionIndex, const ConditionKey& conditionParameters,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
- const bool isPartialLink,
- std::unordered_set<HashableDimensionKey>* dimensionKeySet);
-
- virtual ConditionState getMetConditionDimension(
- const int index, const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
- std::unordered_set<HashableDimensionKey>* dimensionsKeySet) const;
+ const bool isPartialLink);
virtual const std::set<HashableDimensionKey>* getChangedToTrueDimensions(const int index) const;
virtual const std::set<HashableDimensionKey>* getChangedToFalseDimensions(
diff --git a/cmds/statsd/src/condition/SimpleConditionTracker.cpp b/cmds/statsd/src/condition/SimpleConditionTracker.cpp
index 87104a34c009..0c92149f4c96 100644
--- a/cmds/statsd/src/condition/SimpleConditionTracker.cpp
+++ b/cmds/statsd/src/condition/SimpleConditionTracker.cpp
@@ -344,11 +344,8 @@ void SimpleConditionTracker::evaluateCondition(
void SimpleConditionTracker::isConditionMet(
const ConditionKey& conditionParameters, const vector<sp<ConditionTracker>>& allConditions,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
const bool isPartialLink,
- vector<ConditionState>& conditionCache,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const {
+ vector<ConditionState>& conditionCache) const {
if (conditionCache[mIndex] != ConditionState::kNotEvaluated) {
// it has been evaluated.
@@ -360,18 +357,13 @@ void SimpleConditionTracker::isConditionMet(
if (pair == conditionParameters.end()) {
ConditionState conditionState = ConditionState::kNotEvaluated;
- if (dimensionFields.size() > 0 && dimensionFields[0].mMatcher.getTag() == mDimensionTag) {
- conditionState = conditionState | getMetConditionDimension(
- allConditions, dimensionFields, isSubOutputDimensionFields, dimensionsKeySet);
- } else {
- conditionState = conditionState | mInitialValue;
- if (!mSliced) {
- const auto& itr = mSlicedConditionState.find(DEFAULT_DIMENSION_KEY);
- if (itr != mSlicedConditionState.end()) {
- ConditionState sliceState =
- itr->second > 0 ? ConditionState::kTrue : ConditionState::kFalse;
- conditionState = conditionState | sliceState;
- }
+ conditionState = conditionState | mInitialValue;
+ if (!mSliced) {
+ const auto& itr = mSlicedConditionState.find(DEFAULT_DIMENSION_KEY);
+ if (itr != mSlicedConditionState.end()) {
+ ConditionState sliceState =
+ itr->second > 0 ? ConditionState::kTrue : ConditionState::kFalse;
+ conditionState = conditionState | sliceState;
}
}
conditionCache[mIndex] = conditionState;
@@ -389,15 +381,6 @@ void SimpleConditionTracker::isConditionMet(
slice.second > 0 ? ConditionState::kTrue : ConditionState::kFalse;
if (slice.first.contains(key)) {
conditionState = conditionState | sliceState;
- if (sliceState == ConditionState::kTrue && dimensionFields.size() > 0) {
- if (isSubOutputDimensionFields) {
- HashableDimensionKey dimensionKey;
- filterValues(dimensionFields, slice.first.getValues(), &dimensionKey);
- dimensionsKeySet.insert(dimensionKey);
- } else {
- dimensionsKeySet.insert(slice.first);
- }
- }
}
}
} else {
@@ -407,15 +390,6 @@ void SimpleConditionTracker::isConditionMet(
ConditionState sliceState =
startedCountIt->second > 0 ? ConditionState::kTrue : ConditionState::kFalse;
conditionState = conditionState | sliceState;
- if (sliceState == ConditionState::kTrue && dimensionFields.size() > 0) {
- if (isSubOutputDimensionFields) {
- HashableDimensionKey dimensionKey;
- filterValues(dimensionFields, startedCountIt->first.getValues(), &dimensionKey);
- dimensionsKeySet.insert(dimensionKey);
- } else {
- dimensionsKeySet.insert(startedCountIt->first);
- }
- }
}
}
@@ -423,41 +397,6 @@ void SimpleConditionTracker::isConditionMet(
VLOG("Predicate %lld return %d", (long long)mConditionId, conditionCache[mIndex]);
}
-ConditionState SimpleConditionTracker::getMetConditionDimension(
- const std::vector<sp<ConditionTracker>>& allConditions,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const {
- ConditionState conditionState = mInitialValue;
- if (dimensionFields.size() == 0 || mOutputDimensions.size() == 0 ||
- dimensionFields[0].mMatcher.getTag() != mOutputDimensions[0].mMatcher.getTag()) {
- const auto& itr = mSlicedConditionState.find(DEFAULT_DIMENSION_KEY);
- if (itr != mSlicedConditionState.end()) {
- ConditionState sliceState =
- itr->second > 0 ? ConditionState::kTrue : ConditionState::kFalse;
- conditionState = conditionState | sliceState;
- }
- return conditionState;
- }
-
- for (const auto& slice : mSlicedConditionState) {
- ConditionState sliceState =
- slice.second > 0 ? ConditionState::kTrue : ConditionState::kFalse;
- conditionState = conditionState | sliceState;
-
- if (sliceState == ConditionState::kTrue && dimensionFields.size() > 0) {
- if (isSubOutputDimensionFields) {
- HashableDimensionKey dimensionKey;
- filterValues(dimensionFields, slice.first.getValues(), &dimensionKey);
- dimensionsKeySet.insert(dimensionKey);
- } else {
- dimensionsKeySet.insert(slice.first);
- }
- }
- }
- return conditionState;
-}
-
} // namespace statsd
} // namespace os
} // namespace android
diff --git a/cmds/statsd/src/condition/SimpleConditionTracker.h b/cmds/statsd/src/condition/SimpleConditionTracker.h
index 47d1eceb9022..5c5cc565f783 100644
--- a/cmds/statsd/src/condition/SimpleConditionTracker.h
+++ b/cmds/statsd/src/condition/SimpleConditionTracker.h
@@ -48,17 +48,8 @@ public:
void isConditionMet(const ConditionKey& conditionParameters,
const std::vector<sp<ConditionTracker>>& allConditions,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
const bool isPartialLink,
- std::vector<ConditionState>& conditionCache,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const override;
-
- ConditionState getMetConditionDimension(
- const std::vector<sp<ConditionTracker>>& allConditions,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const override;
+ std::vector<ConditionState>& conditionCache) const override;
virtual const std::set<HashableDimensionKey>* getChangedToTrueDimensions(
const std::vector<sp<ConditionTracker>>& allConditions) const {
diff --git a/cmds/statsd/src/condition/StateTracker.cpp b/cmds/statsd/src/condition/StateConditionTracker.cpp
index 1965ce6015ff..7f3eeddba831 100644
--- a/cmds/statsd/src/condition/StateTracker.cpp
+++ b/cmds/statsd/src/condition/StateConditionTracker.cpp
@@ -16,7 +16,7 @@
#define DEBUG false // STOPSHIP if true
#include "Log.h"
-#include "StateTracker.h"
+#include "StateConditionTracker.h"
#include "guardrail/StatsdStats.h"
namespace android {
@@ -27,7 +27,7 @@ using std::string;
using std::unordered_set;
using std::vector;
-StateTracker::StateTracker(const ConfigKey& key, const int64_t& id, const int index,
+StateConditionTracker::StateConditionTracker(const ConfigKey& key, const int64_t& id, const int index,
const SimplePredicate& simplePredicate,
const unordered_map<int64_t, int>& trackerNameIndexMap,
const vector<Matcher> primaryKeys)
@@ -69,19 +69,19 @@ StateTracker::StateTracker(const ConfigKey& key, const int64_t& id, const int in
mInitialized = true;
}
-StateTracker::~StateTracker() {
- VLOG("~StateTracker()");
+StateConditionTracker::~StateConditionTracker() {
+ VLOG("~StateConditionTracker()");
}
-bool StateTracker::init(const vector<Predicate>& allConditionConfig,
+bool StateConditionTracker::init(const vector<Predicate>& allConditionConfig,
const vector<sp<ConditionTracker>>& allConditionTrackers,
const unordered_map<int64_t, int>& conditionIdIndexMap,
vector<bool>& stack) {
return mInitialized;
}
-void StateTracker::dumpState() {
- VLOG("StateTracker %lld DUMP:", (long long)mConditionId);
+void StateConditionTracker::dumpState() {
+ VLOG("StateConditionTracker %lld DUMP:", (long long)mConditionId);
for (const auto& value : mSlicedState) {
VLOG("\t%s -> %s", value.first.toString().c_str(), value.second.toString().c_str());
}
@@ -95,7 +95,7 @@ void StateTracker::dumpState() {
}
}
-bool StateTracker::hitGuardRail(const HashableDimensionKey& newKey) {
+bool StateConditionTracker::hitGuardRail(const HashableDimensionKey& newKey) {
if (mSlicedState.find(newKey) != mSlicedState.end()) {
// if the condition is not sliced or the key is not new, we are good!
return false;
@@ -114,7 +114,7 @@ bool StateTracker::hitGuardRail(const HashableDimensionKey& newKey) {
return false;
}
-void StateTracker::evaluateCondition(const LogEvent& event,
+void StateConditionTracker::evaluateCondition(const LogEvent& event,
const vector<MatchingState>& eventMatcherValues,
const vector<sp<ConditionTracker>>& mAllConditions,
vector<ConditionState>& conditionCache,
@@ -135,7 +135,7 @@ void StateTracker::evaluateCondition(const LogEvent& event,
return;
}
- VLOG("StateTracker evaluate event %s", event.ToString().c_str());
+ VLOG("StateConditionTracker evaluate event %s", event.ToString().c_str());
// Primary key can exclusive fields must be simple fields. so there won't be more than
// one keys matched.
@@ -151,7 +151,7 @@ void StateTracker::evaluateCondition(const LogEvent& event,
}
hitGuardRail(primaryKey);
- VLOG("StateTracker: key %s state %s", primaryKey.toString().c_str(), state.toString().c_str());
+ VLOG("StateConditionTracker: key %s state %s", primaryKey.toString().c_str(), state.toString().c_str());
auto it = mSlicedState.find(primaryKey);
if (it == mSlicedState.end()) {
@@ -176,13 +176,10 @@ void StateTracker::evaluateCondition(const LogEvent& event,
return;
}
-void StateTracker::isConditionMet(
+void StateConditionTracker::isConditionMet(
const ConditionKey& conditionParameters, const vector<sp<ConditionTracker>>& allConditions,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
const bool isPartialLink,
- vector<ConditionState>& conditionCache,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const {
+ vector<ConditionState>& conditionCache) const {
if (conditionCache[mIndex] != ConditionState::kNotEvaluated) {
// it has been evaluated.
VLOG("Yes, already evaluated, %lld %d", (long long)mConditionId, conditionCache[mIndex]);
@@ -193,10 +190,6 @@ void StateTracker::isConditionMet(
if (pair == conditionParameters.end()) {
if (mSlicedState.size() > 0) {
conditionCache[mIndex] = ConditionState::kTrue;
-
- for (const auto& state : mSlicedState) {
- dimensionsKeySet.insert(state.second);
- }
} else {
conditionCache[mIndex] = ConditionState::kUnknown;
}
@@ -208,25 +201,9 @@ void StateTracker::isConditionMet(
auto it = mSlicedState.find(primaryKey);
if (it != mSlicedState.end()) {
conditionCache[mIndex] = ConditionState::kTrue;
- dimensionsKeySet.insert(it->second);
- }
-}
-
-ConditionState StateTracker::getMetConditionDimension(
- const std::vector<sp<ConditionTracker>>& allConditions,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const {
- if (mSlicedState.size() > 0) {
- for (const auto& state : mSlicedState) {
- dimensionsKeySet.insert(state.second);
- }
- return ConditionState::kTrue;
}
-
- return mInitialValue;
}
} // namespace statsd
} // namespace os
-} // namespace android \ No newline at end of file
+} // namespace android
diff --git a/cmds/statsd/src/condition/StateTracker.h b/cmds/statsd/src/condition/StateConditionTracker.h
index 2bdf98c34c32..0efe1fb3fcb2 100644
--- a/cmds/statsd/src/condition/StateTracker.h
+++ b/cmds/statsd/src/condition/StateConditionTracker.h
@@ -25,14 +25,14 @@ namespace android {
namespace os {
namespace statsd {
-class StateTracker : public virtual ConditionTracker {
+class StateConditionTracker : public virtual ConditionTracker {
public:
- StateTracker(const ConfigKey& key, const int64_t& id, const int index,
+ StateConditionTracker(const ConfigKey& key, const int64_t& id, const int index,
const SimplePredicate& simplePredicate,
const std::unordered_map<int64_t, int>& trackerNameIndexMap,
const vector<Matcher> primaryKeys);
- ~StateTracker();
+ ~StateConditionTracker();
bool init(const std::vector<Predicate>& allConditionConfig,
const std::vector<sp<ConditionTracker>>& allConditionTrackers,
@@ -46,8 +46,8 @@ public:
std::vector<bool>& changedCache) override;
/**
- * Note: dimensionFields will be ignored in StateTracker, because we demand metrics
- * must take the entire dimension fields from StateTracker. This is to make implementation
+ * Note: dimensionFields will be ignored in StateConditionTracker, because we demand metrics
+ * must take the entire dimension fields from StateConditionTracker. This is to make implementation
* simple and efficient.
*
* For example: wakelock duration by uid process states:
@@ -55,22 +55,8 @@ public:
*/
void isConditionMet(const ConditionKey& conditionParameters,
const std::vector<sp<ConditionTracker>>& allConditions,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
const bool isPartialLink,
- std::vector<ConditionState>& conditionCache,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const override;
-
- /**
- * Note: dimensionFields will be ignored in StateTracker, because we demand metrics
- * must take the entire dimension fields from StateTracker. This is to make implementation
- * simple and efficient.
- */
- ConditionState getMetConditionDimension(
- const std::vector<sp<ConditionTracker>>& allConditions,
- const vector<Matcher>& dimensionFields,
- const bool isSubOutputDimensionFields,
- std::unordered_set<HashableDimensionKey>& dimensionsKeySet) const override;
+ std::vector<ConditionState>& conditionCache) const override;
virtual const std::set<HashableDimensionKey>* getChangedToTrueDimensions(
const std::vector<sp<ConditionTracker>>& allConditions) const {
@@ -123,9 +109,9 @@ private:
// maps from [primary_key] to [primary_key, exclusive_state].
std::unordered_map<HashableDimensionKey, HashableDimensionKey> mSlicedState;
- FRIEND_TEST(StateTrackerTest, TestStateChange);
+ FRIEND_TEST(StateConditionTrackerTest, TestStateChange);
};
} // namespace statsd
} // namespace os
-} // namespace android \ No newline at end of file
+} // namespace android
diff --git a/cmds/statsd/src/external/GpuStatsPuller.cpp b/cmds/statsd/src/external/GpuStatsPuller.cpp
index 0d3aca05e0e5..bbdb5405ca05 100644
--- a/cmds/statsd/src/external/GpuStatsPuller.cpp
+++ b/cmds/statsd/src/external/GpuStatsPuller.cpp
@@ -96,6 +96,7 @@ static bool pullGpuStatsAppInfo(const sp<IGpuService>& gpuService,
if (!event->write(int64VectorToProtoByteString(info.vkDriverLoadingTime))) return false;
if (!event->write(int64VectorToProtoByteString(info.angleDriverLoadingTime))) return false;
if (!event->write(info.cpuVulkanInUse)) return false;
+ if (!event->write(info.falsePrerotation)) return false;
event->init();
data->emplace_back(event);
}
diff --git a/cmds/statsd/src/matchers/matcher_util.cpp b/cmds/statsd/src/matchers/matcher_util.cpp
index 8dc5cef988b0..10ac4a182f87 100644
--- a/cmds/statsd/src/matchers/matcher_util.cpp
+++ b/cmds/statsd/src/matchers/matcher_util.cpp
@@ -84,7 +84,7 @@ bool combinationMatch(const vector<int>& children, const LogicalOperation& opera
bool tryMatchString(const UidMap& uidMap, const Field& field, const Value& value,
const string& str_match) {
- if (isAttributionUidField(field, value)) {
+ if (isAttributionUidField(field, value) || isUidField(field, value)) {
int uid = value.int_value;
auto aidIt = UidMap::sAidToUidMapping.find(str_match);
if (aidIt != UidMap::sAidToUidMapping.end()) {
diff --git a/cmds/statsd/src/metrics/CountMetricProducer.cpp b/cmds/statsd/src/metrics/CountMetricProducer.cpp
index c023e6f77e7c..23d025f82c26 100644
--- a/cmds/statsd/src/metrics/CountMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/CountMetricProducer.cpp
@@ -48,7 +48,6 @@ const int FIELD_ID_COUNT_METRICS = 5;
const int FIELD_ID_TIME_BASE = 9;
const int FIELD_ID_BUCKET_SIZE = 10;
const int FIELD_ID_DIMENSION_PATH_IN_WHAT = 11;
-const int FIELD_ID_DIMENSION_PATH_IN_CONDITION = 12;
const int FIELD_ID_IS_ACTIVE = 14;
// for CountMetricDataWrapper
@@ -82,12 +81,7 @@ CountMetricProducer::CountMetricProducer(const ConfigKey& key, const CountMetric
mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
}
- mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what()) ||
- HasPositionALL(metric.dimensions_in_condition());
-
- if (metric.has_dimensions_in_condition()) {
- translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
- }
+ mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what());
if (metric.links().size() > 0) {
for (const auto& link : metric.links()) {
@@ -100,8 +94,6 @@ CountMetricProducer::CountMetricProducer(const ConfigKey& key, const CountMetric
mConditionSliced = true;
}
- mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
-
flushIfNeededLocked(startTimeNs);
// Adjust start for partial bucket
mCurrentBucketStartTimeNs = startTimeNs;
@@ -171,13 +163,6 @@ void CountMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
protoOutput->end(dimenPathToken);
}
- if (!mDimensionsInCondition.empty()) {
- uint64_t dimenPathToken = protoOutput->start(
- FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_CONDITION);
- writeDimensionPathToProto(mDimensionsInCondition, protoOutput);
- protoOutput->end(dimenPathToken);
- }
-
}
uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_COUNT_METRICS);
diff --git a/cmds/statsd/src/metrics/DurationMetricProducer.cpp b/cmds/statsd/src/metrics/DurationMetricProducer.cpp
index 96fbf7fb5ebe..cca793b2146a 100644
--- a/cmds/statsd/src/metrics/DurationMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/DurationMetricProducer.cpp
@@ -47,7 +47,6 @@ const int FIELD_ID_DURATION_METRICS = 6;
const int FIELD_ID_TIME_BASE = 9;
const int FIELD_ID_BUCKET_SIZE = 10;
const int FIELD_ID_DIMENSION_PATH_IN_WHAT = 11;
-const int FIELD_ID_DIMENSION_PATH_IN_CONDITION = 12;
const int FIELD_ID_IS_ACTIVE = 14;
// for DurationMetricDataWrapper
const int FIELD_ID_DATA = 1;
@@ -100,12 +99,7 @@ DurationMetricProducer::DurationMetricProducer(const ConfigKey& key, const Durat
ALOGE("Position ANY in dimension_in_what not supported.");
}
- if (metric.has_dimensions_in_condition()) {
- translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
- }
-
- mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what()) ||
- HasPositionALL(metric.dimensions_in_condition());
+ mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what());
if (metric.links().size() > 0) {
for (const auto& link : metric.links()) {
@@ -115,19 +109,16 @@ DurationMetricProducer::DurationMetricProducer(const ConfigKey& key, const Durat
translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
mMetric2ConditionLinks.push_back(mc);
}
+ mConditionSliced = true;
}
- mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
mUnSlicedPartCondition = ConditionState::kUnknown;
mUseWhatDimensionAsInternalDimension = equalDimensions(mDimensionsInWhat, mInternalDimensions);
- if (mWizard != nullptr && mConditionTrackerIndex >= 0) {
- mSameConditionDimensionsInTracker =
- mWizard->equalOutputDimensions(mConditionTrackerIndex, mDimensionsInCondition);
- if (mMetric2ConditionLinks.size() == 1) {
- mHasLinksToAllConditionDimensionsInTracker =
- mWizard->equalOutputDimensions(mConditionTrackerIndex,
- mMetric2ConditionLinks.begin()->conditionFields);
- }
+ if (mWizard != nullptr && mConditionTrackerIndex >= 0 &&
+ mMetric2ConditionLinks.size() == 1) {
+ mHasLinksToAllConditionDimensionsInTracker =
+ mWizard->equalOutputDimensions(mConditionTrackerIndex,
+ mMetric2ConditionLinks.begin()->conditionFields);
}
flushIfNeededLocked(startTimeNs);
// Adjust start for partial bucket
@@ -164,13 +155,13 @@ unique_ptr<DurationTracker> DurationMetricProducer::createDurationTracker(
case DurationMetric_AggregationType_SUM:
return make_unique<OringDurationTracker>(
mConfigKey, mMetricId, eventKey, mWizard, mConditionTrackerIndex,
- mDimensionsInCondition, mNested, mCurrentBucketStartTimeNs, mCurrentBucketNum,
+ mNested, mCurrentBucketStartTimeNs, mCurrentBucketNum,
mTimeBaseNs, mBucketSizeNs, mConditionSliced,
mHasLinksToAllConditionDimensionsInTracker, mAnomalyTrackers);
case DurationMetric_AggregationType_MAX_SPARSE:
return make_unique<MaxDurationTracker>(
mConfigKey, mMetricId, eventKey, mWizard, mConditionTrackerIndex,
- mDimensionsInCondition, mNested, mCurrentBucketStartTimeNs, mCurrentBucketNum,
+ mNested, mCurrentBucketStartTimeNs, mCurrentBucketNum,
mTimeBaseNs, mBucketSizeNs, mConditionSliced,
mHasLinksToAllConditionDimensionsInTracker, mAnomalyTrackers);
}
@@ -178,13 +169,11 @@ unique_ptr<DurationTracker> DurationMetricProducer::createDurationTracker(
// SlicedConditionChange optimization case 1:
// 1. If combination condition, logical operation is AND, only one sliced child predicate.
-// 2. No condition in dimension
-// 3. The links covers all dimension fields in the sliced child condition predicate.
+// 2. The links covers all dimension fields in the sliced child condition predicate.
void DurationMetricProducer::onSlicedConditionMayChangeLocked_opt1(bool condition,
const int64_t eventTime) {
if (mMetric2ConditionLinks.size() != 1 ||
- !mHasLinksToAllConditionDimensionsInTracker ||
- !mDimensionsInCondition.empty()) {
+ !mHasLinksToAllConditionDimensionsInTracker) {
return;
}
@@ -249,178 +238,20 @@ void DurationMetricProducer::onSlicedConditionMayChangeLocked_opt1(bool conditio
}
}
-
-// SlicedConditionChange optimization case 2:
-// 1. If combination condition, logical operation is AND, only one sliced child predicate.
-// 2. Has dimensions_in_condition and it equals to the output dimensions of the sliced predicate.
-void DurationMetricProducer::onSlicedConditionMayChangeLocked_opt2(bool condition,
- const int64_t eventTime) {
- if (mMetric2ConditionLinks.size() > 1 || !mSameConditionDimensionsInTracker) {
- return;
- }
-
- auto dimensionsChangedToTrue = mWizard->getChangedToTrueDimensions(mConditionTrackerIndex);
- auto dimensionsChangedToFalse = mWizard->getChangedToFalseDimensions(mConditionTrackerIndex);
-
- bool currentUnSlicedPartCondition = true;
- if (!mWizard->IsSimpleCondition(mConditionTrackerIndex)) {
- ConditionState unslicedPartState =
- mWizard->getUnSlicedPartConditionState(mConditionTrackerIndex);
- // When the unsliced part is still false, return directly.
- if (mUnSlicedPartCondition == ConditionState::kFalse &&
- unslicedPartState == ConditionState::kFalse) {
- return;
- }
- mUnSlicedPartCondition = unslicedPartState;
- currentUnSlicedPartCondition = mUnSlicedPartCondition > 0;
- }
-
- const std::set<HashableDimensionKey>* trueDimensionsToProcess = nullptr;
- const std::set<HashableDimensionKey>* falseDimensionsToProcess = nullptr;
-
- std::set<HashableDimensionKey> currentTrueConditionDimensions;
- if (dimensionsChangedToTrue == nullptr || dimensionsChangedToFalse == nullptr ||
- (dimensionsChangedToTrue->empty() && dimensionsChangedToFalse->empty())) {
- mWizard->getTrueSlicedDimensions(mConditionTrackerIndex, &currentTrueConditionDimensions);
- trueDimensionsToProcess = &currentTrueConditionDimensions;
- } else if (currentUnSlicedPartCondition) {
- // Handles the condition change from the sliced predicate. If the unsliced condition state
- // is not true, not need to do anything.
- trueDimensionsToProcess = dimensionsChangedToTrue;
- falseDimensionsToProcess = dimensionsChangedToFalse;
- }
-
- if (trueDimensionsToProcess == nullptr && falseDimensionsToProcess == nullptr) {
- return;
- }
-
- for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
- if (falseDimensionsToProcess != nullptr) {
- for (const auto& changedDim : *falseDimensionsToProcess) {
- auto condIt = whatIt.second.find(changedDim);
- if (condIt != whatIt.second.end()) {
- condIt->second->onConditionChanged(false, eventTime);
- }
- }
- }
- if (trueDimensionsToProcess != nullptr) {
- HashableDimensionKey linkedConditionDimensionKey;
- if (!trueDimensionsToProcess->empty() && mMetric2ConditionLinks.size() == 1) {
- getDimensionForCondition(whatIt.first.getValues(),
- mMetric2ConditionLinks[0],
- &linkedConditionDimensionKey);
- }
- for (auto& trueDim : *trueDimensionsToProcess) {
- auto condIt = whatIt.second.find(trueDim);
- if (condIt != whatIt.second.end()) {
- condIt->second->onConditionChanged(
- currentUnSlicedPartCondition, eventTime);
- } else {
- if (mMetric2ConditionLinks.size() == 0 ||
- trueDim.contains(linkedConditionDimensionKey)) {
- if (!whatIt.second.empty()) {
- auto newEventKey = MetricDimensionKey(whatIt.first, trueDim);
- if (hitGuardRailLocked(newEventKey)) {
- continue;
- }
- unique_ptr<DurationTracker> newTracker =
- whatIt.second.begin()->second->clone(eventTime);
- if (newTracker != nullptr) {
- newTracker->setEventKey(newEventKey);
- newTracker->onConditionChanged(true, eventTime);
- whatIt.second[trueDim] = std::move(newTracker);
- }
- }
- }
- }
- }
- }
- }
-}
-
void DurationMetricProducer::onSlicedConditionMayChangeInternalLocked(bool overallCondition,
const int64_t eventTimeNs) {
bool changeDimTrackable = mWizard->IsChangedDimensionTrackable(mConditionTrackerIndex);
- if (changeDimTrackable && mHasLinksToAllConditionDimensionsInTracker &&
- mDimensionsInCondition.empty()) {
+ if (changeDimTrackable && mHasLinksToAllConditionDimensionsInTracker) {
onSlicedConditionMayChangeLocked_opt1(overallCondition, eventTimeNs);
return;
}
- if (changeDimTrackable && mSameConditionDimensionsInTracker &&
- mMetric2ConditionLinks.size() <= 1) {
- onSlicedConditionMayChangeLocked_opt2(overallCondition, eventTimeNs);
- return;
- }
-
// Now for each of the on-going event, check if the condition has changed for them.
for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
for (auto& pair : whatIt.second) {
pair.second->onSlicedConditionMayChange(overallCondition, eventTimeNs);
}
}
-
- if (mDimensionsInCondition.empty()) {
- return;
- }
-
- if (mMetric2ConditionLinks.empty()) {
- std::unordered_set<HashableDimensionKey> conditionDimensionsKeySet;
- mWizard->getMetConditionDimension(mConditionTrackerIndex, mDimensionsInCondition,
- !mSameConditionDimensionsInTracker,
- &conditionDimensionsKeySet);
- for (const auto& whatIt : mCurrentSlicedDurationTrackerMap) {
- for (const auto& pair : whatIt.second) {
- conditionDimensionsKeySet.erase(pair.first);
- }
- }
- for (const auto& conditionDimension : conditionDimensionsKeySet) {
- for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
- if (!whatIt.second.empty()) {
- auto newEventKey = MetricDimensionKey(whatIt.first, conditionDimension);
- if (hitGuardRailLocked(newEventKey)) {
- continue;
- }
- unique_ptr<DurationTracker> newTracker =
- whatIt.second.begin()->second->clone(eventTimeNs);
- if (newTracker != nullptr) {
- newTracker->setEventKey(MetricDimensionKey(newEventKey));
- newTracker->onSlicedConditionMayChange(overallCondition, eventTimeNs);
- whatIt.second[conditionDimension] = std::move(newTracker);
- }
- }
- }
- }
- } else {
- for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
- ConditionKey conditionKey;
- for (const auto& link : mMetric2ConditionLinks) {
- getDimensionForCondition(whatIt.first.getValues(), link,
- &conditionKey[link.conditionId]);
- }
- std::unordered_set<HashableDimensionKey> conditionDimensionsKeys;
- mWizard->query(mConditionTrackerIndex, conditionKey, mDimensionsInCondition,
- !mSameConditionDimensionsInTracker,
- !mHasLinksToAllConditionDimensionsInTracker,
- &conditionDimensionsKeys);
-
- for (const auto& conditionDimension : conditionDimensionsKeys) {
- if (!whatIt.second.empty() &&
- whatIt.second.find(conditionDimension) == whatIt.second.end()) {
- auto newEventKey = MetricDimensionKey(whatIt.first, conditionDimension);
- if (hitGuardRailLocked(newEventKey)) {
- continue;
- }
- auto newTracker = whatIt.second.begin()->second->clone(eventTimeNs);
- if (newTracker != nullptr) {
- newTracker->setEventKey(newEventKey);
- newTracker->onSlicedConditionMayChange(overallCondition, eventTimeNs);
- whatIt.second[conditionDimension] = std::move(newTracker);
- }
- }
- }
- }
- }
}
void DurationMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
@@ -526,12 +357,6 @@ void DurationMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
protoOutput->end(dimenPathToken);
}
- if (!mDimensionsInCondition.empty()) {
- uint64_t dimenPathToken = protoOutput->start(
- FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_CONDITION);
- writeDimensionPathToProto(mDimensionsInCondition, protoOutput);
- protoOutput->end(dimenPathToken);
- }
}
uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DURATION_METRICS);
@@ -790,52 +615,24 @@ void DurationMetricProducer::onMatchedLogEventLocked(const size_t matcherIndex,
bool condition;
ConditionKey conditionKey;
- std::unordered_set<HashableDimensionKey> dimensionKeysInCondition;
if (mConditionSliced) {
for (const auto& link : mMetric2ConditionLinks) {
getDimensionForCondition(event.getValues(), link, &conditionKey[link.conditionId]);
}
auto conditionState =
- mWizard->query(mConditionTrackerIndex, conditionKey, mDimensionsInCondition,
- !mSameConditionDimensionsInTracker,
- !mHasLinksToAllConditionDimensionsInTracker,
- &dimensionKeysInCondition);
+ mWizard->query(mConditionTrackerIndex, conditionKey,
+ !mHasLinksToAllConditionDimensionsInTracker);
condition = conditionState == ConditionState::kTrue;
- if (mDimensionsInCondition.empty() && condition) {
- dimensionKeysInCondition.insert(DEFAULT_DIMENSION_KEY);
- }
} else {
// TODO: The unknown condition state is not handled here, we should fix it.
condition = mCondition == ConditionState::kTrue;
- if (condition) {
- dimensionKeysInCondition.insert(DEFAULT_DIMENSION_KEY);
- }
}
condition = condition && mIsActive;
- if (dimensionKeysInCondition.empty()) {
- handleStartEvent(MetricDimensionKey(dimensionInWhat, DEFAULT_DIMENSION_KEY),
- conditionKey, condition, event);
- } else {
- auto whatIt = mCurrentSlicedDurationTrackerMap.find(dimensionInWhat);
- // If the what dimension is already there, we should update all the trackers even
- // the condition is false.
- if (whatIt != mCurrentSlicedDurationTrackerMap.end()) {
- for (const auto& condIt : whatIt->second) {
- const bool cond = dimensionKeysInCondition.find(condIt.first) !=
- dimensionKeysInCondition.end() && condition;
- handleStartEvent(MetricDimensionKey(dimensionInWhat, condIt.first),
- conditionKey, cond, event);
- dimensionKeysInCondition.erase(condIt.first);
- }
- }
- for (const auto& conditionDimension : dimensionKeysInCondition) {
- handleStartEvent(MetricDimensionKey(dimensionInWhat, conditionDimension), conditionKey,
- condition, event);
- }
- }
+ handleStartEvent(MetricDimensionKey(dimensionInWhat, DEFAULT_DIMENSION_KEY),
+ conditionKey, condition, event);
}
size_t DurationMetricProducer::byteSizeLocked() const {
diff --git a/cmds/statsd/src/metrics/GaugeMetricProducer.cpp b/cmds/statsd/src/metrics/GaugeMetricProducer.cpp
index a64bbc1056e0..1f423cd384ef 100644
--- a/cmds/statsd/src/metrics/GaugeMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/GaugeMetricProducer.cpp
@@ -48,7 +48,6 @@ const int FIELD_ID_GAUGE_METRICS = 8;
const int FIELD_ID_TIME_BASE = 9;
const int FIELD_ID_BUCKET_SIZE = 10;
const int FIELD_ID_DIMENSION_PATH_IN_WHAT = 11;
-const int FIELD_ID_DIMENSION_PATH_IN_CONDITION = 12;
const int FIELD_ID_IS_ACTIVE = 14;
// for GaugeMetricDataWrapper
const int FIELD_ID_DATA = 1;
@@ -115,10 +114,6 @@ GaugeMetricProducer::GaugeMetricProducer(
mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
}
- if (metric.has_dimensions_in_condition()) {
- translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
- }
-
if (metric.links().size() > 0) {
for (const auto& link : metric.links()) {
Metric2Condition mc;
@@ -127,10 +122,9 @@ GaugeMetricProducer::GaugeMetricProducer(
translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
mMetric2ConditionLinks.push_back(mc);
}
+ mConditionSliced = true;
}
- mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
- mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what()) ||
- HasPositionALL(metric.dimensions_in_condition());
+ mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what());
flushIfNeededLocked(startTimeNs);
// Kicks off the puller immediately.
@@ -209,12 +203,6 @@ void GaugeMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
protoOutput->end(dimenPathToken);
}
- if (!mDimensionsInCondition.empty()) {
- uint64_t dimenPathToken = protoOutput->start(
- FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_CONDITION);
- writeDimensionPathToProto(mDimensionsInCondition, protoOutput);
- protoOutput->end(dimenPathToken);
- }
}
uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_GAUGE_METRICS);
diff --git a/cmds/statsd/src/metrics/MetricProducer.cpp b/cmds/statsd/src/metrics/MetricProducer.cpp
index 92752b29ecda..1ab4fdf6e90c 100644
--- a/cmds/statsd/src/metrics/MetricProducer.cpp
+++ b/cmds/statsd/src/metrics/MetricProducer.cpp
@@ -52,38 +52,24 @@ void MetricProducer::onMatchedLogEventLocked(const size_t matcherIndex, const Lo
bool condition;
ConditionKey conditionKey;
- std::unordered_set<HashableDimensionKey> dimensionKeysInCondition;
if (mConditionSliced) {
for (const auto& link : mMetric2ConditionLinks) {
getDimensionForCondition(event.getValues(), link, &conditionKey[link.conditionId]);
}
auto conditionState =
- mWizard->query(mConditionTrackerIndex, conditionKey, mDimensionsInCondition,
- !mSameConditionDimensionsInTracker,
- !mHasLinksToAllConditionDimensionsInTracker,
- &dimensionKeysInCondition);
+ mWizard->query(mConditionTrackerIndex, conditionKey,
+ !mHasLinksToAllConditionDimensionsInTracker);
condition = (conditionState == ConditionState::kTrue);
} else {
// TODO: The unknown condition state is not handled here, we should fix it.
condition = mCondition == ConditionState::kTrue;
}
- if (mDimensionsInCondition.empty() && condition) {
- dimensionKeysInCondition.insert(DEFAULT_DIMENSION_KEY);
- }
-
HashableDimensionKey dimensionInWhat;
filterValues(mDimensionsInWhat, event.getValues(), &dimensionInWhat);
MetricDimensionKey metricKey(dimensionInWhat, DEFAULT_DIMENSION_KEY);
- for (const auto& conditionDimensionKey : dimensionKeysInCondition) {
- metricKey.setDimensionKeyInCondition(conditionDimensionKey);
- onMatchedLogEventInternalLocked(
- matcherIndex, metricKey, conditionKey, condition, event);
- }
- if (dimensionKeysInCondition.empty()) {
- onMatchedLogEventInternalLocked(
- matcherIndex, metricKey, conditionKey, condition, event);
- }
+ onMatchedLogEventInternalLocked(
+ matcherIndex, metricKey, conditionKey, condition, event);
}
bool MetricProducer::evaluateActiveStateLocked(int64_t elapsedTimestampNs) {
diff --git a/cmds/statsd/src/metrics/MetricProducer.h b/cmds/statsd/src/metrics/MetricProducer.h
index 09ad2903fa4c..94f833b20814 100644
--- a/cmds/statsd/src/metrics/MetricProducer.h
+++ b/cmds/statsd/src/metrics/MetricProducer.h
@@ -88,7 +88,6 @@ public:
mConditionTrackerIndex(conditionIndex),
mContainANYPositionInDimensionsInWhat(false),
mSliceByPositionALL(false),
- mSameConditionDimensionsInTracker(false),
mHasLinksToAllConditionDimensionsInTracker(false),
mIsActive(true) {
}
@@ -349,15 +348,10 @@ protected:
int mConditionTrackerIndex;
vector<Matcher> mDimensionsInWhat; // The dimensions_in_what defined in statsd_config
- vector<Matcher> mDimensionsInCondition; // The dimensions_in_condition defined in statsd_config
bool mContainANYPositionInDimensionsInWhat;
bool mSliceByPositionALL;
- // True iff the condition dimensions equal to the sliced dimensions in the simple condition
- // tracker. This field is always false for combinational condition trackers.
- bool mSameConditionDimensionsInTracker;
-
// True iff the metric to condition links cover all dimension fields in the condition tracker.
// This field is always false for combinational condition trackers.
bool mHasLinksToAllConditionDimensionsInTracker;
diff --git a/cmds/statsd/src/metrics/MetricsManager.h b/cmds/statsd/src/metrics/MetricsManager.h
index 8efca1e10de5..3dad61465416 100644
--- a/cmds/statsd/src/metrics/MetricsManager.h
+++ b/cmds/statsd/src/metrics/MetricsManager.h
@@ -260,17 +260,6 @@ private:
FRIEND_TEST(ValueMetricE2eTest, TestPulledEvents);
FRIEND_TEST(ValueMetricE2eTest, TestPulledEvents_LateAlarm);
FRIEND_TEST(ValueMetricE2eTest, TestPulledEvents_WithActivation);
- FRIEND_TEST(DimensionInConditionE2eTest, TestCreateCountMetric_NoLink_OR_CombinationCondition);
- FRIEND_TEST(DimensionInConditionE2eTest, TestCreateCountMetric_Link_OR_CombinationCondition);
- FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_NoLink_OR_CombinationCondition);
- FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_Link_OR_CombinationCondition);
-
- FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_NoLink_SimpleCondition);
- FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_Link_SimpleCondition);
- FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_PartialLink_SimpleCondition);
- FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_NoLink_AND_CombinationCondition);
- FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_Link_AND_CombinationCondition);
- FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetric_PartialLink_AND_CombinationCondition);
FRIEND_TEST(AnomalyDetectionE2eTest, TestSlicedCountMetric_single_bucket);
FRIEND_TEST(AnomalyDetectionE2eTest, TestSlicedCountMetric_multiple_buckets);
diff --git a/cmds/statsd/src/metrics/ValueMetricProducer.cpp b/cmds/statsd/src/metrics/ValueMetricProducer.cpp
index 0e33a0f9f29b..bc1602497c39 100644
--- a/cmds/statsd/src/metrics/ValueMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/ValueMetricProducer.cpp
@@ -51,7 +51,6 @@ const int FIELD_ID_VALUE_METRICS = 7;
const int FIELD_ID_TIME_BASE = 9;
const int FIELD_ID_BUCKET_SIZE = 10;
const int FIELD_ID_DIMENSION_PATH_IN_WHAT = 11;
-const int FIELD_ID_DIMENSION_PATH_IN_CONDITION = 12;
const int FIELD_ID_IS_ACTIVE = 14;
// for ValueMetricDataWrapper
const int FIELD_ID_DATA = 1;
@@ -127,10 +126,6 @@ ValueMetricProducer::ValueMetricProducer(
mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
}
- if (metric.has_dimensions_in_condition()) {
- translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
- }
-
if (metric.links().size() > 0) {
for (const auto& link : metric.links()) {
Metric2Condition mc;
@@ -139,11 +134,10 @@ ValueMetricProducer::ValueMetricProducer(
translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
mMetric2ConditionLinks.push_back(mc);
}
+ mConditionSliced = true;
}
- mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
- mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what()) ||
- HasPositionALL(metric.dimensions_in_condition());
+ mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what());
int64_t numBucketsForward = calcBucketsForwardCount(startTimeNs);
mCurrentBucketNum += numBucketsForward;
@@ -243,12 +237,6 @@ void ValueMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
protoOutput->end(dimenPathToken);
}
- if (!mDimensionsInCondition.empty()) {
- uint64_t dimenPathToken =
- protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_CONDITION);
- writeDimensionPathToProto(mDimensionsInCondition, protoOutput);
- protoOutput->end(dimenPathToken);
- }
}
uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_VALUE_METRICS);
diff --git a/cmds/statsd/src/metrics/duration_helper/DurationTracker.h b/cmds/statsd/src/metrics/duration_helper/DurationTracker.h
index 081e61ed21fa..6b5c2994a0c8 100644
--- a/cmds/statsd/src/metrics/duration_helper/DurationTracker.h
+++ b/cmds/statsd/src/metrics/duration_helper/DurationTracker.h
@@ -60,7 +60,7 @@ class DurationTracker {
public:
DurationTracker(const ConfigKey& key, const int64_t& id, const MetricDimensionKey& eventKey,
sp<ConditionWizard> wizard, int conditionIndex,
- const std::vector<Matcher>& dimensionInCondition, bool nesting,
+ bool nesting,
int64_t currentBucketStartNs, int64_t currentBucketNum, int64_t startTimeNs,
int64_t bucketSizeNs, bool conditionSliced, bool fullLink,
const std::vector<sp<DurationAnomalyTracker>>& anomalyTrackers)
@@ -70,7 +70,6 @@ public:
mWizard(wizard),
mConditionTrackerIndex(conditionIndex),
mBucketSizeNs(bucketSizeNs),
- mDimensionInCondition(dimensionInCondition),
mNested(nesting),
mCurrentBucketStartTimeNs(currentBucketStartNs),
mDuration(0),
@@ -180,8 +179,6 @@ protected:
const int64_t mBucketSizeNs;
- const std::vector<Matcher>& mDimensionInCondition;
-
const bool mNested;
int64_t mCurrentBucketStartTimeNs;
@@ -196,7 +193,6 @@ protected:
const bool mConditionSliced;
- bool mSameConditionDimensionsInTracker;
bool mHasLinksToAllConditionDimensionsInTracker;
std::vector<sp<DurationAnomalyTracker>> mAnomalyTrackers;
diff --git a/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.cpp b/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.cpp
index 6868b8c24c71..df66cb0c53e5 100644
--- a/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.cpp
+++ b/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.cpp
@@ -27,18 +27,14 @@ namespace statsd {
MaxDurationTracker::MaxDurationTracker(const ConfigKey& key, const int64_t& id,
const MetricDimensionKey& eventKey,
sp<ConditionWizard> wizard, int conditionIndex,
- const vector<Matcher>& dimensionInCondition, bool nesting,
+ bool nesting,
int64_t currentBucketStartNs, int64_t currentBucketNum,
int64_t startTimeNs, int64_t bucketSizeNs,
bool conditionSliced, bool fullLink,
const vector<sp<DurationAnomalyTracker>>& anomalyTrackers)
- : DurationTracker(key, id, eventKey, wizard, conditionIndex, dimensionInCondition, nesting,
+ : DurationTracker(key, id, eventKey, wizard, conditionIndex, nesting,
currentBucketStartNs, currentBucketNum, startTimeNs, bucketSizeNs,
conditionSliced, fullLink, anomalyTrackers) {
- if (mWizard != nullptr) {
- mSameConditionDimensionsInTracker =
- mWizard->equalOutputDimensions(conditionIndex, mDimensionInCondition);
- }
}
unique_ptr<DurationTracker> MaxDurationTracker::clone(const int64_t eventTime) {
@@ -252,17 +248,11 @@ void MaxDurationTracker::onSlicedConditionMayChange(bool overallCondition,
if (pair.second.state == kStopped) {
continue;
}
- std::unordered_set<HashableDimensionKey> conditionDimensionKeySet;
ConditionState conditionState = mWizard->query(
- mConditionTrackerIndex, pair.second.conditionKeys, mDimensionInCondition,
- !mSameConditionDimensionsInTracker,
- !mHasLinksToAllConditionDimensionsInTracker,
- &conditionDimensionKeySet);
- bool conditionMet =
- (conditionState == ConditionState::kTrue) &&
- (mDimensionInCondition.size() == 0 ||
- conditionDimensionKeySet.find(mEventKey.getDimensionKeyInCondition()) !=
- conditionDimensionKeySet.end());
+ mConditionTrackerIndex, pair.second.conditionKeys,
+ !mHasLinksToAllConditionDimensionsInTracker);
+ bool conditionMet = (conditionState == ConditionState::kTrue);
+
VLOG("key: %s, condition: %d", pair.first.toString().c_str(), conditionMet);
noteConditionChanged(pair.first, conditionMet, timestamp);
}
diff --git a/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.h b/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.h
index 8e8f2cd6c582..d0371da096ea 100644
--- a/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.h
+++ b/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.h
@@ -30,7 +30,7 @@ class MaxDurationTracker : public DurationTracker {
public:
MaxDurationTracker(const ConfigKey& key, const int64_t& id, const MetricDimensionKey& eventKey,
sp<ConditionWizard> wizard, int conditionIndex,
- const std::vector<Matcher>& dimensionInCondition, bool nesting,
+ bool nesting,
int64_t currentBucketStartNs, int64_t currentBucketNum,
int64_t startTimeNs, int64_t bucketSizeNs, bool conditionSliced,
bool fullLink,
diff --git a/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.cpp b/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.cpp
index 956383a99eea..b0fd975b2328 100644
--- a/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.cpp
+++ b/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.cpp
@@ -26,20 +26,16 @@ using std::pair;
OringDurationTracker::OringDurationTracker(
const ConfigKey& key, const int64_t& id, const MetricDimensionKey& eventKey,
- sp<ConditionWizard> wizard, int conditionIndex, const vector<Matcher>& dimensionInCondition,
+ sp<ConditionWizard> wizard, int conditionIndex,
bool nesting, int64_t currentBucketStartNs, int64_t currentBucketNum,
int64_t startTimeNs, int64_t bucketSizeNs, bool conditionSliced, bool fullLink,
const vector<sp<DurationAnomalyTracker>>& anomalyTrackers)
- : DurationTracker(key, id, eventKey, wizard, conditionIndex, dimensionInCondition, nesting,
+ : DurationTracker(key, id, eventKey, wizard, conditionIndex, nesting,
currentBucketStartNs, currentBucketNum, startTimeNs, bucketSizeNs,
conditionSliced, fullLink, anomalyTrackers),
mStarted(),
mPaused() {
mLastStartTime = 0;
- if (mWizard != nullptr) {
- mSameConditionDimensionsInTracker =
- mWizard->equalOutputDimensions(conditionIndex, mDimensionInCondition);
- }
}
unique_ptr<DurationTracker> OringDurationTracker::clone(const int64_t eventTime) {
@@ -227,17 +223,10 @@ void OringDurationTracker::onSlicedConditionMayChange(bool overallCondition,
++it;
continue;
}
- std::unordered_set<HashableDimensionKey> conditionDimensionKeySet;
ConditionState conditionState =
mWizard->query(mConditionTrackerIndex, condIt->second,
- mDimensionInCondition,
- !mSameConditionDimensionsInTracker,
- !mHasLinksToAllConditionDimensionsInTracker,
- &conditionDimensionKeySet);
- if (conditionState != ConditionState::kTrue ||
- (mDimensionInCondition.size() != 0 &&
- conditionDimensionKeySet.find(mEventKey.getDimensionKeyInCondition()) ==
- conditionDimensionKeySet.end())) {
+ !mHasLinksToAllConditionDimensionsInTracker);
+ if (conditionState != ConditionState::kTrue) {
startedToPaused.push_back(*it);
it = mStarted.erase(it);
VLOG("Key %s started -> paused", key.toString().c_str());
@@ -262,17 +251,10 @@ void OringDurationTracker::onSlicedConditionMayChange(bool overallCondition,
++it;
continue;
}
- std::unordered_set<HashableDimensionKey> conditionDimensionKeySet;
ConditionState conditionState =
mWizard->query(mConditionTrackerIndex, mConditionKeyMap[key],
- mDimensionInCondition,
- !mSameConditionDimensionsInTracker,
- !mHasLinksToAllConditionDimensionsInTracker,
- &conditionDimensionKeySet);
- if (conditionState == ConditionState::kTrue &&
- (mDimensionInCondition.size() == 0 ||
- conditionDimensionKeySet.find(mEventKey.getDimensionKeyInCondition()) !=
- conditionDimensionKeySet.end())) {
+ !mHasLinksToAllConditionDimensionsInTracker);
+ if (conditionState == ConditionState::kTrue) {
pausedToStarted.push_back(*it);
it = mPaused.erase(it);
VLOG("Key %s paused -> started", key.toString().c_str());
diff --git a/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.h b/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.h
index 8e73256d4a01..43c48d5f536b 100644
--- a/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.h
+++ b/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.h
@@ -29,7 +29,7 @@ class OringDurationTracker : public DurationTracker {
public:
OringDurationTracker(const ConfigKey& key, const int64_t& id,
const MetricDimensionKey& eventKey, sp<ConditionWizard> wizard,
- int conditionIndex, const std::vector<Matcher>& dimensionInCondition,
+ int conditionIndex,
bool nesting, int64_t currentBucketStartNs, int64_t currentBucketNum,
int64_t startTimeNs, int64_t bucketSizeNs, bool conditionSliced,
bool fullLink,
diff --git a/cmds/statsd/src/metrics/metrics_manager_util.cpp b/cmds/statsd/src/metrics/metrics_manager_util.cpp
index dd32c08faba3..40484f4fb86b 100644
--- a/cmds/statsd/src/metrics/metrics_manager_util.cpp
+++ b/cmds/statsd/src/metrics/metrics_manager_util.cpp
@@ -21,7 +21,7 @@
#include "../condition/CombinationConditionTracker.h"
#include "../condition/SimpleConditionTracker.h"
-#include "../condition/StateTracker.h"
+#include "../condition/StateConditionTracker.h"
#include "../external/StatsPullerManager.h"
#include "../matchers/CombinationLogMatchingTracker.h"
#include "../matchers/SimpleLogMatchingTracker.h"
@@ -35,6 +35,8 @@
#include "stats_util.h"
#include "statslog.h"
+#include <inttypes.h>
+
using std::set;
using std::string;
using std::unordered_map;
@@ -182,13 +184,13 @@ bool initLogTrackers(const StatsdConfig& config, const UidMap& uidMap,
}
/**
- * A StateTracker is built from a SimplePredicate which has only "start", and no "stop"
+ * A StateConditionTracker is built from a SimplePredicate which has only "start", and no "stop"
* or "stop_all". The start must be an atom matcher that matches a state atom. It must
* have dimension, the dimension must be the state atom's primary fields plus exclusive state
- * field. For example, the StateTracker is used in tracking UidProcessState and ScreenState.
+ * field. For example, the StateConditionTracker is used in tracking UidProcessState and ScreenState.
*
*/
-bool isStateTracker(const SimplePredicate& simplePredicate, vector<Matcher>* primaryKeys) {
+bool isStateConditionTracker(const SimplePredicate& simplePredicate, vector<Matcher>* primaryKeys) {
// 1. must not have "stop". must have "dimension"
if (!simplePredicate.has_stop() && simplePredicate.has_dimensions()) {
auto it = android::util::AtomsInfo::kStateAtomsFieldOptions.find(
@@ -240,8 +242,8 @@ bool initConditions(const ConfigKey& key, const StatsdConfig& config,
switch (condition.contents_case()) {
case Predicate::ContentsCase::kSimplePredicate: {
vector<Matcher> primaryKeys;
- if (isStateTracker(condition.simple_predicate(), &primaryKeys)) {
- allConditionTrackers.push_back(new StateTracker(key, condition.id(), index,
+ if (isStateConditionTracker(condition.simple_predicate(), &primaryKeys)) {
+ allConditionTrackers.push_back(new StateConditionTracker(key, condition.id(), index,
condition.simple_predicate(),
logTrackerMap, primaryKeys));
} else {
@@ -593,7 +595,7 @@ bool initMetrics(const ConfigKey& key, const StatsdConfig& config, const int64_t
for (int i = 0; i < config.no_report_metric_size(); ++i) {
const auto no_report_metric = config.no_report_metric(i);
if (metricMap.find(no_report_metric) == metricMap.end()) {
- ALOGW("no_report_metric %lld not exist", no_report_metric);
+ ALOGW("no_report_metric %" PRId64 " not exist", no_report_metric);
return false;
}
noReportMetricIds.insert(no_report_metric);
diff --git a/cmds/statsd/src/metrics/metrics_manager_util.h b/cmds/statsd/src/metrics/metrics_manager_util.h
index 028231ff908c..3704969039c4 100644
--- a/cmds/statsd/src/metrics/metrics_manager_util.h
+++ b/cmds/statsd/src/metrics/metrics_manager_util.h
@@ -113,7 +113,7 @@ bool initStatsdConfig(const ConfigKey& key, const StatsdConfig& config, UidMap&
vector<int>& metricsWithActivation,
std::set<int64_t>& noReportMetricIds);
-bool isStateTracker(const SimplePredicate& simplePredicate, std::vector<Matcher>* primaryKeys);
+bool isStateConditionTracker(const SimplePredicate& simplePredicate, std::vector<Matcher>* primaryKeys);
} // namespace statsd
} // namespace os
diff --git a/cmds/statsd/src/stats_log.proto b/cmds/statsd/src/stats_log.proto
index b87547056ad3..d9c04f248af0 100644
--- a/cmds/statsd/src/stats_log.proto
+++ b/cmds/statsd/src/stats_log.proto
@@ -66,13 +66,13 @@ message CountBucketInfo {
message CountMetricData {
optional DimensionsValue dimensions_in_what = 1;
- optional DimensionsValue dimensions_in_condition = 2;
+ optional DimensionsValue dimensions_in_condition = 2 [deprecated = true];
repeated CountBucketInfo bucket_info = 3;
repeated DimensionsValue dimension_leaf_values_in_what = 4;
- repeated DimensionsValue dimension_leaf_values_in_condition = 5;
+ repeated DimensionsValue dimension_leaf_values_in_condition = 5 [deprecated = true];
}
message DurationBucketInfo {
@@ -92,13 +92,13 @@ message DurationBucketInfo {
message DurationMetricData {
optional DimensionsValue dimensions_in_what = 1;
- optional DimensionsValue dimensions_in_condition = 2;
+ optional DimensionsValue dimensions_in_condition = 2 [deprecated = true];
repeated DurationBucketInfo bucket_info = 3;
repeated DimensionsValue dimension_leaf_values_in_what = 4;
- repeated DimensionsValue dimension_leaf_values_in_condition = 5;
+ repeated DimensionsValue dimension_leaf_values_in_condition = 5 [deprecated = true];
}
message ValueBucketInfo {
@@ -136,13 +136,13 @@ message ValueBucketInfo {
message ValueMetricData {
optional DimensionsValue dimensions_in_what = 1;
- optional DimensionsValue dimensions_in_condition = 2;
+ optional DimensionsValue dimensions_in_condition = 2 [deprecated = true];
repeated ValueBucketInfo bucket_info = 3;
repeated DimensionsValue dimension_leaf_values_in_what = 4;
- repeated DimensionsValue dimension_leaf_values_in_condition = 5;
+ repeated DimensionsValue dimension_leaf_values_in_condition = 5 [deprecated = true];
}
message GaugeBucketInfo {
@@ -166,13 +166,13 @@ message GaugeBucketInfo {
message GaugeMetricData {
optional DimensionsValue dimensions_in_what = 1;
- optional DimensionsValue dimensions_in_condition = 2;
+ optional DimensionsValue dimensions_in_condition = 2 [deprecated = true];
repeated GaugeBucketInfo bucket_info = 3;
repeated DimensionsValue dimension_leaf_values_in_what = 4;
- repeated DimensionsValue dimension_leaf_values_in_condition = 5;
+ repeated DimensionsValue dimension_leaf_values_in_condition = 5 [deprecated = true];
}
message StatsLogReport {
@@ -220,7 +220,7 @@ message StatsLogReport {
optional DimensionsValue dimensions_path_in_what = 11;
- optional DimensionsValue dimensions_path_in_condition = 12;
+ optional DimensionsValue dimensions_path_in_condition = 12 [deprecated = true];
// DO NOT USE field 13.
@@ -363,7 +363,7 @@ message StatsdStatsReport {
repeated ConditionStats condition_stats = 14;
repeated MetricStats metric_stats = 15;
repeated AlertStats alert_stats = 16;
- repeated MetricStats metric_dimension_in_condition_stats = 17;
+ repeated MetricStats metric_dimension_in_condition_stats = 17 [deprecated = true];
message Annotation {
optional int64 field_int64 = 1;
optional int32 field_int32 = 2;
@@ -483,7 +483,7 @@ message AlertTriggerDetails {
message MetricValue {
optional int64 metric_id = 1;
optional DimensionsValue dimension_in_what = 2;
- optional DimensionsValue dimension_in_condition = 3;
+ optional DimensionsValue dimension_in_condition = 3 [deprecated = true];
optional int64 value = 4;
}
oneof value {
diff --git a/cmds/statsd/src/statsd_config.proto b/cmds/statsd/src/statsd_config.proto
index 79c06b98a82d..1b7f39806608 100644
--- a/cmds/statsd/src/statsd_config.proto
+++ b/cmds/statsd/src/statsd_config.proto
@@ -182,7 +182,7 @@ message CountMetric {
optional FieldMatcher dimensions_in_what = 4;
- optional FieldMatcher dimensions_in_condition = 7;
+ optional FieldMatcher dimensions_in_condition = 7 [deprecated = true];
optional TimeUnit bucket = 5;
@@ -207,7 +207,7 @@ message DurationMetric {
optional FieldMatcher dimensions_in_what = 6;
- optional FieldMatcher dimensions_in_condition = 8;
+ optional FieldMatcher dimensions_in_condition = 8 [deprecated = true];
optional TimeUnit bucket = 7;
}
@@ -225,7 +225,7 @@ message GaugeMetric {
optional FieldMatcher dimensions_in_what = 5;
- optional FieldMatcher dimensions_in_condition = 8;
+ optional FieldMatcher dimensions_in_condition = 8 [deprecated = true];
optional TimeUnit bucket = 6;
@@ -259,7 +259,7 @@ message ValueMetric {
optional FieldMatcher dimensions_in_what = 5;
- optional FieldMatcher dimensions_in_condition = 9;
+ optional FieldMatcher dimensions_in_condition = 9 [deprecated = true];
optional TimeUnit bucket = 6;
diff --git a/cmds/statsd/tests/LogEntryMatcher_test.cpp b/cmds/statsd/tests/LogEntryMatcher_test.cpp
index 2b9528f7d1de..70f0f6f75a59 100644
--- a/cmds/statsd/tests/LogEntryMatcher_test.cpp
+++ b/cmds/statsd/tests/LogEntryMatcher_test.cpp
@@ -29,6 +29,7 @@ using std::unordered_map;
using std::vector;
const int32_t TAG_ID = 123;
+const int32_t TAG_ID_2 = 28; // hardcoded tag of atom with uid field
const int FIELD_ID_1 = 1;
const int FIELD_ID_2 = 2;
const int FIELD_ID_3 = 2;
@@ -297,6 +298,45 @@ TEST(AtomMatcherTest, TestAttributionMatcher) {
EXPECT_FALSE(matchesSimple(uidMap, *simpleMatcher, event));
}
+TEST(AtomMatcherTest, TestUidFieldMatcher) {
+ UidMap uidMap;
+ uidMap.updateMap(
+ 1, {1111, 1111, 2222, 3333, 3333} /* uid list */, {1, 1, 2, 1, 2} /* version list */,
+ {android::String16("v1"), android::String16("v1"), android::String16("v2"),
+ android::String16("v1"), android::String16("v2")},
+ {android::String16("pkg0"), android::String16("pkg1"), android::String16("pkg1"),
+ android::String16("Pkg2"), android::String16("PkG3")} /* package name list */,
+ {android::String16(""), android::String16(""), android::String16(""),
+ android::String16(""), android::String16("")});
+
+ // Set up matcher
+ AtomMatcher matcher;
+ auto simpleMatcher = matcher.mutable_simple_atom_matcher();
+ simpleMatcher->set_atom_id(TAG_ID);
+ simpleMatcher->add_field_value_matcher()->set_field(1);
+ simpleMatcher->mutable_field_value_matcher(0)->set_eq_string("pkg0");
+
+ // Set up the event
+ LogEvent event(TAG_ID, 0);
+ event.write(1111);
+ event.init();
+
+ LogEvent event2(TAG_ID_2, 0);
+ event2.write(1111);
+ event2.write("some value");
+ event2.init();
+
+ // Tag not in kAtomsWithUidField
+ EXPECT_FALSE(matchesSimple(uidMap, *simpleMatcher, event));
+
+ // Tag found in kAtomsWithUidField and has matching uid
+ EXPECT_TRUE(matchesSimple(uidMap, *simpleMatcher, event2));
+
+ // Tag found in kAtomsWithUidField but has non-matching uid
+ simpleMatcher->mutable_field_value_matcher(0)->set_eq_string("Pkg2");
+ EXPECT_FALSE(matchesSimple(uidMap, *simpleMatcher, event2));
+}
+
TEST(AtomMatcherTest, TestNeqAnyStringMatcher) {
UidMap uidMap;
uidMap.updateMap(
diff --git a/cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp b/cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp
index e826a52c2f33..6eaa2311e5ed 100644
--- a/cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp
+++ b/cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp
@@ -268,8 +268,6 @@ TEST(SimpleConditionTrackerTest, TestSlicedCondition) {
std::vector<sp<ConditionTracker>> allConditions;
for (Position position :
{ Position::FIRST, Position::LAST}) {
- vector<Matcher> dimensionInCondition;
- std::unordered_set<HashableDimensionKey> dimensionKeys;
SimplePredicate simplePredicate = getWakeLockHeldCondition(
true /*nesting*/, true /*default to false*/, true /*output slice by uid*/,
@@ -321,9 +319,9 @@ TEST(SimpleConditionTrackerTest, TestSlicedCondition) {
const auto queryKey = getWakeLockQueryKey(position, uids, conditionName);
conditionCache[0] = ConditionState::kNotEvaluated;
- conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
- false, false,
- conditionCache, dimensionKeys);
+ conditionTracker.isConditionMet(queryKey, allPredicates,
+ false,
+ conditionCache);
EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
// another wake lock acquired by this uid
@@ -389,9 +387,9 @@ TEST(SimpleConditionTrackerTest, TestSlicedCondition) {
// query again
conditionCache[0] = ConditionState::kNotEvaluated;
- conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
- false, false,
- conditionCache, dimensionKeys);
+ conditionTracker.isConditionMet(queryKey, allPredicates,
+ false,
+ conditionCache);
EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
}
@@ -399,8 +397,6 @@ TEST(SimpleConditionTrackerTest, TestSlicedCondition) {
TEST(SimpleConditionTrackerTest, TestSlicedWithNoOutputDim) {
std::vector<sp<ConditionTracker>> allConditions;
- vector<Matcher> dimensionInCondition;
- std::unordered_set<HashableDimensionKey> dimensionKeys;
SimplePredicate simplePredicate = getWakeLockHeldCondition(
true /*nesting*/, true /*default to false*/, false /*slice output by uid*/,
@@ -445,9 +441,9 @@ TEST(SimpleConditionTrackerTest, TestSlicedWithNoOutputDim) {
ConditionKey queryKey;
conditionCache[0] = ConditionState::kNotEvaluated;
- conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
- true, true,
- conditionCache, dimensionKeys);
+ conditionTracker.isConditionMet(queryKey, allPredicates,
+ true,
+ conditionCache);
EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
// another wake lock acquired by this uid
@@ -489,10 +485,9 @@ TEST(SimpleConditionTrackerTest, TestSlicedWithNoOutputDim) {
// query again
conditionCache[0] = ConditionState::kNotEvaluated;
- dimensionKeys.clear();
- conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
- true, true,
- conditionCache, dimensionKeys);
+ conditionTracker.isConditionMet(queryKey, allPredicates,
+ true,
+ conditionCache);
EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
}
@@ -500,8 +495,6 @@ TEST(SimpleConditionTrackerTest, TestStopAll) {
std::vector<sp<ConditionTracker>> allConditions;
for (Position position :
{ Position::FIRST, Position::LAST }) {
- vector<Matcher> dimensionInCondition;
- std::unordered_set<HashableDimensionKey> dimensionKeys;
SimplePredicate simplePredicate = getWakeLockHeldCondition(
true /*nesting*/, true /*default to false*/, true /*output slice by uid*/,
position);
@@ -555,9 +548,9 @@ TEST(SimpleConditionTrackerTest, TestStopAll) {
const auto queryKey = getWakeLockQueryKey(position, uid_list1, conditionName);
conditionCache[0] = ConditionState::kNotEvaluated;
- conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
- false, false,
- conditionCache, dimensionKeys);
+ conditionTracker.isConditionMet(queryKey, allPredicates,
+ false,
+ conditionCache);
EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
// another wake lock acquired by uid2
@@ -594,9 +587,9 @@ TEST(SimpleConditionTrackerTest, TestStopAll) {
// TEST QUERY
const auto queryKey2 = getWakeLockQueryKey(position, uid_list2, conditionName);
conditionCache[0] = ConditionState::kNotEvaluated;
- conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
- false, false,
- conditionCache, dimensionKeys);
+ conditionTracker.isConditionMet(queryKey, allPredicates,
+ false,
+ conditionCache);
EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
@@ -628,17 +621,17 @@ TEST(SimpleConditionTrackerTest, TestStopAll) {
// TEST QUERY
const auto queryKey3 = getWakeLockQueryKey(position, uid_list1, conditionName);
conditionCache[0] = ConditionState::kNotEvaluated;
- conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
- false, false,
- conditionCache, dimensionKeys);
+ conditionTracker.isConditionMet(queryKey, allPredicates,
+ false,
+ conditionCache);
EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
// TEST QUERY
const auto queryKey4 = getWakeLockQueryKey(position, uid_list2, conditionName);
conditionCache[0] = ConditionState::kNotEvaluated;
- conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
- false, false,
- conditionCache, dimensionKeys);
+ conditionTracker.isConditionMet(queryKey, allPredicates,
+ false,
+ conditionCache);
EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
}
}
diff --git a/cmds/statsd/tests/condition/StateTracker_test.cpp b/cmds/statsd/tests/condition/StateConditionTracker_test.cpp
index 9a66254afce0..fbf6efdcf966 100644
--- a/cmds/statsd/tests/condition/StateTracker_test.cpp
+++ b/cmds/statsd/tests/condition/StateConditionTracker_test.cpp
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-#include "src/condition/StateTracker.h"
+#include "src/condition/StateConditionTracker.h"
#include "tests/statsd_test_util.h"
#include <gmock/gmock.h>
@@ -50,7 +50,7 @@ void makeUidProcStateEvent(int32_t uid, int32_t state, LogEvent* event) {
event->init();
}
-TEST(StateTrackerTest, TestStateChange) {
+TEST(StateConditionTrackerTest, TestStateChange) {
int uid1 = 111;
int uid2 = 222;
@@ -60,7 +60,7 @@ TEST(StateTrackerTest, TestStateChange) {
trackerNameIndexMap[StringToId("UidProcState")] = 0;
vector<Matcher> primaryFields;
primaryFields.push_back(getSimpleMatcher(kUidProcTag, 1));
- StateTracker tracker(ConfigKey(12, 123), 123, 0, getUidProcStatePredicate(),
+ StateConditionTracker tracker(ConfigKey(12, 123), 123, 0, getUidProcStatePredicate(),
trackerNameIndexMap, primaryFields);
LogEvent event(kUidProcTag, 0 /*timestamp*/);
diff --git a/cmds/statsd/tests/e2e/DimensionInCondition_e2e_combination_AND_cond_test.cpp b/cmds/statsd/tests/e2e/DimensionInCondition_e2e_combination_AND_cond_test.cpp
deleted file mode 100644
index e4186b7200a0..000000000000
--- a/cmds/statsd/tests/e2e/DimensionInCondition_e2e_combination_AND_cond_test.cpp
+++ /dev/null
@@ -1,961 +0,0 @@
-// Copyright (C) 2017 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include <gtest/gtest.h>
-
-#include "src/StatsLogProcessor.h"
-#include "src/stats_log_util.h"
-#include "tests/statsd_test_util.h"
-
-#include <vector>
-
-namespace android {
-namespace os {
-namespace statsd {
-
-#ifdef __ANDROID__
-
-namespace {
-
-StatsdConfig CreateDurationMetricConfig_NoLink_AND_CombinationCondition(
- DurationMetric::AggregationType aggregationType, bool addExtraDimensionInCondition,
- bool hashStringInReport) {
- StatsdConfig config;
- config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
- *config.add_atom_matcher() = CreateStartScheduledJobAtomMatcher();
- *config.add_atom_matcher() = CreateFinishScheduledJobAtomMatcher();
- *config.add_atom_matcher() = CreateSyncStartAtomMatcher();
- *config.add_atom_matcher() = CreateSyncEndAtomMatcher();
- *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
- *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
-
- auto scheduledJobPredicate = CreateScheduledJobPredicate();
- auto dimensions = scheduledJobPredicate.mutable_simple_predicate()->mutable_dimensions();
- dimensions->set_field(android::util::SCHEDULED_JOB_STATE_CHANGED);
- dimensions->add_child()->set_field(2); // job name field.
-
- auto screenIsOffPredicate = CreateScreenIsOffPredicate();
-
- auto isSyncingPredicate = CreateIsSyncingPredicate();
- auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
- *syncDimension = CreateAttributionUidAndTagDimensions(android::util::SYNC_STATE_CHANGED,
- {Position::FIRST});
- if (addExtraDimensionInCondition) {
- syncDimension->add_child()->set_field(2 /* name field*/);
- }
-
- config.set_hash_strings_in_metric_report(hashStringInReport);
- *config.add_predicate() = scheduledJobPredicate;
- *config.add_predicate() = screenIsOffPredicate;
- *config.add_predicate() = isSyncingPredicate;
- auto combinationPredicate = config.add_predicate();
- combinationPredicate->set_id(StringToId("CombinationPredicate"));
- combinationPredicate->mutable_combination()->set_operation(LogicalOperation::AND);
- addPredicateToPredicateCombination(screenIsOffPredicate, combinationPredicate);
- addPredicateToPredicateCombination(isSyncingPredicate, combinationPredicate);
-
- auto metric = config.add_duration_metric();
- metric->set_bucket(FIVE_MINUTES);
- metric->set_id(StringToId("scheduledJob"));
- metric->set_what(scheduledJobPredicate.id());
- metric->set_condition(combinationPredicate->id());
- metric->set_aggregation_type(aggregationType);
- auto dimensionWhat = metric->mutable_dimensions_in_what();
- dimensionWhat->set_field(android::util::SCHEDULED_JOB_STATE_CHANGED);
- dimensionWhat->add_child()->set_field(2); // job name field.
- *metric->mutable_dimensions_in_condition() = CreateAttributionUidAndTagDimensions(
- android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- return config;
-}
-
-} // namespace
-
-/*
- The following test has the following input.
-
-{ 10000000002 10000000002 (8)9999[I], [S], job0[S], 1[I], }
-{ 10000000010 10000000010 (7)111[I], App1[S], 222[I], GMSCoreModule1[S], 222[I], GMSCoreModule2[S], ReadEmail[S], 1[I], }
-{ 10000000011 10000000011 (29)1[I], }
-{ 10000000040 10000000040 (29)2[I], }
-{ 10000000050 10000000050 (7)111[I], App1[S], 222[I], GMSCoreModule1[S], 222[I], GMSCoreModule2[S], ReadEmail[S], 0[I], }
-{ 10000000101 10000000101 (8)9999[I], [S], job0[S], 0[I], }
-{ 10000000102 10000000102 (29)1[I], }
-{ 10000000200 10000000200 (7)111[I], App1[S], 222[I], GMSCoreModule1[S], 222[I], GMSCoreModule2[S], ReadEmail[S], 1[I], }
-{ 10000000201 10000000201 (8)9999[I], [S], job2[S], 1[I], }
-{ 10000000400 10000000400 (7)111[I], App1[S], 222[I], GMSCoreModule1[S], 222[I], GMSCoreModule2[S], ReadDoc[S], 1[I], }
-{ 10000000401 10000000401 (7)333[I], App2[S], 222[I], GMSCoreModule1[S], 555[I], GMSCoreModule2[S], ReadEmail[S], 1[I], }
-{ 10000000450 10000000450 (29)2[I], }
-{ 10000000500 10000000500 (8)9999[I], [S], job2[S], 0[I], }
-{ 10000000600 10000000600 (8)8888[I], [S], job2[S], 1[I], }
-{ 10000000650 10000000650 (29)1[I], }
-{ 309999999999 309999999999 (7)111[I], App1[S], 222[I], GMSCoreModule1[S], 222[I], GMSCoreModule2[S], ReadDoc[S], 0[I], }
-{ 310000000100 310000000100 (29)2[I], }
-{ 310000000300 310000000300 (7)111[I], App1[S], 222[I], GMSCoreModule1[S], 222[I], GMSCoreModule2[S], ReadEmail[S], 0[I], }
-{ 310000000600 310000000600 (8)8888[I], [S], job1[S], 1[I], }
-{ 310000000640 310000000640 (29)1[I], }
-{ 310000000650 310000000650 (29)2[I], }
-{ 310000000700 310000000700 (7)333[I], App2[S], 222[I], GMSCoreModule1[S], 555[I], GMSCoreModule2[S], ReadEmail[S], 0[I], }
-{ 310000000850 310000000850 (8)8888[I], [S], job2[S], 0[I], }
-{ 310000000900 310000000900 (8)8888[I], [S], job1[S], 0[I], }
-*/
-TEST(DimensionInConditionE2eTest, TestDurationMetric_NoLink_AND_CombinationCondition) {
- for (const bool hashStringInReport : { true, false }) {
- for (bool isDimensionInConditionSubSetOfConditionTrackerDimension : { true, false }) {
- for (auto aggregationType : {DurationMetric::MAX_SPARSE, DurationMetric::SUM}) {
- ConfigKey cfgKey;
- auto config = CreateDurationMetricConfig_NoLink_AND_CombinationCondition(
- aggregationType, isDimensionInConditionSubSetOfConditionTrackerDimension,
- hashStringInReport);
- int64_t bucketStartTimeNs = 10000000000;
- int64_t bucketSizeNs =
- TimeUnitToBucketSizeInMillis(
- config.duration_metric(0).bucket()) * 1000000LL;
-
- auto processor = CreateStatsLogProcessor(
- bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
- EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
- EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-
- std::vector<AttributionNodeInternal> attributions1 = {
- CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(222, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions2 = {
- CreateAttribution(333, "App2"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<std::unique_ptr<LogEvent>> events;
-
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 11));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + 40));
-
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 102));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + 450));
-
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 650));
- events.push_back(CreateScreenStateChangedEvent(
- android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + bucketSizeNs + 100));
-
- events.push_back(CreateScreenStateChangedEvent(
- android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + bucketSizeNs + 640));
- events.push_back(CreateScreenStateChangedEvent(
- android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + bucketSizeNs + 650));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(9999, "")}, "job0", bucketStartTimeNs + 2));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(9999, "")}, "job0",bucketStartTimeNs + 101));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(9999, "")}, "job2", bucketStartTimeNs + 201));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(9999, "")}, "job2",bucketStartTimeNs + 500));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(8888, "")}, "job2", bucketStartTimeNs + 600));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(8888, "")}, "job2",
- bucketStartTimeNs + bucketSizeNs + 850));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(8888, "")}, "job1",
- bucketStartTimeNs + bucketSizeNs + 600));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(8888, "")}, "job1",
- bucketStartTimeNs + bucketSizeNs + 900));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 10));
- events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 50));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 200));
- events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + bucketSizeNs + 300));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadDoc",
- bucketStartTimeNs + 400));
- events.push_back(CreateSyncEndEvent(attributions1, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs - 1));
-
- events.push_back(CreateSyncStartEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + 401));
- events.push_back(CreateSyncEndEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + bucketSizeNs + 700));
-
- sortLogEventsByTimestamp(&events);
-
- for (const auto& event : events) {
- processor->OnLogEvent(event.get());
- }
-
- ConfigMetricsReportList reports;
- vector<uint8_t> buffer;
- processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false,
- true, ADB_DUMP, FAST, &buffer);
- EXPECT_TRUE(buffer.size() > 0);
- EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
- backfillDimensionPath(&reports);
- backfillStringInReport(&reports);
- backfillStartEndTimestamp(&reports);
-
- EXPECT_EQ(reports.reports_size(), 1);
- EXPECT_EQ(reports.reports(0).metrics_size(), 1);
- StatsLogReport::DurationMetricDataWrapper metrics;
- sortMetricDataByDimensionsValue(
- reports.reports(0).metrics(0).duration_metrics(), &metrics);
- if (aggregationType == DurationMetric::SUM) {
- EXPECT_EQ(metrics.data_size(), 4);
- auto data = metrics.data(0);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().
- dimensions_value(0).value_str(),
- "job0"); // job name
- ValidateAttributionUidAndTagDimension(
- data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 111, "App1");
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 40 - 11);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
-
-
- data = metrics.data(1);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().
- dimensions_value(0).value_str(),
- "job1"); // job name
- ValidateAttributionUidAndTagDimension(
- data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 333, "App2");
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 10);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(2);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().
- dimensions_value(0).value_str(),
- "job2"); // job name
- ValidateAttributionUidAndTagDimension(
- data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 111, "App1");
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 450 - 201 + bucketSizeNs - 650);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 100);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(3);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().
- dimensions_value(0).value_str(),
- "job2"); // job name
- ValidateAttributionUidAndTagDimension(
- data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 333, "App2");
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 450 - 401 + bucketSizeNs - 650);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 100 + 650 - 640);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- } else {
- EXPECT_EQ(metrics.data_size(), 4);
- auto data = metrics.data(0);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().
- dimensions_value(0).value_str(),
- "job0"); // job name
- ValidateAttributionUidAndTagDimension(
- data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 111, "App1");
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 40 - 11);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
-
- data = metrics.data(1);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().
- dimensions_value(0).value_str(),
- "job1"); // job name
- ValidateAttributionUidAndTagDimension(
- data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 333, "App2");
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 10);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(2);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str(),
- "job2"); // job name
- ValidateAttributionUidAndTagDimension(
- data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 111, "App1");
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 450 - 201);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), bucketSizeNs - 650 + 100);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(3);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().
- dimensions_value(0).value_str(),
- "job2"); // job name
- ValidateAttributionUidAndTagDimension(
- data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 333, "App2");
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 450 - 401);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), bucketSizeNs - 650 + 110);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- }
- }
- }
- }
-}
-
-namespace {
-
-StatsdConfig CreateDurationMetricConfig_Link_AND_CombinationCondition(
- DurationMetric::AggregationType aggregationType, bool addExtraDimensionInCondition) {
- StatsdConfig config;
- config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
- *config.add_atom_matcher() = CreateStartScheduledJobAtomMatcher();
- *config.add_atom_matcher() = CreateFinishScheduledJobAtomMatcher();
- *config.add_atom_matcher() = CreateSyncStartAtomMatcher();
- *config.add_atom_matcher() = CreateSyncEndAtomMatcher();
- *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
- *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
-
- auto scheduledJobPredicate = CreateScheduledJobPredicate();
- auto dimensions = scheduledJobPredicate.mutable_simple_predicate()->mutable_dimensions();
- *dimensions = CreateAttributionUidDimensions(
- android::util::SCHEDULED_JOB_STATE_CHANGED, {Position::FIRST});
- dimensions->add_child()->set_field(2); // job name field.
-
- auto isSyncingPredicate = CreateIsSyncingPredicate();
- auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
- *syncDimension = CreateAttributionUidDimensions(
- android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- if (addExtraDimensionInCondition) {
- syncDimension->add_child()->set_field(2 /* name field*/);
- }
-
- auto screenIsOffPredicate = CreateScreenIsOffPredicate();
-
- *config.add_predicate() = scheduledJobPredicate;
- *config.add_predicate() = screenIsOffPredicate;
- *config.add_predicate() = isSyncingPredicate;
- auto combinationPredicate = config.add_predicate();
- combinationPredicate->set_id(StringToId("CombinationPredicate"));
- combinationPredicate->mutable_combination()->set_operation(LogicalOperation::AND);
- addPredicateToPredicateCombination(screenIsOffPredicate, combinationPredicate);
- addPredicateToPredicateCombination(isSyncingPredicate, combinationPredicate);
-
- auto metric = config.add_duration_metric();
- metric->set_bucket(FIVE_MINUTES);
- metric->set_id(StringToId("scheduledJob"));
- metric->set_what(scheduledJobPredicate.id());
- metric->set_condition(combinationPredicate->id());
- metric->set_aggregation_type(aggregationType);
- *metric->mutable_dimensions_in_what() = CreateAttributionUidDimensions(
- android::util::SCHEDULED_JOB_STATE_CHANGED, {Position::FIRST});
-
- auto links = metric->add_links();
- links->set_condition(isSyncingPredicate.id());
- *links->mutable_fields_in_what() =
- CreateAttributionUidDimensions(
- android::util::SCHEDULED_JOB_STATE_CHANGED, {Position::FIRST});
- *links->mutable_fields_in_condition() =
- CreateAttributionUidDimensions(android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- return config;
-}
-
-} // namespace
-
-TEST(DimensionInConditionE2eTest, TestDurationMetric_Link_AND_CombinationCondition) {
- for (bool isFullLink : {true, false}) {
- for (auto aggregationType : {DurationMetric::SUM, DurationMetric::MAX_SPARSE}) {
- ConfigKey cfgKey;
- auto config = CreateDurationMetricConfig_Link_AND_CombinationCondition(
- aggregationType, !isFullLink);
- int64_t bucketStartTimeNs = 10000000000;
- int64_t bucketSizeNs =
- TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-
- auto processor = CreateStatsLogProcessor(
- bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
- EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
- EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-
- std::vector<AttributionNodeInternal> attributions1 = {
- CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(222, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions2 = {
- CreateAttribution(333, "App2"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions3 = {
- CreateAttribution(444, "App3"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<std::unique_ptr<LogEvent>> events;
-
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 55));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + 120));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 121));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + 450));
-
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 501));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + bucketSizeNs + 100));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(111, "App1")}, "job1", bucketStartTimeNs + 1));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(111, "App1")}, "job1",bucketStartTimeNs + 101));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2", bucketStartTimeNs + 201));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2",bucketStartTimeNs + 500));
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2", bucketStartTimeNs + 600));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2",
- bucketStartTimeNs + bucketSizeNs + 850));
-
- events.push_back(
- CreateStartScheduledJobEvent({CreateAttribution(444, "App3")}, "job3",
- bucketStartTimeNs + bucketSizeNs - 2));
- events.push_back(
- CreateFinishScheduledJobEvent({CreateAttribution(444, "App3")}, "job3",
- bucketStartTimeNs + bucketSizeNs + 900));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 50));
- events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 110));
-
- events.push_back(CreateSyncStartEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + 300));
- events.push_back(CreateSyncEndEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + bucketSizeNs + 700));
- events.push_back(CreateSyncStartEvent(attributions2, "ReadDoc",
- bucketStartTimeNs + 400));
- events.push_back(CreateSyncEndEvent(attributions2, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs - 1));
-
- events.push_back(CreateSyncStartEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + 550));
- events.push_back(CreateSyncEndEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + 800));
- events.push_back(CreateSyncStartEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs - 1));
- events.push_back(CreateSyncEndEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs + 700));
-
- sortLogEventsByTimestamp(&events);
-
- for (const auto& event : events) {
- processor->OnLogEvent(event.get());
- }
-
- ConfigMetricsReportList reports;
- vector<uint8_t> buffer;
- processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false,
- true, ADB_DUMP, FAST, &buffer);
- EXPECT_TRUE(buffer.size() > 0);
- EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
- backfillDimensionPath(&reports);
- backfillStringInReport(&reports);
- backfillStartEndTimestamp(&reports);
-
- EXPECT_EQ(reports.reports_size(), 1);
- EXPECT_EQ(reports.reports(0).metrics_size(), 1);
- StatsLogReport::DurationMetricDataWrapper metrics;
- sortMetricDataByDimensionsValue(
- reports.reports(0).metrics(0).duration_metrics(), &metrics);
-
- if (aggregationType == DurationMetric::SUM) {
- EXPECT_EQ(metrics.data_size(), 3);
- auto data = metrics.data(0);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 111);
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 101 - 55);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
-
- data = metrics.data(1);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 333);
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 450 - 300 + bucketSizeNs - 600);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 100);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(2);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 444);
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 100);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- } else {
- EXPECT_EQ(metrics.data_size(), 3);
- auto data = metrics.data(0);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 111);
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 101 - 55);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
-
- data = metrics.data(1);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 333);
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 450 - 300);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), bucketSizeNs - 600 + 100);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(2);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 444);
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 101);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- }
- }
- }
-}
-
-namespace {
-
-StatsdConfig CreateDurationMetricConfig_PartialLink_AND_CombinationCondition(
- DurationMetric::AggregationType aggregationType, bool hashStringInReport) {
- StatsdConfig config;
- config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
- *config.add_atom_matcher() = CreateStartScheduledJobAtomMatcher();
- *config.add_atom_matcher() = CreateFinishScheduledJobAtomMatcher();
- *config.add_atom_matcher() = CreateSyncStartAtomMatcher();
- *config.add_atom_matcher() = CreateSyncEndAtomMatcher();
- *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
- *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
-
- auto scheduledJobPredicate = CreateScheduledJobPredicate();
- auto dimensions = scheduledJobPredicate.mutable_simple_predicate()->mutable_dimensions();
- *dimensions = CreateAttributionUidDimensions(
- android::util::SCHEDULED_JOB_STATE_CHANGED, {Position::FIRST});
- dimensions->add_child()->set_field(2); // job name field.
-
- auto isSyncingPredicate = CreateIsSyncingPredicate();
- auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
- *syncDimension = CreateAttributionUidDimensions(
- android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- syncDimension->add_child()->set_field(2 /* name field*/);
-
- auto screenIsOffPredicate = CreateScreenIsOffPredicate();
-
- config.set_hash_strings_in_metric_report(hashStringInReport);
- *config.add_predicate() = scheduledJobPredicate;
- *config.add_predicate() = screenIsOffPredicate;
- *config.add_predicate() = isSyncingPredicate;
- auto combinationPredicate = config.add_predicate();
- combinationPredicate->set_id(StringToId("CombinationPredicate"));
- combinationPredicate->mutable_combination()->set_operation(LogicalOperation::AND);
- addPredicateToPredicateCombination(screenIsOffPredicate, combinationPredicate);
- addPredicateToPredicateCombination(isSyncingPredicate, combinationPredicate);
-
- auto metric = config.add_duration_metric();
- metric->set_bucket(FIVE_MINUTES);
- metric->set_id(StringToId("scheduledJob"));
- metric->set_what(scheduledJobPredicate.id());
- metric->set_condition(combinationPredicate->id());
- metric->set_aggregation_type(aggregationType);
- *metric->mutable_dimensions_in_what() = CreateAttributionUidDimensions(
- android::util::SCHEDULED_JOB_STATE_CHANGED, {Position::FIRST});
- *metric->mutable_dimensions_in_condition() = *syncDimension;
-
-
- auto links = metric->add_links();
- links->set_condition(isSyncingPredicate.id());
- *links->mutable_fields_in_what() =
- CreateAttributionUidDimensions(
- android::util::SCHEDULED_JOB_STATE_CHANGED, {Position::FIRST});
- *links->mutable_fields_in_condition() =
- CreateAttributionUidDimensions(android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- return config;
-}
-
-} // namespace
-
-TEST(DimensionInConditionE2eTest, TestDurationMetric_PartialLink_AND_CombinationCondition) {
- for (const bool hashStringInReport : {true, false}) {
- for (auto aggregationType : {DurationMetric::SUM, DurationMetric::MAX_SPARSE}) {
- ConfigKey cfgKey;
- auto config =
- CreateDurationMetricConfig_PartialLink_AND_CombinationCondition(
- aggregationType, hashStringInReport);
- int64_t bucketStartTimeNs = 10000000000;
- int64_t bucketSizeNs =
- TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-
- auto processor = CreateStatsLogProcessor(
- bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
- EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
- EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-
- std::vector<AttributionNodeInternal> attributions1 = {
- CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(222, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions2 = {
- CreateAttribution(333, "App2"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions3 = {
- CreateAttribution(444, "App3"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<std::unique_ptr<LogEvent>> events;
-
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 55));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + 120));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 121));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + 450));
-
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 501));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + bucketSizeNs + 100));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(111, "App1")}, "job1", bucketStartTimeNs + 1));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(111, "App1")}, "job1",bucketStartTimeNs + 101));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2", bucketStartTimeNs + 201));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2",bucketStartTimeNs + 500));
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2", bucketStartTimeNs + 600));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2",
- bucketStartTimeNs + bucketSizeNs + 850));
-
- events.push_back(
- CreateStartScheduledJobEvent({CreateAttribution(444, "App3")}, "job3",
- bucketStartTimeNs + bucketSizeNs - 2));
- events.push_back(
- CreateFinishScheduledJobEvent({CreateAttribution(444, "App3")}, "job3",
- bucketStartTimeNs + bucketSizeNs + 900));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 50));
- events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 110));
-
- events.push_back(CreateSyncStartEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + 300));
- events.push_back(CreateSyncEndEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + bucketSizeNs + 700));
- events.push_back(CreateSyncStartEvent(attributions2, "ReadDoc",
- bucketStartTimeNs + 400));
- events.push_back(CreateSyncEndEvent(attributions2, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs - 1));
-
- events.push_back(CreateSyncStartEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + 550));
- events.push_back(CreateSyncEndEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + 800));
- events.push_back(CreateSyncStartEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs - 1));
- events.push_back(CreateSyncEndEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs + 700));
-
- sortLogEventsByTimestamp(&events);
-
- for (const auto& event : events) {
- processor->OnLogEvent(event.get());
- }
-
- ConfigMetricsReportList reports;
- vector<uint8_t> buffer;
- processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false,
- true, ADB_DUMP, FAST, &buffer);
- EXPECT_TRUE(buffer.size() > 0);
- EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
- backfillDimensionPath(&reports);
- backfillStringInReport(&reports);
- backfillStartEndTimestamp(&reports);
-
- EXPECT_EQ(reports.reports_size(), 1);
- EXPECT_EQ(reports.reports(0).metrics_size(), 1);
- StatsLogReport::DurationMetricDataWrapper metrics;
- sortMetricDataByDimensionsValue(
- reports.reports(0).metrics(0).duration_metrics(), &metrics);
- if (aggregationType == DurationMetric::SUM) {
- EXPECT_EQ(metrics.data_size(), 4);
- auto data = metrics.data(0);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 111);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 111);
- EXPECT_EQ("ReadEmail",
- data.dimensions_in_condition().value_tuple().
- dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 101 - 55);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
-
- data = metrics.data(1);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 333);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 333);
- EXPECT_EQ("ReadDoc",
- data.dimensions_in_condition().value_tuple().
- dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), bucketSizeNs - 1 - 600 + 50);
-
- data = metrics.data(2);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 333);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 333);
- EXPECT_EQ("ReadEmail",
- data.dimensions_in_condition().value_tuple().
- dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 450 - 300 + bucketSizeNs - 600);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 100);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(3);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 444);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 444);
- EXPECT_EQ("ReadDoc",
- data.dimensions_in_condition().value_tuple().
- dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 100);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- } else {
- EXPECT_EQ(metrics.data_size(), 4);
- auto data = metrics.data(0);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 111);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 111);
- EXPECT_EQ("ReadEmail",
- data.dimensions_in_condition().value_tuple().
- dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 101 - 55);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
-
- data = metrics.data(1);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 333);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 333);
- EXPECT_EQ("ReadDoc",
- data.dimensions_in_condition().value_tuple().
- dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 50);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), bucketSizeNs - 1 - 600);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(2);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 333);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 333);
- EXPECT_EQ("ReadEmail",
- data.dimensions_in_condition().value_tuple().
- dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 450 - 300);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), bucketSizeNs - 600 + 100);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(3);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 444);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 444);
- EXPECT_EQ("ReadDoc",
- data.dimensions_in_condition().value_tuple().
- dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 101);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- }
- }
- }
-}
-
-#else
-GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif
-
-} // namespace statsd
-} // namespace os
-} // namespace android
diff --git a/cmds/statsd/tests/e2e/DimensionInCondition_e2e_combination_OR_cond_test.cpp b/cmds/statsd/tests/e2e/DimensionInCondition_e2e_combination_OR_cond_test.cpp
deleted file mode 100644
index f3ecd56dd946..000000000000
--- a/cmds/statsd/tests/e2e/DimensionInCondition_e2e_combination_OR_cond_test.cpp
+++ /dev/null
@@ -1,816 +0,0 @@
-// Copyright (C) 2017 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include <gtest/gtest.h>
-
-#include "src/StatsLogProcessor.h"
-#include "src/stats_log_util.h"
-#include "tests/statsd_test_util.h"
-
-#include <vector>
-
-namespace android {
-namespace os {
-namespace statsd {
-
-#ifdef __ANDROID__
-
-namespace {
-
-StatsdConfig CreateCountMetric_NoLink_CombinationCondition_Config() {
- StatsdConfig config;
- config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
- auto screenBrightnessChangeAtomMatcher = CreateScreenBrightnessChangedAtomMatcher();
- *config.add_atom_matcher() = screenBrightnessChangeAtomMatcher;
- *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
- *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
- *config.add_atom_matcher() = CreateAcquireWakelockAtomMatcher();
- *config.add_atom_matcher() = CreateReleaseWakelockAtomMatcher();
-
- auto screenIsOffPredicate = CreateScreenIsOffPredicate();
- *config.add_predicate() = screenIsOffPredicate;
-
- auto holdingWakelockPredicate = CreateHoldingWakelockPredicate();
- // The predicate is dimensioning by any attribution node and both by uid and tag.
- *holdingWakelockPredicate.mutable_simple_predicate()->mutable_dimensions() =
- CreateAttributionUidAndTagDimensions(android::util::WAKELOCK_STATE_CHANGED,
- {Position::FIRST});
- *config.add_predicate() = holdingWakelockPredicate;
-
- auto combinationPredicate = config.add_predicate();
- combinationPredicate->set_id(987654);
- combinationPredicate->mutable_combination()->set_operation(LogicalOperation::OR);
- addPredicateToPredicateCombination(screenIsOffPredicate, combinationPredicate);
- addPredicateToPredicateCombination(holdingWakelockPredicate, combinationPredicate);
-
- auto metric = config.add_count_metric();
- metric->set_id(StringToId("ScreenBrightnessChangeMetric"));
- metric->set_what(screenBrightnessChangeAtomMatcher.id());
- metric->set_condition(combinationPredicate->id());
- *metric->mutable_dimensions_in_what() =
- CreateDimensions(android::util::SCREEN_BRIGHTNESS_CHANGED, {1 /* level */});
- *metric->mutable_dimensions_in_condition() = CreateAttributionUidDimensions(
- android::util::WAKELOCK_STATE_CHANGED, {Position::FIRST});
- metric->set_bucket(FIVE_MINUTES);
- return config;
-}
-
-} // namespace
-
-TEST(DimensionInConditionE2eTest, TestCreateCountMetric_NoLink_OR_CombinationCondition) {
- ConfigKey cfgKey;
- auto config = CreateCountMetric_NoLink_CombinationCondition_Config();
- int64_t bucketStartTimeNs = 10000000000;
- int64_t bucketSizeNs =
- TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
-
- auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
- EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
- EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-
- std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(111, "App1"),
- CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(222, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions2 = {CreateAttribution(333, "App2"),
- CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<std::unique_ptr<LogEvent>> events;
- events.push_back(
- CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON, bucketStartTimeNs + 10));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 100));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + bucketSizeNs + 1));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 2 * bucketSizeNs - 10));
-
- events.push_back(CreateAcquireWakelockEvent(attributions1, "wl1", bucketStartTimeNs + 200));
- events.push_back(
- CreateReleaseWakelockEvent(attributions1, "wl1", bucketStartTimeNs + bucketSizeNs + 1));
-
- events.push_back(CreateAcquireWakelockEvent(attributions2, "wl2",
- bucketStartTimeNs + bucketSizeNs - 100));
- events.push_back(CreateReleaseWakelockEvent(attributions2, "wl2",
- bucketStartTimeNs + 2 * bucketSizeNs - 50));
-
- events.push_back(CreateScreenBrightnessChangedEvent(123, bucketStartTimeNs + 11));
- events.push_back(CreateScreenBrightnessChangedEvent(123, bucketStartTimeNs + 101));
- events.push_back(CreateScreenBrightnessChangedEvent(123, bucketStartTimeNs + 201));
- events.push_back(CreateScreenBrightnessChangedEvent(456, bucketStartTimeNs + 203));
- events.push_back(
- CreateScreenBrightnessChangedEvent(456, bucketStartTimeNs + bucketSizeNs - 99));
- events.push_back(CreateScreenBrightnessChangedEvent(456, bucketStartTimeNs + bucketSizeNs - 2));
- events.push_back(CreateScreenBrightnessChangedEvent(789, bucketStartTimeNs + bucketSizeNs - 1));
- events.push_back(CreateScreenBrightnessChangedEvent(456, bucketStartTimeNs + bucketSizeNs + 2));
- events.push_back(
- CreateScreenBrightnessChangedEvent(789, bucketStartTimeNs + 2 * bucketSizeNs - 11));
- events.push_back(
- CreateScreenBrightnessChangedEvent(789, bucketStartTimeNs + 2 * bucketSizeNs - 9));
- events.push_back(
- CreateScreenBrightnessChangedEvent(789, bucketStartTimeNs + 2 * bucketSizeNs - 1));
-
- sortLogEventsByTimestamp(&events);
-
- for (const auto& event : events) {
- processor->OnLogEvent(event.get());
- }
-
- ConfigMetricsReportList reports;
- vector<uint8_t> buffer;
- processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false, true,
- ADB_DUMP, FAST, &buffer);
- EXPECT_TRUE(buffer.size() > 0);
- EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
- backfillDimensionPath(&reports);
- backfillStringInReport(&reports);
- backfillStartEndTimestamp(&reports);
-
- EXPECT_EQ(reports.reports_size(), 1);
- EXPECT_EQ(reports.reports(0).metrics_size(), 1);
- StatsLogReport::CountMetricDataWrapper countMetrics;
- sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
-
- EXPECT_EQ(countMetrics.data_size(), 7);
- auto data = countMetrics.data(0);
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).count(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 123);
- EXPECT_FALSE(data.dimensions_in_condition().has_field());
-
- data = countMetrics.data(1);
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).count(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 123);
- ValidateAttributionUidDimension(data.dimensions_in_condition(),
- android::util::WAKELOCK_STATE_CHANGED, 111);
-
- data = countMetrics.data(2);
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).count(), 3);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 456);
- ValidateAttributionUidDimension(data.dimensions_in_condition(),
- android::util::WAKELOCK_STATE_CHANGED, 111);
-
- data = countMetrics.data(3);
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).count(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).count(), 1);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
- EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 456);
- ValidateAttributionUidDimension(data.dimensions_in_condition(),
- android::util::WAKELOCK_STATE_CHANGED, 333);
-
- data = countMetrics.data(4);
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).count(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
- EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 789);
- EXPECT_FALSE(data.dimensions_in_condition().has_field());
-
- data = countMetrics.data(5);
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).count(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 789);
- ValidateAttributionUidDimension(data.dimensions_in_condition(),
- android::util::WAKELOCK_STATE_CHANGED, 111);
-
- data = countMetrics.data(6);
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).count(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 789);
- ValidateAttributionUidDimension(data.dimensions_in_condition(),
- android::util::WAKELOCK_STATE_CHANGED, 333);
-}
-
-namespace {
-
-StatsdConfig CreateCountMetric_Link_CombinationCondition() {
- StatsdConfig config;
- config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
- auto appCrashMatcher = CreateProcessCrashAtomMatcher();
- *config.add_atom_matcher() = appCrashMatcher;
- *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
- *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
- *config.add_atom_matcher() = CreateSyncStartAtomMatcher();
- *config.add_atom_matcher() = CreateSyncEndAtomMatcher();
-
- auto screenIsOffPredicate = CreateScreenIsOffPredicate();
- auto isSyncingPredicate = CreateIsSyncingPredicate();
- auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
- *syncDimension = CreateAttributionUidAndTagDimensions(android::util::SYNC_STATE_CHANGED,
- {Position::FIRST});
- syncDimension->add_child()->set_field(2 /* name field*/);
-
- *config.add_predicate() = screenIsOffPredicate;
- *config.add_predicate() = isSyncingPredicate;
- auto combinationPredicate = config.add_predicate();
- combinationPredicate->set_id(987654);
- combinationPredicate->mutable_combination()->set_operation(LogicalOperation::OR);
- addPredicateToPredicateCombination(screenIsOffPredicate, combinationPredicate);
- addPredicateToPredicateCombination(isSyncingPredicate, combinationPredicate);
-
- auto metric = config.add_count_metric();
- metric->set_bucket(FIVE_MINUTES);
- metric->set_id(StringToId("AppCrashMetric"));
- metric->set_what(appCrashMatcher.id());
- metric->set_condition(combinationPredicate->id());
- *metric->mutable_dimensions_in_what() =
- CreateDimensions(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, {1 /* uid */});
- *metric->mutable_dimensions_in_condition() = CreateAttributionUidAndTagDimensions(
- android::util::SYNC_STATE_CHANGED, {Position::FIRST});
-
- // Links between crash atom and condition of app is in syncing.
- auto links = metric->add_links();
- links->set_condition(isSyncingPredicate.id());
- auto dimensionWhat = links->mutable_fields_in_what();
- dimensionWhat->set_field(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
- dimensionWhat->add_child()->set_field(1); // uid field.
- *links->mutable_fields_in_condition() =
- CreateAttributionUidDimensions(android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- return config;
-}
-
-} // namespace
-
-TEST(DimensionInConditionE2eTest, TestCreateCountMetric_Link_OR_CombinationCondition) {
- ConfigKey cfgKey;
- auto config = CreateCountMetric_Link_CombinationCondition();
- int64_t bucketStartTimeNs = 10000000000;
- int64_t bucketSizeNs =
- TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
-
- auto processor = CreateStatsLogProcessor(bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
- EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
- EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
- std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(111, "App1"),
- CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(222, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions2 = {CreateAttribution(333, "App2"),
- CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<std::unique_ptr<LogEvent>> events;
-
- events.push_back(CreateAppCrashEvent(111, bucketStartTimeNs + 11));
- events.push_back(CreateAppCrashEvent(111, bucketStartTimeNs + 101));
- events.push_back(CreateAppCrashEvent(222, bucketStartTimeNs + 101));
-
- events.push_back(CreateAppCrashEvent(222, bucketStartTimeNs + 201));
- events.push_back(CreateAppCrashEvent(111, bucketStartTimeNs + 211));
- events.push_back(CreateAppCrashEvent(333, bucketStartTimeNs + 211));
-
- events.push_back(CreateAppCrashEvent(111, bucketStartTimeNs + 401));
- events.push_back(CreateAppCrashEvent(333, bucketStartTimeNs + 401));
- events.push_back(CreateAppCrashEvent(555, bucketStartTimeNs + 401));
-
- events.push_back(CreateAppCrashEvent(111, bucketStartTimeNs + bucketSizeNs + 301));
- events.push_back(CreateAppCrashEvent(333, bucketStartTimeNs + bucketSizeNs + 301));
-
- events.push_back(CreateAppCrashEvent(777, bucketStartTimeNs + bucketSizeNs + 701));
-
- events.push_back(
- CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON, bucketStartTimeNs + 10));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 100));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + 202));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + bucketSizeNs + 700));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail", bucketStartTimeNs + 200));
- events.push_back(
- CreateSyncEndEvent(attributions1, "ReadEmail", bucketStartTimeNs + bucketSizeNs + 300));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadDoc", bucketStartTimeNs + 400));
- events.push_back(
- CreateSyncEndEvent(attributions1, "ReadDoc", bucketStartTimeNs + bucketSizeNs - 1));
-
- events.push_back(CreateSyncStartEvent(attributions2, "ReadEmail", bucketStartTimeNs + 400));
- events.push_back(
- CreateSyncEndEvent(attributions2, "ReadEmail", bucketStartTimeNs + bucketSizeNs + 600));
-
- sortLogEventsByTimestamp(&events);
-
- for (const auto& event : events) {
- processor->OnLogEvent(event.get());
- }
-
- ConfigMetricsReportList reports;
- vector<uint8_t> buffer;
- processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false, true,
- ADB_DUMP, FAST, &buffer);
- EXPECT_TRUE(buffer.size() > 0);
- EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
- backfillDimensionPath(&reports);
- backfillStringInReport(&reports);
- backfillStartEndTimestamp(&reports);
-
- EXPECT_EQ(reports.reports_size(), 1);
- EXPECT_EQ(reports.reports(0).metrics_size(), 1);
- StatsLogReport::CountMetricDataWrapper countMetrics;
- sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
-
- EXPECT_EQ(countMetrics.data_size(), 5);
- auto data = countMetrics.data(0);
- EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 111);
- EXPECT_FALSE(data.dimensions_in_condition().has_field());
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).count(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
-
- data = countMetrics.data(1);
- EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 111);
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 111, "App1");
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).count(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
-
- data = countMetrics.data(2);
- EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 222);
- EXPECT_FALSE(data.dimensions_in_condition().has_field());
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).count(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
-
- data = countMetrics.data(3);
- EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 333);
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 333, "App2");
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).count(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).count(), 1);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = countMetrics.data(4);
- EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 777);
- EXPECT_FALSE(data.dimensions_in_condition().has_field());
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).count(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
-}
-
-namespace {
-
-StatsdConfig CreateDurationMetricConfig_NoLink_CombinationCondition(
- DurationMetric::AggregationType aggregationType) {
- StatsdConfig config;
- config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
- *config.add_atom_matcher() = CreateBatterySaverModeStartAtomMatcher();
- *config.add_atom_matcher() = CreateBatterySaverModeStopAtomMatcher();
- *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
- *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
- *config.add_atom_matcher() = CreateSyncStartAtomMatcher();
- *config.add_atom_matcher() = CreateSyncEndAtomMatcher();
-
- auto inBatterySaverModePredicate = CreateBatterySaverModePredicate();
-
- auto screenIsOffPredicate = CreateScreenIsOffPredicate();
- auto isSyncingPredicate = CreateIsSyncingPredicate();
- auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
- *syncDimension = CreateAttributionUidAndTagDimensions(android::util::SYNC_STATE_CHANGED,
- {Position::FIRST});
- syncDimension->add_child()->set_field(2 /* name field */);
-
- *config.add_predicate() = inBatterySaverModePredicate;
- *config.add_predicate() = screenIsOffPredicate;
- *config.add_predicate() = isSyncingPredicate;
- auto combinationPredicate = config.add_predicate();
- combinationPredicate->set_id(987654);
- combinationPredicate->mutable_combination()->set_operation(LogicalOperation::OR);
- addPredicateToPredicateCombination(screenIsOffPredicate, combinationPredicate);
- addPredicateToPredicateCombination(isSyncingPredicate, combinationPredicate);
-
- auto metric = config.add_duration_metric();
- metric->set_bucket(FIVE_MINUTES);
- metric->set_id(StringToId("BatterySaverModeDurationMetric"));
- metric->set_what(inBatterySaverModePredicate.id());
- metric->set_condition(combinationPredicate->id());
- metric->set_aggregation_type(aggregationType);
- *metric->mutable_dimensions_in_condition() = CreateAttributionUidAndTagDimensions(
- android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- return config;
-}
-
-} // namespace
-
-TEST(DimensionInConditionE2eTest, TestDurationMetric_NoLink_OR_CombinationCondition) {
- for (auto aggregationType : { DurationMetric::MAX_SPARSE, DurationMetric::SUM}) {
- ConfigKey cfgKey;
- auto config = CreateDurationMetricConfig_NoLink_CombinationCondition(aggregationType);
- int64_t bucketStartTimeNs = 10000000000;
- int64_t bucketSizeNs =
- TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-
- auto processor = CreateStatsLogProcessor(
- bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
- EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
- EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-
- std::vector<AttributionNodeInternal> attributions1 = {
- CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(222, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions2 = {
- CreateAttribution(333, "App2"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<std::unique_ptr<LogEvent>> events;
-
- events.push_back(CreateBatterySaverOffEvent(bucketStartTimeNs + 1));
- events.push_back(CreateBatterySaverOnEvent(bucketStartTimeNs + 101));
- events.push_back(CreateBatterySaverOffEvent(bucketStartTimeNs + 110));
-
- events.push_back(CreateBatterySaverOnEvent(bucketStartTimeNs + 201));
- events.push_back(CreateBatterySaverOffEvent(bucketStartTimeNs + 500));
-
- events.push_back(CreateBatterySaverOnEvent(bucketStartTimeNs + 600));
- events.push_back(CreateBatterySaverOffEvent(bucketStartTimeNs + bucketSizeNs + 850));
-
- events.push_back(CreateBatterySaverOnEvent(bucketStartTimeNs + bucketSizeNs + 870));
- events.push_back(CreateBatterySaverOffEvent(bucketStartTimeNs + bucketSizeNs + 900));
-
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + 10));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 100));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + 202));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + bucketSizeNs + 800));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail", bucketStartTimeNs + 200));
- events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + bucketSizeNs + 300));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadDoc", bucketStartTimeNs + 400));
- events.push_back(
- CreateSyncEndEvent(attributions1, "ReadDoc", bucketStartTimeNs + bucketSizeNs - 1));
-
- events.push_back(CreateSyncStartEvent(attributions2, "ReadEmail", bucketStartTimeNs + 401));
- events.push_back(CreateSyncEndEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + bucketSizeNs + 700));
-
- sortLogEventsByTimestamp(&events);
-
- for (const auto& event : events) {
- processor->OnLogEvent(event.get());
- }
-
- ConfigMetricsReportList reports;
- vector<uint8_t> buffer;
- processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false, true,
- ADB_DUMP, FAST, &buffer);
- EXPECT_TRUE(buffer.size() > 0);
- EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
- backfillDimensionPath(&reports);
- backfillStringInReport(&reports);
- backfillStartEndTimestamp(&reports);
-
- EXPECT_EQ(reports.reports_size(), 1);
- EXPECT_EQ(reports.reports(0).metrics_size(), 1);
- StatsLogReport::DurationMetricDataWrapper metrics;
- sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).duration_metrics(), &metrics);
-
- EXPECT_EQ(metrics.data_size(), 3);
- auto data = metrics.data(0);
- EXPECT_FALSE(data.dimensions_in_what().has_field());
- EXPECT_FALSE(data.dimensions_in_condition().has_field());
- if (aggregationType == DurationMetric::SUM) {
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 9);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 30);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- } else {
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 9);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 30);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- }
-
- data = metrics.data(1);
- EXPECT_FALSE(data.dimensions_in_what().has_field());
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 111, "App1");
- EXPECT_EQ(data.bucket_info_size(), 2);
-
- if (aggregationType == DurationMetric::SUM) {
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 201 + bucketSizeNs - 600);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 300);
- } else {
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 201);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), bucketSizeNs - 300);
- }
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(2);
- EXPECT_FALSE(data.dimensions_in_what().has_field());
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 333, "App2");
- EXPECT_EQ(data.bucket_info_size(), 2);
- if (aggregationType == DurationMetric::SUM) {
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 401 + bucketSizeNs - 600);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 700);
- } else {
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 401);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), bucketSizeNs + 700 - 600);
- }
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- }
-}
-
-namespace {
-
-StatsdConfig CreateDurationMetricConfig_Link_CombinationCondition(
- DurationMetric::AggregationType aggregationType) {
- StatsdConfig config;
- config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
- *config.add_atom_matcher() = CreateMoveToBackgroundAtomMatcher();
- *config.add_atom_matcher() = CreateMoveToForegroundAtomMatcher();
- *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
- *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
- *config.add_atom_matcher() = CreateSyncStartAtomMatcher();
- *config.add_atom_matcher() = CreateSyncEndAtomMatcher();
-
- auto screenIsOffPredicate = CreateScreenIsOffPredicate();
- auto isSyncingPredicate = CreateIsSyncingPredicate();
- auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
- *syncDimension = CreateAttributionUidAndTagDimensions(android::util::SYNC_STATE_CHANGED,
- {Position::FIRST});
- syncDimension->add_child()->set_field(2 /* name field */);
-
- auto isInBackgroundPredicate = CreateIsInBackgroundPredicate();
- *isInBackgroundPredicate.mutable_simple_predicate()->mutable_dimensions() =
- CreateDimensions(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, {1 /* uid field */});
-
- *config.add_predicate() = screenIsOffPredicate;
- *config.add_predicate() = isSyncingPredicate;
- *config.add_predicate() = isInBackgroundPredicate;
- auto combinationPredicate = config.add_predicate();
- combinationPredicate->set_id(987654);
- combinationPredicate->mutable_combination()->set_operation(LogicalOperation::OR);
- addPredicateToPredicateCombination(screenIsOffPredicate, combinationPredicate);
- addPredicateToPredicateCombination(isSyncingPredicate, combinationPredicate);
-
- auto metric = config.add_duration_metric();
- metric->set_bucket(FIVE_MINUTES);
- metric->set_id(StringToId("AppInBackgroundMetric"));
- metric->set_what(isInBackgroundPredicate.id());
- metric->set_condition(combinationPredicate->id());
- metric->set_aggregation_type(aggregationType);
- *metric->mutable_dimensions_in_what() =
- CreateDimensions(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, {1 /* uid field */});
- *metric->mutable_dimensions_in_condition() = CreateAttributionUidAndTagDimensions(
- android::util::SYNC_STATE_CHANGED, {Position::FIRST});
-
- // Links between crash atom and condition of app is in syncing.
- auto links = metric->add_links();
- links->set_condition(isSyncingPredicate.id());
- auto dimensionWhat = links->mutable_fields_in_what();
- dimensionWhat->set_field(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED);
- dimensionWhat->add_child()->set_field(1); // uid field.
- *links->mutable_fields_in_condition() =
- CreateAttributionUidDimensions(android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- return config;
-}
-
-} // namespace
-
-TEST(DimensionInConditionE2eTest, TestDurationMetric_Link_OR_CombinationCondition) {
- for (auto aggregationType : {DurationMetric::SUM, DurationMetric::MAX_SPARSE}) {
- ConfigKey cfgKey;
- auto config = CreateDurationMetricConfig_Link_CombinationCondition(aggregationType);
- int64_t bucketStartTimeNs = 10000000000;
- int64_t bucketSizeNs =
- TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-
- auto processor = CreateStatsLogProcessor(
- bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
- EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
- EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-
- std::vector<AttributionNodeInternal> attributions1 = {
- CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(222, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions2 = {
- CreateAttribution(333, "App2"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<std::unique_ptr<LogEvent>> events;
-
- events.push_back(CreateMoveToBackgroundEvent(111, bucketStartTimeNs + 101));
- events.push_back(CreateMoveToForegroundEvent(111, bucketStartTimeNs + 110));
-
- events.push_back(CreateMoveToBackgroundEvent(111, bucketStartTimeNs + 201));
- events.push_back(CreateMoveToForegroundEvent(111, bucketStartTimeNs + bucketSizeNs + 100));
-
- events.push_back(CreateMoveToBackgroundEvent(333, bucketStartTimeNs + 399));
- events.push_back(CreateMoveToForegroundEvent(333, bucketStartTimeNs + bucketSizeNs + 800));
-
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + 10));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + 100));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
- bucketStartTimeNs + 202));
- events.push_back(CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_OFF,
- bucketStartTimeNs + bucketSizeNs + 801));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail", bucketStartTimeNs + 200));
- events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + bucketSizeNs + 300));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadDoc", bucketStartTimeNs + 400));
- events.push_back(
- CreateSyncEndEvent(attributions1, "ReadDoc", bucketStartTimeNs + bucketSizeNs - 1));
-
- events.push_back(CreateSyncStartEvent(attributions2, "ReadEmail", bucketStartTimeNs + 401));
- events.push_back(CreateSyncEndEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + bucketSizeNs + 700));
-
- sortLogEventsByTimestamp(&events);
-
- for (const auto& event : events) {
- processor->OnLogEvent(event.get());
- }
-
- ConfigMetricsReportList reports;
- vector<uint8_t> buffer;
- processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false, true,
- ADB_DUMP, FAST, &buffer);
- EXPECT_TRUE(buffer.size() > 0);
- EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
- backfillDimensionPath(&reports);
- backfillStringInReport(&reports);
- backfillStartEndTimestamp(&reports);
-
- EXPECT_EQ(reports.reports_size(), 1);
- EXPECT_EQ(reports.reports(0).metrics_size(), 1);
- StatsLogReport::DurationMetricDataWrapper metrics;
- sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).duration_metrics(), &metrics);
-
- EXPECT_EQ(metrics.data_size(), 3);
- auto data = metrics.data(0);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 111);
- EXPECT_FALSE(data.dimensions_in_condition().has_field());
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 9);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(), bucketStartTimeNs + bucketSizeNs);
-
- data = metrics.data(1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 111);
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 111, "App1");
- if (aggregationType == DurationMetric::SUM) {
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), bucketSizeNs - 201);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 100);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- } else {
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), bucketSizeNs + 100 - 201);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- }
-
- data = metrics.data(2);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 333);
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 333, "App2");
- if (aggregationType == DurationMetric::SUM) {
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), bucketSizeNs - 401);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 700);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- } else {
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), bucketSizeNs + 299);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- }
- }
-}
-
-#else
-GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif
-
-} // namespace statsd
-} // namespace os
-} // namespace android
diff --git a/cmds/statsd/tests/e2e/DimensionInCondition_e2e_simple_cond_test.cpp b/cmds/statsd/tests/e2e/DimensionInCondition_e2e_simple_cond_test.cpp
deleted file mode 100644
index 489bb0b21a2e..000000000000
--- a/cmds/statsd/tests/e2e/DimensionInCondition_e2e_simple_cond_test.cpp
+++ /dev/null
@@ -1,814 +0,0 @@
-// Copyright (C) 2017 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#include <gtest/gtest.h>
-
-#include "src/StatsLogProcessor.h"
-#include "src/stats_log_util.h"
-#include "tests/statsd_test_util.h"
-
-#include <vector>
-
-namespace android {
-namespace os {
-namespace statsd {
-
-#ifdef __ANDROID__
-
-namespace {
-
-StatsdConfig CreateDurationMetricConfig_NoLink_SimpleCondition(
- DurationMetric::AggregationType aggregationType, bool addExtraDimensionInCondition) {
- StatsdConfig config;
- config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
- *config.add_atom_matcher() = CreateStartScheduledJobAtomMatcher();
- *config.add_atom_matcher() = CreateFinishScheduledJobAtomMatcher();
- *config.add_atom_matcher() = CreateSyncStartAtomMatcher();
- *config.add_atom_matcher() = CreateSyncEndAtomMatcher();
-
- auto scheduledJobPredicate = CreateScheduledJobPredicate();
- auto dimensions = scheduledJobPredicate.mutable_simple_predicate()->mutable_dimensions();
- dimensions->set_field(android::util::SCHEDULED_JOB_STATE_CHANGED);
- dimensions->add_child()->set_field(2); // job name field.
-
- auto isSyncingPredicate = CreateIsSyncingPredicate();
- auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
- *syncDimension = CreateAttributionUidAndTagDimensions(android::util::SYNC_STATE_CHANGED,
- {Position::FIRST});
- if (addExtraDimensionInCondition) {
- syncDimension->add_child()->set_field(2 /* name field*/);
- }
-
- *config.add_predicate() = scheduledJobPredicate;
- *config.add_predicate() = isSyncingPredicate;
-
- auto metric = config.add_duration_metric();
- metric->set_bucket(FIVE_MINUTES);
- metric->set_id(StringToId("scheduledJob"));
- metric->set_what(scheduledJobPredicate.id());
- metric->set_condition(isSyncingPredicate.id());
- metric->set_aggregation_type(aggregationType);
- auto dimensionWhat = metric->mutable_dimensions_in_what();
- dimensionWhat->set_field(android::util::SCHEDULED_JOB_STATE_CHANGED);
- dimensionWhat->add_child()->set_field(2); // job name field.
- *metric->mutable_dimensions_in_condition() = CreateAttributionUidAndTagDimensions(
- android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- return config;
-}
-
-} // namespace
-
-TEST(DimensionInConditionE2eTest, TestDurationMetric_NoLink_SimpleCondition) {
- for (bool isDimensionInConditionSubSetOfConditionTrackerDimension : {true, false}) {
- for (auto aggregationType : {DurationMetric::SUM, DurationMetric::MAX_SPARSE}) {
- ConfigKey cfgKey;
- auto config = CreateDurationMetricConfig_NoLink_SimpleCondition(
- aggregationType, isDimensionInConditionSubSetOfConditionTrackerDimension);
- int64_t bucketStartTimeNs = 10000000000;
- int64_t bucketSizeNs =
- TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-
- auto processor = CreateStatsLogProcessor(
- bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
- EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
- EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-
- std::vector<AttributionNodeInternal> attributions1 = {
- CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(222, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions2 = {
- CreateAttribution(333, "App2"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<std::unique_ptr<LogEvent>> events;
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(9999, "")}, "job0", bucketStartTimeNs + 1));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(9999, "")}, "job0",bucketStartTimeNs + 101));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(9999, "")}, "job2", bucketStartTimeNs + 201));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(9999, "")}, "job2",bucketStartTimeNs + 500));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(8888, "")}, "job2", bucketStartTimeNs + 600));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(8888, "")}, "job2",bucketStartTimeNs + bucketSizeNs + 850));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(8888, "")}, "job1", bucketStartTimeNs + bucketSizeNs + 600));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(8888, "")}, "job1", bucketStartTimeNs + bucketSizeNs + 900));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 10));
- events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 50));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 200));
- events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + bucketSizeNs + 300));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadDoc",
- bucketStartTimeNs + 400));
- events.push_back(CreateSyncEndEvent(attributions1, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs - 1));
-
- events.push_back(CreateSyncStartEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + 401));
- events.push_back(CreateSyncEndEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + bucketSizeNs + 700));
-
- sortLogEventsByTimestamp(&events);
-
- for (const auto& event : events) {
- processor->OnLogEvent(event.get());
- }
-
- ConfigMetricsReportList reports;
- vector<uint8_t> buffer;
- processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false,
- true, ADB_DUMP, FAST, &buffer);
- EXPECT_TRUE(buffer.size() > 0);
- EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
- backfillDimensionPath(&reports);
- backfillStringInReport(&reports);
- backfillStartEndTimestamp(&reports);
-
- EXPECT_EQ(reports.reports_size(), 1);
- EXPECT_EQ(reports.reports(0).metrics_size(), 1);
- StatsLogReport::DurationMetricDataWrapper metrics;
- sortMetricDataByDimensionsValue(
- reports.reports(0).metrics(0).duration_metrics(), &metrics);
- if (aggregationType == DurationMetric::SUM) {
- EXPECT_EQ(metrics.data_size(), 4);
- auto data = metrics.data(0);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str(),
- "job0"); // job name
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 111, "App1");
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 40);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
-
- data = metrics.data(1);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str(),
- "job1"); // job name
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 333, "App2");
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 100);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(2);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str(),
- "job2"); // job name
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 111, "App1");
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 201 + bucketSizeNs - 600);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 300);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(3);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str(),
- "job2"); // job name
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 333, "App2");
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 401 + bucketSizeNs - 600);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 700);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- } else {
- EXPECT_EQ(metrics.data_size(), 4);
- auto data = metrics.data(0);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str(),
- "job0"); // job name
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 111, "App1");
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 40);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
-
- data = metrics.data(1);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str(),
- "job1"); // job name
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 333, "App2");
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 100);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(2);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str(),
- "job2"); // job name
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 111, "App1");
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 201);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), bucketSizeNs - 600 + 300);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(3);
- EXPECT_EQ(data.dimensions_in_what().field(),
- android::util::SCHEDULED_JOB_STATE_CHANGED);
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(),
- 2); // job name field
- EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_str(),
- "job2"); // job name
- ValidateAttributionUidAndTagDimension(data.dimensions_in_condition(),
- android::util::SYNC_STATE_CHANGED, 333, "App2");
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 401 );
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), bucketSizeNs - 600 + 700);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- }
- }
- }
-}
-
-namespace {
-
-StatsdConfig createDurationMetric_Link_SimpleConditionConfig(
- DurationMetric::AggregationType aggregationType, bool addExtraDimensionInCondition) {
- StatsdConfig config;
- config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
- *config.add_atom_matcher() = CreateStartScheduledJobAtomMatcher();
- *config.add_atom_matcher() = CreateFinishScheduledJobAtomMatcher();
- *config.add_atom_matcher() = CreateSyncStartAtomMatcher();
- *config.add_atom_matcher() = CreateSyncEndAtomMatcher();
-
- auto scheduledJobPredicate = CreateScheduledJobPredicate();
- auto dimensions = scheduledJobPredicate.mutable_simple_predicate()->mutable_dimensions();
- *dimensions = CreateAttributionUidDimensions(
- android::util::SCHEDULED_JOB_STATE_CHANGED, {Position::FIRST});
- dimensions->add_child()->set_field(2); // job name field.
-
- auto isSyncingPredicate = CreateIsSyncingPredicate();
- auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
- *syncDimension = CreateAttributionUidDimensions(
- android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- if (addExtraDimensionInCondition) {
- syncDimension->add_child()->set_field(2 /* name field*/);
- }
-
- *config.add_predicate() = scheduledJobPredicate;
- *config.add_predicate() = isSyncingPredicate;
-
- auto metric = config.add_duration_metric();
- metric->set_bucket(FIVE_MINUTES);
- metric->set_id(StringToId("scheduledJob"));
- metric->set_what(scheduledJobPredicate.id());
- metric->set_condition(isSyncingPredicate.id());
- metric->set_aggregation_type(aggregationType);
- *metric->mutable_dimensions_in_what() = CreateAttributionUidDimensions(
- android::util::SCHEDULED_JOB_STATE_CHANGED, {Position::FIRST});
-
- auto links = metric->add_links();
- links->set_condition(isSyncingPredicate.id());
- *links->mutable_fields_in_what() =
- CreateAttributionUidDimensions(
- android::util::SCHEDULED_JOB_STATE_CHANGED, {Position::FIRST});
- *links->mutable_fields_in_condition() =
- CreateAttributionUidDimensions(android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- return config;
-}
-
-} // namespace
-
-TEST(DimensionInConditionE2eTest, TestDurationMetric_Link_SimpleCondition) {
- for (bool isFullLink : {true, false}) {
- for (auto aggregationType : {DurationMetric::SUM, DurationMetric::MAX_SPARSE}) {
- ConfigKey cfgKey;
- auto config = createDurationMetric_Link_SimpleConditionConfig(
- aggregationType, !isFullLink);
- int64_t bucketStartTimeNs = 10000000000;
- int64_t bucketSizeNs =
- TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-
- auto processor = CreateStatsLogProcessor(
- bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
- EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
- EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-
- std::vector<AttributionNodeInternal> attributions1 = {
- CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(222, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions2 = {
- CreateAttribution(333, "App2"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions3 = {
- CreateAttribution(444, "App3"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<std::unique_ptr<LogEvent>> events;
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(111, "App1")}, "job1", bucketStartTimeNs + 1));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(111, "App1")}, "job1",bucketStartTimeNs + 101));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2", bucketStartTimeNs + 201));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2",bucketStartTimeNs + 500));
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2", bucketStartTimeNs + 600));
- events.push_back(
- CreateFinishScheduledJobEvent({CreateAttribution(333, "App2")}, "job2",
- bucketStartTimeNs + bucketSizeNs + 850));
-
- events.push_back(
- CreateStartScheduledJobEvent({CreateAttribution(444, "App3")}, "job3",
- bucketStartTimeNs + bucketSizeNs - 2));
- events.push_back(
- CreateFinishScheduledJobEvent({CreateAttribution(444, "App3")}, "job3",
- bucketStartTimeNs + bucketSizeNs + 900));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 50));
- events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 110));
-
- events.push_back(CreateSyncStartEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + 300));
- events.push_back(CreateSyncEndEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + bucketSizeNs + 700));
- events.push_back(CreateSyncStartEvent(attributions2, "ReadDoc",
- bucketStartTimeNs + 400));
- events.push_back(CreateSyncEndEvent(attributions2, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs - 1));
-
- events.push_back(CreateSyncStartEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + 550));
- events.push_back(CreateSyncEndEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + 800));
- events.push_back(CreateSyncStartEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs - 1));
- events.push_back(CreateSyncEndEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs + 700));
-
- sortLogEventsByTimestamp(&events);
-
- for (const auto& event : events) {
- processor->OnLogEvent(event.get());
- }
-
- ConfigMetricsReportList reports;
- vector<uint8_t> buffer;
- processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false,
- true, ADB_DUMP, FAST, &buffer);
- EXPECT_TRUE(buffer.size() > 0);
- EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
- backfillDimensionPath(&reports);
- backfillStringInReport(&reports);
- backfillStartEndTimestamp(&reports);
-
- EXPECT_EQ(reports.reports_size(), 1);
- EXPECT_EQ(reports.reports(0).metrics_size(), 1);
- StatsLogReport::DurationMetricDataWrapper metrics;
- sortMetricDataByDimensionsValue(
- reports.reports(0).metrics(0).duration_metrics(), &metrics);
-
- if (aggregationType == DurationMetric::SUM) {
- EXPECT_EQ(metrics.data_size(), 3);
- auto data = metrics.data(0);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 111);
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 101 - 50);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
-
- data = metrics.data(1);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 333);
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 300 + bucketSizeNs - 600);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 700);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(2);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 444);
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 700);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- } else {
- EXPECT_EQ(metrics.data_size(), 3);
- auto data = metrics.data(0);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 111);
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 101 - 50);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
-
- data = metrics.data(1);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 333);
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 300);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), bucketSizeNs - 600 + 700);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(2);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 444);
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 701);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- }
- }
- }
-}
-
-namespace {
-
-StatsdConfig createDurationMetric_PartialLink_SimpleConditionConfig(
- DurationMetric::AggregationType aggregationType) {
- StatsdConfig config;
- config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
- *config.add_atom_matcher() = CreateStartScheduledJobAtomMatcher();
- *config.add_atom_matcher() = CreateFinishScheduledJobAtomMatcher();
- *config.add_atom_matcher() = CreateSyncStartAtomMatcher();
- *config.add_atom_matcher() = CreateSyncEndAtomMatcher();
-
- auto scheduledJobPredicate = CreateScheduledJobPredicate();
- auto dimensions = scheduledJobPredicate.mutable_simple_predicate()->mutable_dimensions();
- *dimensions = CreateAttributionUidDimensions(
- android::util::SCHEDULED_JOB_STATE_CHANGED, {Position::FIRST});
- dimensions->add_child()->set_field(2); // job name field.
-
- auto isSyncingPredicate = CreateIsSyncingPredicate();
- auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
- *syncDimension = CreateAttributionUidDimensions(
- android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- syncDimension->add_child()->set_field(2 /* name field*/);
-
- *config.add_predicate() = scheduledJobPredicate;
- *config.add_predicate() = isSyncingPredicate;
-
- auto metric = config.add_duration_metric();
- metric->set_bucket(FIVE_MINUTES);
- metric->set_id(StringToId("scheduledJob"));
- metric->set_what(scheduledJobPredicate.id());
- metric->set_condition(isSyncingPredicate.id());
- metric->set_aggregation_type(aggregationType);
- *metric->mutable_dimensions_in_what() = CreateAttributionUidDimensions(
- android::util::SCHEDULED_JOB_STATE_CHANGED, {Position::FIRST});
- *metric->mutable_dimensions_in_condition() = *syncDimension;
-
- auto links = metric->add_links();
- links->set_condition(isSyncingPredicate.id());
- *links->mutable_fields_in_what() =
- CreateAttributionUidDimensions(
- android::util::SCHEDULED_JOB_STATE_CHANGED, {Position::FIRST});
- *links->mutable_fields_in_condition() =
- CreateAttributionUidDimensions(android::util::SYNC_STATE_CHANGED, {Position::FIRST});
- return config;
-}
-
-} // namespace
-
-TEST(DimensionInConditionE2eTest, TestDurationMetric_PartialLink_SimpleCondition) {
- for (auto aggregationType : {DurationMetric::SUM, DurationMetric::MAX_SPARSE}) {
- ConfigKey cfgKey;
- auto config = createDurationMetric_PartialLink_SimpleConditionConfig(
- aggregationType);
- int64_t bucketStartTimeNs = 10000000000;
- int64_t bucketSizeNs =
- TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
-
- auto processor = CreateStatsLogProcessor(
- bucketStartTimeNs, bucketStartTimeNs, config, cfgKey);
- EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
- EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
-
- std::vector<AttributionNodeInternal> attributions1 = {
- CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(222, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions2 = {
- CreateAttribution(333, "App2"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<AttributionNodeInternal> attributions3 = {
- CreateAttribution(444, "App3"), CreateAttribution(222, "GMSCoreModule1"),
- CreateAttribution(555, "GMSCoreModule2")};
-
- std::vector<std::unique_ptr<LogEvent>> events;
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(111, "App1")}, "job1", bucketStartTimeNs + 1));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(111, "App1")}, "job1",bucketStartTimeNs + 101));
-
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2", bucketStartTimeNs + 201));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2",bucketStartTimeNs + 500));
- events.push_back(CreateStartScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2", bucketStartTimeNs + 600));
- events.push_back(CreateFinishScheduledJobEvent(
- {CreateAttribution(333, "App2")}, "job2", bucketStartTimeNs + bucketSizeNs + 850));
-
- events.push_back(
- CreateStartScheduledJobEvent({CreateAttribution(444, "App3")}, "job3",
- bucketStartTimeNs + bucketSizeNs - 2));
- events.push_back(
- CreateFinishScheduledJobEvent({CreateAttribution(444, "App3")}, "job3",
- bucketStartTimeNs + bucketSizeNs + 900));
-
- events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 50));
- events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
- bucketStartTimeNs + 110));
-
- events.push_back(CreateSyncStartEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + 300));
- events.push_back(CreateSyncEndEvent(attributions2, "ReadEmail",
- bucketStartTimeNs + bucketSizeNs + 700));
- events.push_back(CreateSyncStartEvent(attributions2, "ReadDoc",
- bucketStartTimeNs + 400));
- events.push_back(CreateSyncEndEvent(attributions2, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs - 1));
-
- events.push_back(CreateSyncStartEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + 550));
- events.push_back(CreateSyncEndEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + 800));
- events.push_back(CreateSyncStartEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs - 1));
- events.push_back(CreateSyncEndEvent(attributions3, "ReadDoc",
- bucketStartTimeNs + bucketSizeNs + 700));
-
- sortLogEventsByTimestamp(&events);
-
- for (const auto& event : events) {
- processor->OnLogEvent(event.get());
- }
-
- ConfigMetricsReportList reports;
- vector<uint8_t> buffer;
- processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, false, true,
- ADB_DUMP, FAST, &buffer);
- EXPECT_TRUE(buffer.size() > 0);
- EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
- backfillDimensionPath(&reports);
- backfillStringInReport(&reports);
- backfillStartEndTimestamp(&reports);
-
- EXPECT_EQ(reports.reports_size(), 1);
- EXPECT_EQ(reports.reports(0).metrics_size(), 1);
- StatsLogReport::DurationMetricDataWrapper metrics;
- sortMetricDataByDimensionsValue(
- reports.reports(0).metrics(0).duration_metrics(), &metrics);
-
- if (aggregationType == DurationMetric::SUM) {
- EXPECT_EQ(4, metrics.data_size());
- auto data = metrics.data(0);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 111);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 111);
- EXPECT_EQ("ReadEmail",
- data.dimensions_in_condition().value_tuple().dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 101 - 50);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
-
- data = metrics.data(1);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 333);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 333);
- EXPECT_EQ("ReadDoc",
- data.dimensions_in_condition().value_tuple().dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), bucketSizeNs - 1 - 400 - 100);
-
- data = metrics.data(2);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 333);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 333);
- EXPECT_EQ("ReadEmail",
- data.dimensions_in_condition().value_tuple().dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 300 + bucketSizeNs - 600);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 700);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(3);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 444);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 444);
- EXPECT_EQ("ReadDoc",
- data.dimensions_in_condition().value_tuple().dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 1);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), 700);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- } else {
- EXPECT_EQ(metrics.data_size(), 4);
- auto data = metrics.data(0);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 111);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 111);
- EXPECT_EQ("ReadEmail",
- data.dimensions_in_condition().value_tuple().dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 101 - 50);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
-
- data = metrics.data(1);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 333);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 333);
- EXPECT_EQ("ReadDoc",
- data.dimensions_in_condition().value_tuple().dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 100);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), bucketSizeNs - 1 - 600);
-
- data = metrics.data(2);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 333);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 333);
- EXPECT_EQ("ReadEmail",
- data.dimensions_in_condition().value_tuple().dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 2);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(), bucketStartTimeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 300);
- EXPECT_EQ(data.bucket_info(1).duration_nanos(), bucketSizeNs - 600 + 700);
- EXPECT_EQ(data.bucket_info(1).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(1).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
-
- data = metrics.data(3);
- ValidateAttributionUidDimension(
- data.dimensions_in_what(), android::util::SCHEDULED_JOB_STATE_CHANGED, 444);
- ValidateAttributionUidDimension(
- data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 444);
- EXPECT_EQ("ReadDoc",
- data.dimensions_in_condition().value_tuple().dimensions_value(1).value_str());
- EXPECT_EQ(data.bucket_info_size(), 1);
- EXPECT_EQ(data.bucket_info(0).duration_nanos(), 701);
- EXPECT_EQ(data.bucket_info(0).start_bucket_elapsed_nanos(),
- bucketStartTimeNs + bucketSizeNs);
- EXPECT_EQ(data.bucket_info(0).end_bucket_elapsed_nanos(),
- bucketStartTimeNs + 2 * bucketSizeNs);
- }
- }
-}
-
-#else
-GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif
-
-} // namespace statsd
-} // namespace os
-} // namespace android
diff --git a/cmds/statsd/tests/external/GpuStatsPuller_test.cpp b/cmds/statsd/tests/external/GpuStatsPuller_test.cpp
index bdc52b0af34c..e91fb0d4b27c 100644
--- a/cmds/statsd/tests/external/GpuStatsPuller_test.cpp
+++ b/cmds/statsd/tests/external/GpuStatsPuller_test.cpp
@@ -56,8 +56,9 @@ static const int32_t VULKAN_VERSION = 1;
static const int32_t CPU_VULKAN_VERSION = 2;
static const int32_t GLES_VERSION = 3;
static const bool CPU_VULKAN_IN_USE = true;
+static const bool FALSE_PREROTATION = true;
static const size_t NUMBER_OF_VALUES_GLOBAL = 13;
-static const size_t NUMBER_OF_VALUES_APP = 6;
+static const size_t NUMBER_OF_VALUES_APP = 7;
// clang-format on
class MockGpuStatsPuller : public GpuStatsPuller {
@@ -150,6 +151,7 @@ TEST_F(GpuStatsPuller_test, PullGpuStatsAppInfo) {
EXPECT_TRUE(event->write(int64VectorToProtoByteString(vkDriverLoadingTime)));
EXPECT_TRUE(event->write(int64VectorToProtoByteString(angleDriverLoadingTime)));
EXPECT_TRUE(event->write(CPU_VULKAN_IN_USE));
+ EXPECT_TRUE(event->write(FALSE_PREROTATION));
event->init();
inData.emplace_back(event);
MockGpuStatsPuller mockPuller(android::util::GPU_STATS_APP_INFO, &inData);
@@ -168,6 +170,7 @@ TEST_F(GpuStatsPuller_test, PullGpuStatsAppInfo) {
EXPECT_EQ(int64VectorToProtoByteString(angleDriverLoadingTime),
outData[0]->getValues()[4].mValue.str_value);
EXPECT_EQ(CPU_VULKAN_IN_USE, outData[0]->getValues()[5].mValue.int_value);
+ EXPECT_EQ(FALSE_PREROTATION, outData[0]->getValues()[6].mValue.int_value);
}
} // namespace statsd
diff --git a/cmds/statsd/tests/metrics/CountMetricProducer_test.cpp b/cmds/statsd/tests/metrics/CountMetricProducer_test.cpp
index 67c704eb87fd..839daa4b7f8a 100644
--- a/cmds/statsd/tests/metrics/CountMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/CountMetricProducer_test.cpp
@@ -187,9 +187,9 @@ TEST(CountMetricProducerTest, TestEventsWithSlicedCondition) {
{getMockedDimensionKey(conditionTagId, 2, "222")};
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- EXPECT_CALL(*wizard, query(_, key1, _, _, _, _)).WillOnce(Return(ConditionState::kFalse));
+ EXPECT_CALL(*wizard, query(_, key1, _)).WillOnce(Return(ConditionState::kFalse));
- EXPECT_CALL(*wizard, query(_, key2, _, _, _, _)).WillOnce(Return(ConditionState::kTrue));
+ EXPECT_CALL(*wizard, query(_, key2, _)).WillOnce(Return(ConditionState::kTrue));
CountMetricProducer countProducer(kConfigKey, metric, 1 /*condition tracker index*/, wizard,
bucketStartTimeNs, bucketStartTimeNs);
diff --git a/cmds/statsd/tests/metrics/EventMetricProducer_test.cpp b/cmds/statsd/tests/metrics/EventMetricProducer_test.cpp
index d2fd95c818cf..f30873b92afc 100644
--- a/cmds/statsd/tests/metrics/EventMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/EventMetricProducer_test.cpp
@@ -113,9 +113,9 @@ TEST(EventMetricProducerTest, TestEventsWithSlicedCondition) {
key2[StringToId("APP_IN_BACKGROUND_PER_UID")] = {getMockedDimensionKey(conditionTagId, 2, "222")};
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- EXPECT_CALL(*wizard, query(_, key1, _, _, _, _)).WillOnce(Return(ConditionState::kFalse));
+ EXPECT_CALL(*wizard, query(_, key1, _)).WillOnce(Return(ConditionState::kFalse));
- EXPECT_CALL(*wizard, query(_, key2, _, _, _, _)).WillOnce(Return(ConditionState::kTrue));
+ EXPECT_CALL(*wizard, query(_, key2, _)).WillOnce(Return(ConditionState::kTrue));
EventMetricProducer eventProducer(kConfigKey, metric, 1, wizard, bucketStartTimeNs);
diff --git a/cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp b/cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp
index b9553a8fded8..47c21aa8f1df 100644
--- a/cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp
@@ -485,10 +485,6 @@ TEST(GaugeMetricProducerTest, TestPulledEventsWithSlicedCondition) {
dim->set_field(tagId);
dim->add_child()->set_field(1);
- dim = metric.mutable_dimensions_in_condition();
- dim->set_field(conditionTag);
- dim->add_child()->set_field(1);
-
UidMap uidMap;
SimpleAtomMatcher atomMatcher;
atomMatcher.set_atom_id(tagId);
@@ -496,18 +492,14 @@ TEST(GaugeMetricProducerTest, TestPulledEventsWithSlicedCondition) {
new SimpleLogMatchingTracker(atomMatcherId, logEventMatcherIndex, atomMatcher, uidMap)});
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- EXPECT_CALL(*wizard, query(_, _, _, _, _, _))
+ EXPECT_CALL(*wizard, query(_, _, _))
.WillRepeatedly(
Invoke([](const int conditionIndex, const ConditionKey& conditionParameters,
- const vector<Matcher>& dimensionFields, const bool isSubsetDim,
- const bool isPartialLink,
- std::unordered_set<HashableDimensionKey>* dimensionKeySet) {
- dimensionKeySet->clear();
+ const bool isPartialLink) {
int pos[] = {1, 0, 0};
Field f(conditionTag, pos, 0);
HashableDimensionKey key;
key.mutableValues()->emplace_back(f, Value((int32_t)1000000));
- dimensionKeySet->insert(key);
return ConditionState::kTrue;
}));
@@ -538,9 +530,6 @@ TEST(GaugeMetricProducerTest, TestPulledEventsWithSlicedCondition) {
EXPECT_EQ(1UL, key.getDimensionKeyInWhat().getValues().size());
EXPECT_EQ(1000, key.getDimensionKeyInWhat().getValues()[0].mValue.int_value);
- EXPECT_EQ(1UL, key.getDimensionKeyInCondition().getValues().size());
- EXPECT_EQ(1000000, key.getDimensionKeyInCondition().getValues()[0].mValue.int_value);
-
EXPECT_EQ(0UL, gaugeProducer.mPastBuckets.size());
vector<shared_ptr<LogEvent>> allData;
diff --git a/cmds/statsd/tests/metrics/MaxDurationTracker_test.cpp b/cmds/statsd/tests/metrics/MaxDurationTracker_test.cpp
index bf047520cc77..100220b730d7 100644
--- a/cmds/statsd/tests/metrics/MaxDurationTracker_test.cpp
+++ b/cmds/statsd/tests/metrics/MaxDurationTracker_test.cpp
@@ -52,7 +52,6 @@ TEST(MaxDurationTrackerTest, TestSimpleMaxDuration) {
const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
@@ -63,7 +62,7 @@ TEST(MaxDurationTrackerTest, TestSimpleMaxDuration) {
int64_t bucketNum = 0;
int64_t metricId = 1;
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, dimensionInCondition,
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1,
false, bucketStartTimeNs, bucketNum, bucketStartTimeNs, bucketSizeNs,
false, false, {});
@@ -88,7 +87,6 @@ TEST(MaxDurationTrackerTest, TestStopAll) {
const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
@@ -99,7 +97,7 @@ TEST(MaxDurationTrackerTest, TestStopAll) {
int64_t bucketNum = 0;
int64_t metricId = 1;
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, dimensionInCondition,
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1,
false, bucketStartTimeNs, bucketNum, bucketStartTimeNs, bucketSizeNs,
false, false, {});
@@ -124,7 +122,6 @@ TEST(MaxDurationTrackerTest, TestCrossBucketBoundary) {
const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
@@ -135,7 +132,7 @@ TEST(MaxDurationTrackerTest, TestCrossBucketBoundary) {
int64_t bucketNum = 0;
int64_t metricId = 1;
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, dimensionInCondition,
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1,
false, bucketStartTimeNs, bucketNum, bucketStartTimeNs, bucketSizeNs,
false, false, {});
@@ -165,7 +162,6 @@ TEST(MaxDurationTrackerTest, TestCrossBucketBoundary_nested) {
const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
@@ -176,7 +172,7 @@ TEST(MaxDurationTrackerTest, TestCrossBucketBoundary_nested) {
int64_t bucketNum = 0;
int64_t metricId = 1;
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, dimensionInCondition,
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1,
true, bucketStartTimeNs, bucketNum, bucketStartTimeNs, bucketSizeNs,
false, false, {});
@@ -202,7 +198,6 @@ TEST(MaxDurationTrackerTest, TestCrossBucketBoundary_nested) {
TEST(MaxDurationTrackerTest, TestMaxDurationWithCondition) {
const HashableDimensionKey conditionDimKey = key1;
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
ConditionKey conditionKey1;
@@ -223,7 +218,7 @@ TEST(MaxDurationTrackerTest, TestMaxDurationWithCondition) {
int64_t eventStopTimeNs = conditionStops2 + 8 * NS_PER_SEC;
int64_t metricId = 1;
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
false, bucketStartTimeNs, 0, bucketStartTimeNs, bucketSizeNs, true,
false, {});
EXPECT_TRUE(tracker.mAnomalyTrackers.empty());
@@ -246,7 +241,6 @@ TEST(MaxDurationTrackerTest, TestMaxDurationWithCondition) {
}
TEST(MaxDurationTrackerTest, TestAnomalyDetection) {
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
ConditionKey conditionKey1;
@@ -273,7 +267,7 @@ TEST(MaxDurationTrackerTest, TestAnomalyDetection) {
sp<AlarmMonitor> alarmMonitor;
sp<DurationAnomalyTracker> anomalyTracker =
new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
false, bucketStartTimeNs, bucketNum, bucketStartTimeNs, bucketSizeNs,
true, false, {anomalyTracker});
@@ -295,7 +289,6 @@ TEST(MaxDurationTrackerTest, TestAnomalyDetection) {
// This tests that we correctly compute the predicted time of an anomaly assuming that the current
// state continues forward as-is.
TEST(MaxDurationTrackerTest, TestAnomalyPredictedTimestamp) {
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
ConditionKey conditionKey1;
@@ -333,7 +326,7 @@ TEST(MaxDurationTrackerTest, TestAnomalyPredictedTimestamp) {
sp<AlarmMonitor> alarmMonitor;
sp<DurationAnomalyTracker> anomalyTracker =
new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
false, bucketStartTimeNs, bucketNum, bucketStartTimeNs, bucketSizeNs,
true, false, {anomalyTracker});
@@ -381,7 +374,6 @@ TEST(MaxDurationTrackerTest, TestAnomalyPredictedTimestamp) {
// Suppose A starts, then B starts, and then A stops. We still need to set an anomaly based on the
// elapsed duration of B.
TEST(MaxDurationTrackerTest, TestAnomalyPredictedTimestamp_UpdatedOnStop) {
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
ConditionKey conditionKey1;
@@ -416,7 +408,7 @@ TEST(MaxDurationTrackerTest, TestAnomalyPredictedTimestamp_UpdatedOnStop) {
sp<AlarmMonitor> alarmMonitor;
sp<DurationAnomalyTracker> anomalyTracker =
new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
false, bucketStartTimeNs, bucketNum, bucketStartTimeNs, bucketSizeNs,
true, false, {anomalyTracker});
@@ -434,4 +426,4 @@ TEST(MaxDurationTrackerTest, TestAnomalyPredictedTimestamp_UpdatedOnStop) {
} // namespace android
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif \ No newline at end of file
+#endif
diff --git a/cmds/statsd/tests/metrics/OringDurationTracker_test.cpp b/cmds/statsd/tests/metrics/OringDurationTracker_test.cpp
index 7c2b4236add8..1cd7bdbf7bb0 100644
--- a/cmds/statsd/tests/metrics/OringDurationTracker_test.cpp
+++ b/cmds/statsd/tests/metrics/OringDurationTracker_test.cpp
@@ -51,7 +51,6 @@ TEST(OringDurationTrackerTest, TestDurationOverlap) {
const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
@@ -62,7 +61,7 @@ TEST(OringDurationTrackerTest, TestDurationOverlap) {
int64_t eventStartTimeNs = bucketStartTimeNs + 1;
int64_t durationTimeNs = 2 * 1000;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
false, bucketStartTimeNs, bucketNum, bucketStartTimeNs,
bucketSizeNs, false, false, {});
@@ -84,7 +83,6 @@ TEST(OringDurationTrackerTest, TestDurationNested) {
const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
@@ -94,7 +92,7 @@ TEST(OringDurationTrackerTest, TestDurationNested) {
int64_t bucketNum = 0;
int64_t eventStartTimeNs = bucketStartTimeNs + 1;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
true, bucketStartTimeNs, bucketNum, bucketStartTimeNs,
bucketSizeNs, false, false, {});
@@ -117,7 +115,6 @@ TEST(OringDurationTrackerTest, TestStopAll) {
{getMockedDimensionKey(TagId, 1, "maps")};
const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
@@ -127,7 +124,7 @@ TEST(OringDurationTrackerTest, TestStopAll) {
int64_t bucketNum = 0;
int64_t eventStartTimeNs = bucketStartTimeNs + 1;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
true, bucketStartTimeNs, bucketNum, bucketStartTimeNs,
bucketSizeNs, false, false, {});
@@ -147,7 +144,6 @@ TEST(OringDurationTrackerTest, TestCrossBucketBoundary) {
const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
@@ -158,7 +154,7 @@ TEST(OringDurationTrackerTest, TestCrossBucketBoundary) {
int64_t eventStartTimeNs = bucketStartTimeNs + 1;
int64_t durationTimeNs = 2 * 1000;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
true, bucketStartTimeNs, bucketNum, bucketStartTimeNs,
bucketSizeNs, false, false, {});
@@ -186,13 +182,12 @@ TEST(OringDurationTrackerTest, TestDurationConditionChange) {
const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
ConditionKey key1;
key1[StringToId("APP_BACKGROUND")] = kConditionKey1;
- EXPECT_CALL(*wizard, query(_, key1, _, _, _, _)) // #4
+ EXPECT_CALL(*wizard, query(_, key1, _)) // #4
.WillOnce(Return(ConditionState::kFalse));
unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
@@ -203,7 +198,7 @@ TEST(OringDurationTrackerTest, TestDurationConditionChange) {
int64_t eventStartTimeNs = bucketStartTimeNs + 1;
int64_t durationTimeNs = 2 * 1000;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
false, bucketStartTimeNs, bucketNum, bucketStartTimeNs,
bucketSizeNs, true, false, {});
@@ -224,13 +219,12 @@ TEST(OringDurationTrackerTest, TestDurationConditionChange2) {
const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
ConditionKey key1;
key1[StringToId("APP_BACKGROUND")] = kConditionKey1;
- EXPECT_CALL(*wizard, query(_, key1, _, _, _, _))
+ EXPECT_CALL(*wizard, query(_, key1, _))
.Times(2)
.WillOnce(Return(ConditionState::kFalse))
.WillOnce(Return(ConditionState::kTrue));
@@ -243,7 +237,7 @@ TEST(OringDurationTrackerTest, TestDurationConditionChange2) {
int64_t eventStartTimeNs = bucketStartTimeNs + 1;
int64_t durationTimeNs = 2 * 1000;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
false, bucketStartTimeNs, bucketNum, bucketStartTimeNs,
bucketSizeNs, true, false, {});
@@ -266,13 +260,12 @@ TEST(OringDurationTrackerTest, TestDurationConditionChangeNested) {
const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
- vector<Matcher> dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
ConditionKey key1;
key1[StringToId("APP_BACKGROUND")] = kConditionKey1;
- EXPECT_CALL(*wizard, query(_, key1, _, _, _, _)) // #4
+ EXPECT_CALL(*wizard, query(_, key1, _)) // #4
.WillOnce(Return(ConditionState::kFalse));
unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
@@ -282,7 +275,7 @@ TEST(OringDurationTrackerTest, TestDurationConditionChangeNested) {
int64_t bucketNum = 0;
int64_t eventStartTimeNs = bucketStartTimeNs + 1;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
true, bucketStartTimeNs, bucketNum, bucketStartTimeNs,
bucketSizeNs, true, false, {});
@@ -306,7 +299,6 @@ TEST(OringDurationTrackerTest, TestPredictAnomalyTimestamp) {
const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
- vector<Matcher> dimensionInCondition;
Alert alert;
alert.set_id(101);
alert.set_metric_id(1);
@@ -324,7 +316,7 @@ TEST(OringDurationTrackerTest, TestPredictAnomalyTimestamp) {
sp<AlarmMonitor> alarmMonitor;
sp<DurationAnomalyTracker> anomalyTracker =
new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
true, bucketStartTimeNs, bucketNum, bucketStartTimeNs,
bucketSizeNs, true, false, {anomalyTracker});
@@ -371,7 +363,6 @@ TEST(OringDurationTrackerTest, TestPredictAnomalyTimestamp) {
}
TEST(OringDurationTrackerTest, TestPredictAnomalyTimestamp2) {
- vector<Matcher> dimensionInCondition;
Alert alert;
alert.set_id(101);
alert.set_metric_id(1);
@@ -387,7 +378,7 @@ TEST(OringDurationTrackerTest, TestPredictAnomalyTimestamp2) {
sp<DurationAnomalyTracker> anomalyTracker =
new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
OringDurationTracker tracker(kConfigKey, metricId, DEFAULT_METRIC_DIMENSION_KEY, wizard, 1,
- dimensionInCondition,
+
true, bucketStartTimeNs, bucketNum, bucketStartTimeNs,
bucketSizeNs, true, false, {anomalyTracker});
@@ -415,7 +406,7 @@ TEST(OringDurationTrackerTest, TestPredictAnomalyTimestamp3) {
for (int j = 0; j < 3; j++) {
int64_t thresholdNs = j * bucketSizeNs + 5 * NS_PER_SEC;
for (int i = 0; i <= 7; ++i) {
- vector<Matcher> dimensionInCondition;
+
Alert alert;
alert.set_id(101);
alert.set_metric_id(1);
@@ -432,7 +423,7 @@ TEST(OringDurationTrackerTest, TestPredictAnomalyTimestamp3) {
sp<DurationAnomalyTracker> anomalyTracker =
new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
OringDurationTracker tracker(kConfigKey, metricId, DEFAULT_METRIC_DIMENSION_KEY,
- wizard, 1, dimensionInCondition,
+ wizard, 1,
true, bucketStartTimeNs, bucketNum, bucketStartTimeNs,
bucketSizeNs, true, false, {anomalyTracker});
@@ -472,7 +463,6 @@ TEST(OringDurationTrackerTest, TestAnomalyDetectionExpiredAlarm) {
const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
- vector<Matcher> dimensionInCondition;
Alert alert;
alert.set_id(101);
alert.set_metric_id(1);
@@ -491,7 +481,7 @@ TEST(OringDurationTrackerTest, TestAnomalyDetectionExpiredAlarm) {
sp<AlarmMonitor> alarmMonitor;
sp<DurationAnomalyTracker> anomalyTracker =
new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
true /*nesting*/, bucketStartTimeNs, bucketNum, bucketStartTimeNs,
bucketSizeNs, false, false, {anomalyTracker});
@@ -522,7 +512,6 @@ TEST(OringDurationTrackerTest, TestAnomalyDetectionFiredAlarm) {
const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
- vector<Matcher> dimensionInCondition;
Alert alert;
alert.set_id(101);
alert.set_metric_id(1);
@@ -541,7 +530,7 @@ TEST(OringDurationTrackerTest, TestAnomalyDetectionFiredAlarm) {
sp<AlarmMonitor> alarmMonitor;
sp<DurationAnomalyTracker> anomalyTracker =
new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1,
true /*nesting*/, bucketStartTimeNs, 0, bucketStartTimeNs,
bucketSizeNs, false, false, {anomalyTracker});
@@ -589,4 +578,4 @@ TEST(OringDurationTrackerTest, TestAnomalyDetectionFiredAlarm) {
} // namespace android
#else
GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif \ No newline at end of file
+#endif
diff --git a/cmds/statsd/tests/metrics/metrics_test_helper.h b/cmds/statsd/tests/metrics/metrics_test_helper.h
index 97c107228f9c..329e39fc4eff 100644
--- a/cmds/statsd/tests/metrics/metrics_test_helper.h
+++ b/cmds/statsd/tests/metrics/metrics_test_helper.h
@@ -26,11 +26,9 @@ namespace statsd {
class MockConditionWizard : public ConditionWizard {
public:
- MOCK_METHOD6(query,
+ MOCK_METHOD3(query,
ConditionState(const int conditionIndex, const ConditionKey& conditionParameters,
- const vector<Matcher>& dimensionFields,
- const bool isSubsetDim, const bool isPartialLink,
- std::unordered_set<HashableDimensionKey>* dimensionKeySet));
+ const bool isPartialLink));
};
class MockStatsPullerManager : public StatsPullerManager {
@@ -55,4 +53,4 @@ void buildSimpleAtomFieldMatcher(const int tagId, FieldMatcher* matcher);
} // namespace statsd
} // namespace os
-} // namespace android \ No newline at end of file
+} // namespace android
diff --git a/cmds/statsd/tools/dogfood/Android.bp b/cmds/statsd/tools/dogfood/Android.bp
deleted file mode 100644
index bb494a6025af..000000000000
--- a/cmds/statsd/tools/dogfood/Android.bp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (C) 2017 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//
-
-android_app {
- name: "StatsdDogfood",
- platform_apis: true,
-
- srcs: ["src/**/*.java"],
-
- resource_dirs: ["res"],
- static_libs: [
- "platformprotoslite",
- "statsdprotolite",
- ],
-
- privileged: true,
- dex_preopt: {
- enabled: false,
- },
- certificate: "platform",
- optimize: {
- enabled: false,
- },
-}
diff --git a/cmds/statsd/tools/dogfood/AndroidManifest.xml b/cmds/statsd/tools/dogfood/AndroidManifest.xml
deleted file mode 100644
index 52673fbdcf92..000000000000
--- a/cmds/statsd/tools/dogfood/AndroidManifest.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-** http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
--->
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.statsd.dogfood"
- android:sharedUserId="android.uid.system"
- android:versionCode="1"
- android:versionName="1.0" >
-
- <uses-permission android:name="android.permission.DUMP" />
-
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name" >
- <activity
- android:name=".MainActivity"
- android:label="@string/app_name"
- android:launchMode="singleTop" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
-
- <service android:name=".MainActivity$ReceiverIntentService" android:exported="true" />
- </application>
-</manifest>
diff --git a/cmds/statsd/tools/dogfood/res/drawable-hdpi/ic_launcher.png b/cmds/statsd/tools/dogfood/res/drawable-hdpi/ic_launcher.png
deleted file mode 100644
index 55621cc1074f..000000000000
--- a/cmds/statsd/tools/dogfood/res/drawable-hdpi/ic_launcher.png
+++ /dev/null
Binary files differ
diff --git a/cmds/statsd/tools/dogfood/res/drawable-mdpi/ic_launcher.png b/cmds/statsd/tools/dogfood/res/drawable-mdpi/ic_launcher.png
deleted file mode 100644
index 11ec2068be19..000000000000
--- a/cmds/statsd/tools/dogfood/res/drawable-mdpi/ic_launcher.png
+++ /dev/null
Binary files differ
diff --git a/cmds/statsd/tools/dogfood/res/drawable-xhdpi/ic_launcher.png b/cmds/statsd/tools/dogfood/res/drawable-xhdpi/ic_launcher.png
deleted file mode 100644
index 7c02b784aa5d..000000000000
--- a/cmds/statsd/tools/dogfood/res/drawable-xhdpi/ic_launcher.png
+++ /dev/null
Binary files differ
diff --git a/cmds/statsd/tools/dogfood/res/drawable-xxhdpi/ic_launcher.png b/cmds/statsd/tools/dogfood/res/drawable-xxhdpi/ic_launcher.png
deleted file mode 100644
index 915d91441349..000000000000
--- a/cmds/statsd/tools/dogfood/res/drawable-xxhdpi/ic_launcher.png
+++ /dev/null
Binary files differ
diff --git a/cmds/statsd/tools/dogfood/res/layout/activity_main.xml b/cmds/statsd/tools/dogfood/res/layout/activity_main.xml
deleted file mode 100644
index 784ed40ce2c2..000000000000
--- a/cmds/statsd/tools/dogfood/res/layout/activity_main.xml
+++ /dev/null
@@ -1,162 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-** http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
--->
-<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <Button
- android:id="@+id/push_config"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:background="@android:color/holo_green_light"
- android:text="@string/push_config"/>
- <Button
- android:id="@+id/set_receiver"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:background="@android:color/holo_green_light"
- android:text="@string/set_receiver"/>
- <Button
- android:id="@+id/remove_receiver"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:background="@android:color/holo_green_light"
- android:text="@string/remove_receiver"/>
-
- <LinearLayout android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
- <Button android:id="@+id/app_a_wake_lock_acquire1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/app_a_get_wl1"/>
- <Button android:id="@+id/app_a_wake_lock_release1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/app_a_release_wl1"/>
- </LinearLayout>
-
- <LinearLayout android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
- <Button android:id="@+id/app_a_wake_lock_acquire2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/app_a_get_wl2"/>
- <Button android:id="@+id/app_a_wake_lock_release2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/app_a_release_wl2"/>
- </LinearLayout>
-
- <LinearLayout android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
- <Button android:id="@+id/app_b_wake_lock_acquire1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/app_b_get_wl1"/>
- <Button android:id="@+id/app_b_wake_lock_release1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/app_b_release_wl1"/>
- </LinearLayout>
- <LinearLayout android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
- <Button android:id="@+id/app_b_wake_lock_acquire2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/app_b_get_wl2"/>
- <Button android:id="@+id/app_b_wake_lock_release2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/app_b_release_wl2"/>
- </LinearLayout>
-
- <LinearLayout android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
- <Button android:id="@+id/plug"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/plug"/>
-
- <Button android:id="@+id/unplug"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/unplug"/>
- </LinearLayout>
-
- <LinearLayout android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
- <Button android:id="@+id/screen_on"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/screen_on"/>
-
- <Button android:id="@+id/screen_off"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/screen_off"/>
- </LinearLayout>
-
- <LinearLayout android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
-
- <Button
- android:id="@+id/custom_start"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/custom_start" />
-
- <Button
- android:id="@+id/custom_stop"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/custom_stop" />
- </LinearLayout>
-
- <Button android:id="@+id/dump"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:background="@android:color/holo_purple"
- android:text="@string/dump"/>
-
- <TextView
- android:id="@+id/header"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/report_header"/>
-
- <TextView
- android:id="@+id/report_text"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
-
- </LinearLayout>
-
-</ScrollView> \ No newline at end of file
diff --git a/cmds/statsd/tools/dogfood/res/raw/statsd_baseline_config b/cmds/statsd/tools/dogfood/res/raw/statsd_baseline_config
deleted file mode 100644
index d05006124994..000000000000
--- a/cmds/statsd/tools/dogfood/res/raw/statsd_baseline_config
+++ /dev/null
@@ -1,109 +0,0 @@
-¹ÓõÕ¯¤”årÝèåâÕ»éÉ7¬ìŸ‘Ψê­.–´šÄÁŒç¶ÚšäÑùôºZªÑ€¸ëÐé­í‘˜‹Ý™ûÆŽ6ˆ™ÁÖ΂õ›Ã¥¼à¨É—ÿQÝàåÈ߀äÍ@ÆÙÑ„ÓІ„èѿ̲±™¨lŸÄ€ìúˆÖ­ü¶ú̳Šéâ‡ãà§ØÈË´Ù%ó­ÓÚ«¹¼ÜyÛ®±ë¸«”º?­¹•繡¸Œ€â鿨ŒÙœ®‘)çæ©Á”§äéîÀ‚Ò®ö‡.ÐÙ•°‹ÁÈy"'(WòóÀ–ðßæ¬ùÕàÀ™ýëZ”ÔÆ™Ž¤š¹»"
- (2!ûÄߪæþªâÚ 
-V¢¦€¡’€Ç€¡ùÕàÀ™ýëZÈ‹ÄÂë¢Ä¯Ø"
- (2 ª–¨Œ×ÿ¹¡k 
-V‡úÌòá㿘>ùÕàÀ™ýëZáž‹â‘Ý»ä"
- (2!÷‘–ä–Œ¿¯ 
-WØõé¼ÃóÀàþùÕàÀ™ýëZ°ÔØùΣ‘¯"
- (2!Ïä†÷ɯ 
-VÚœäÌþ½¬jùÕàÀ™ýëZ³Ö‰Ó¾ ½Ñ"
- (2!Ÿ¡ªˆëôùÇ 
-V¨¾ñ≎̅ùÕàÀ™ýëZ“Ðåÿèåò?"
- (2!½šòÐ䤿Œ 
-U…£²†µÜ‡‘_ùÕàÀ™ýëZñîôÒ‡¤´†z"
- (2!é’¬¸ç¼‡Óª 
-K‘ã´¶üÅçúñ±Ë壆¨D”ÔÆ™Ž¤š¹»"
-#(2ûÄߪæþªâÚ#Ië§ì·ºê•Æúñ±Ë壆¨DÈ‹ÄÂë¢Ä¯Ø"
-#(2ª–¨Œ×ÿ¹¡k#JÙ¢Öúƒ†ðúñ±Ë壆¨Dáž‹â‘Ý»ä"
-#(2÷‘–ä–Œ¿¯#JãýØåóªü)úñ±Ë壆¨D°ÔØùΣ‘¯"
-#(2Ïä†÷ɯ#KËÅÝÇž¹Åãúñ±Ë壆¨D³Ö‰Ó¾ ½Ñ"
-#(2Ÿ¡ªˆëôùÇ#Jɳ¸ó€„ø‘Ãúñ±Ë壆¨D“Ðåÿèåò?"
-#(2½šòÐ䤿Œ#J•–ó«ðô¤Þïúñ±Ë壆¨DñîôÒ‡¤´†z"
-#(2é’¬¸ç¼‡Óª#J•ºÔ¯•…Î’:›ºô¿Úó¾kŒÓÜ¢¾ÌÊ"
-(2ûÄߪæþªâÚI»ÓòÓí‰àÖ
-›ºô¿Úó¾kǮ›ŸÊŸäâ"
-(2ª–¨Œ×ÿ¹¡kJÖÐük÷y›ºô¿Úó¾kÿ‚¾žÃ“’§õ"
-(2÷‘–ä–Œ¿¯JøÿÊ“åøË¨›ºô¿Úó¾k˜ý˜‘¢ŒÐÀI"
-(2Ïä†÷ɯKõ­ß°—’ì¾×›ºô¿Úó¾kì‘áÒîŸÙÍá"
-(2Ÿ¡ªˆëôùÇJà¸ëòä¥û݈›ºô¿Úó¾kôé‹¿¿¸ßÄ"
-(2½šòÐ䤿ŒJУŒð†¬µÙ›ºô¿Úó¾k‰±Öйˆ–Ôõ"
-(2é’¬¸ç¼‡ÓªK—ÍË é÷ÐM鮣öü©µŒÓÜ¢¾ÌÊ"
-(2ûÄߪæþªâÚJÌŽë á«¡´{鮣öü©µǮ›ŸÊŸäâ"
-(2ª–¨Œ×ÿ¹¡kL˜†ŒÏØì¡‹³鮣öü©µÿ‚¾žÃ“’§õ"
-(2÷‘–ä–Œ¿¯Ká°Ñàƒ½†¶ý鮣öü©µ˜ý˜‘¢ŒÐÀI"
-(2Ïä†÷ɯKÛ”Ÿò§…ÂÁY鮣öü©µì‘áÒîŸÙÍá"
-(2Ÿ¡ªˆëôùÇKϜݗÞç±ù¥鮣öü©µôé‹¿¿¸ßÄ"
-(2½šòÐ䤿ŒKÚÖ•·‰­–B鮣öü©µ‰±Öйˆ–Ôõ"
-(2é’¬¸ç¼‡Óª,Ä®öèÀƒ‘âÌ¥•€†ÜÖ×AÐÙ•°‹ÁÈy"
-(€õ»•÷¾ÓçȪŠéñðȃŹ~”‰àÉ­®¶f"(2é’¬¸ç¼‡Óª2½šòÐ䤿Œ2Ÿ¡ªˆëôùÇLشͼá™þþæ¿É¶ˆœ‚æð±ûÄߪæþªâÚ"
--(2ûÄߪæþªâÚ-JÉ¥˜‘Ûüˆ‹ò¿É¶ˆœ‚æð±ª–¨Œ×ÿ¹¡k"
--(2ª–¨Œ×ÿ¹¡k-L¡©äÞ¨ô¶ø½¿É¶ˆœ‚æð±÷‘–ä–Œ¿¯"
--(2÷‘–ä–Œ¿¯-L‡õÇþ¡¾ÚÈþ¿É¶ˆœ‚æð±Ïä†÷ɯ"
--(2Ïä†÷ɯ-L—î«ãïÚ½û¬¿É¶ˆœ‚æð±Ÿ¡ªˆëôùÇ"
--(2Ÿ¡ªˆëôùÇ-LñÍý‚ÿô­¿É¶ˆœ‚æð±½šòÐ䤿Œ"
--(2½šòÐ䤿Œ-K‹òʰ«»íè|¿É¶ˆœ‚æð±é’¬¸ç¼‡Óª"
--(2é’¬¸ç¼‡Óª-"9äëæÚòœ§=̨…¥”ìãÏ‘N ÐÙ•°‹ÁÈy* ‘N0@":­šˆž‚έñÐ̨…¥”ìãÏ‘N ÐÙ•°‹ÁÈy* ‘N0@":ù»Žôç¾ãˆÐ̨…¥”ìãÏ‘N ÐÙ•°‹ÁÈy* ‘N0@"9›™›ŸÝ†—ãS̨…¥”ìãÏ‘N ÐÙ•°‹ÁÈy* ‘N0@":‹ããùŸáŽôºßñ¼ûÌ•˜“N ÐÙ•°‹ÁÈy* “N0@":ç΀àë Œƒôºßñ¼ûÌ•˜“N ÐÙ•°‹ÁÈy* “N0@":™˜µøÖ²Äìõôºßñ¼ûÌ•˜“N ÐÙ•°‹ÁÈy* “N0@":¬Öœ¥¥ÃÆŒÑôºßñ¼ûÌ•˜“N ÐÙ•°‹ÁÈy* “N0@"5ôÇ™±¶Ï¢‘ò•™ÔéŠñ˜Èu›N ÐÙ•°‹ÁÈy*›N0@"4«÷µÿ󲂜e•™ÔéŠñ˜Èu›N ÐÙ•°‹ÁÈy*›N0@"4å¢úˆÑÙúý•™ÔéŠñ˜Èu›N ÐÙ•°‹ÁÈy*›N0@"+ž—Õõ‰î¶±~‡î‚ÒÔÊ´ËœN ÐÙ•°‹ÁÈy0@",‘ó‚³ïÙù¦‚‡î‚ÒÔÊ´ËœN ÐÙ•°‹ÁÈy0@"+òßù¥·«Äà;‡î‚ÒÔÊ´ËœN ÐÙ•°‹ÁÈy0@",ÓûÅñÒ¢ô§Â‡î‚ÒÔÊ´ËœN ÐÙ•°‹ÁÈy0@"+¨²°žò³ƒ¨R‡î‚ÒÔÊ´ËœN ÐÙ•°‹ÁÈy0@"+ÞìøݱþÖq‡î‚ÒÔÊ´ËœN ÐÙ•°‹ÁÈy0@",͉šæÜ­ŽÄÀ‡î‚ÒÔÊ´ËœN ÐÙ•°‹ÁÈy0@"3Ä»±ê¾¸ô°˜þËÉÇåãÃ2 ÐÙ•°‹ÁÈy*0@"‰ѽËñɤ¡™a˜þËÉÇåãÃ2 ”‰àÉ­®¶f*0:é’¬¸ç¼‡Óª:½šòÐ䤿Œ:Ÿ¡ªˆëôùÇ@":ÃêåÒýéó¦ï‘ŽÁ°×ËÇÅß–N ÐÙ•°‹ÁÈy* –N0@":Àš‚ÑÀí£Ï‹‘ŽÁ°×ËÇÅß–N ÐÙ•°‹ÁÈy* –N0@"9¾¢ðÛßÒëéø›²Ö·ÔÈšN ÐÙ•°‹ÁÈy* šN0@"9÷´ç鼯Š~½ ¤„¹®Ð§¨˜N ÐÙ•°‹ÁÈy* ˜N0@2YÝæÆËò ‚ú‘»óÓ¤ãËÕ”ÔÆ™Ž¤š¹»"!ûÄߪæþªâÚ 
-(2
- 82X°öòΪáŠþ„»óÓ¤ãËÕÈ‹ÄÂë¢Ä¯Ø" ª–¨Œ×ÿ¹¡k 
-(2
- 82X°ç¦ùºŒó·0»óÓ¤ãËÕáž‹â‘Ý»ä"!÷‘–ä–Œ¿¯ 
-(2
- 82Yôæï°Þ¼  ”»óÓ¤ãËÕ°ÔØùΣ‘¯"!Ïä†÷ɯ 
-(2
- 82Y¡Î°Ãåüý»óÓ¤ãËÕ³Ö‰Ó¾ ½Ñ"!Ÿ¡ªˆëôùÇ 
-(2
- 82XÕ¤ô®Ã£ÇÓÈ»óÓ¤ãËÕ“Ðåÿèåò?"!½šòÐ䤿Œ 
-(2
- 82XÖÂªßøæÌÊ»óÓ¤ãËÕñîôÒ‡¤´†z"!é’¬¸ç¼‡Óª 
-(2
- 825’ÌíûÍõ÷Æ­»óÓ¤ãËÕ®Èùé€ù’±W(2
- 82X²¹÷߆ŒÀ¶`»óÓ¤ãËÕ”ÔÆ™Ž¤š¹»"!ûÄߪæþªâÚ 
-(2
- 82W÷ÞŸÉÔ ëÍd»óÓ¤ãËÕÈ‹ÄÂë¢Ä¯Ø" ª–¨Œ×ÿ¹¡k 
-(2
- 82XäÁš´¤·ñì.»óÓ¤ãËÕáž‹â‘Ý»ä"!÷‘–ä–Œ¿¯ 
-(2
- 82YîæÍçâ»óÓ¤ãËÕ°ÔØùΣ‘¯"!Ïä†÷ɯ 
-(2
- 82Y˜²Ì´×³ìóÓ¤ãËÕ³Ö‰Ó¾ ½Ñ"!Ÿ¡ªˆëôùÇ 
-(2
- 82W¾¯†‘§È“¿P»óÓ¤ãËÕ“Ðåÿèåò?"!½šòÐ䤿Œ 
-(2
- 82XÂÀ¶òšË˜‚ð»óÓ¤ãËÕñîôÒ‡¤´†z"!é’¬¸ç¼‡Óª 
-(2
- 82U—îïÛ²¸¸†µ»óÓ¤ãËÕ”ÔÆ™Ž¤š¹»"!ûÄߪæþªâÚ 
-(2 
-82Tû¯ûû²¶ýñ§»óÓ¤ãËÕÈ‹ÄÂë¢Ä¯Ø" ª–¨Œ×ÿ¹¡k 
-(2 
-82T†ñù™ŸÈ¨«»óÓ¤ãËÕáž‹â‘Ý»ä"!÷‘–ä–Œ¿¯ 
-(2 
-82T҈πŸ¯‰ŠD»óÓ¤ãËÕ°ÔØùΣ‘¯"!Ïä†÷ɯ 
-(2 
-82Uš¤Ë„阿ö†»óÓ¤ãËÕ³Ö‰Ó¾ ½Ñ"!Ÿ¡ªˆëôùÇ 
-(2 
-82SË©ËÞ¯öÈÞ&»óÓ¤ãËÕ“Ðåÿèåò?"!½šòÐ䤿Œ 
-(2 
-82TάóýᔺèÞ»óÓ¤ãËÕñîôÒ‡¤´†z"!é’¬¸ç¼‡Óª 
-(2 
-82#àšÉ±ûÿ±»óÓ¤ãËÕ®Èùé€ù’±W(82#ÞžÞïƒ÷“…±œ–±ÃŸ€ÀâFÐÙ•°‹ÁÈy(82"䣞ƒƒ¿Èòrœ–±ÃŸ€ÀâFÐÙ•°‹ÁÈy(82*¦‚ó©ÂÊÓŒ3œ–±ÃŸ€ÀâFÐÙ•°‹ÁÈy(2%82*ÅМ½à®ÄŠœ–±ÃŸ€ÀâFÐÙ•°‹ÁÈy(2%82"‡è‘²†ÙÓÂ+œ–±ÃŸ€ÀâFÐÙ•°‹ÁÈy(82J›»ÜŽáø©ÔӈƄת¶£«ŒÓÜ¢¾ÌÊ"ûÄߪæþªâÚ'(2'82H®Ñä‚Òš„ÝqˆÆ„ת¶£«Ǯ›ŸÊŸäâ"ª–¨Œ×ÿ¹¡k'(2'82JêýÂÄ…Œ™ÉˆƄת¶£«ÿ‚¾žÃ“’§õ"÷‘–ä–Œ¿¯'(2'82Iâ븛ÚðÖóˆÆ„ת¶£«˜ý˜‘¢ŒÐÀI"Ïä†÷ɯ'(2'82Iÿ±å¨ ïÉ­KˆÆ„ת¶£«ì‘áÒîŸÙÍá"Ÿ¡ªˆëôùÇ'(2'82Hý©ëÞ¥é÷“\ˆÆ„ת¶£«ôé‹¿¿¸ßÄ"½šòÐ䤿Œ'(2'82JÁ°Õ즊ý…¯ˆÆ„ת¶£«‰±Öйˆ–Ôõ"é’¬¸ç¼‡Óª'(2'82ƒ˜Êã•ÿÊÙÚ·æúŸÌ½‚¡”‰àÉ­®¶f"é’¬¸ç¼‡Óª"½šòÐ䤿Œ"Ÿ¡ªˆëôùÇ(282‚ÊùÑèÂóžàY·æúŸÌ½‚¡”‰àÉ­®¶f"é’¬¸ç¼‡Óª"½šòÐ䤿Œ"Ÿ¡ªˆëôùÇ(282MÚËñ´ä‡¼Ä'ª ÿçû¤é刌ÓÜ¢¾ÌÊ"ûÄߪæþªâÚ(2
-82LŽÏ—ꤦݯ5ª ÿçû¤éåˆǮ›ŸÊŸäâ"ª–¨Œ×ÿ¹¡k(2
-82Nø‚ÍÁœÆÚª ÿçû¤éåˆÿ‚¾žÃ“’§õ"÷‘–ä–Œ¿¯(2
-82LŸ¿ŽöåèÆ)ª ÿçû¤é刘ý˜‘¢ŒÐÀI"Ïä†÷ɯ(2
-82NþÝÒÿ§Ù¡±˜ª ÿçû¤éåˆì‘áÒîŸÙÍá"Ÿ¡ªˆëôùÇ(2
-82M³­Ñ×饊ÿ¦ª ÿçû¤éåˆôé‹¿¿¸ßÄ"½šòÐ䤿Œ(2
-82M–ÎÜ‹ó¯Ë„ª ÿçû¤é刉±Öйˆ–Ôõ"é’¬¸ç¼‡Óª(2
-82ƒÍê´ýÞÁöª ÿçû¤é刔‰àÉ­®¶f"é’¬¸ç¼‡Óª"½šòÐ䤿Œ"Ÿ¡ªˆëôùÇ(282,Ü›ä¤ö¸Åˆºª ÿçû¤éåˆÐÙ•°‹ÁÈy(282+Ù¼‡úýõ‰—êâÓ»ä¾ÙÙ9ÐÙ•°‹ÁÈy(282.ƒÚæË›Õ²“^âÓ»ä¾ÙÙ9ÐÙ•°‹ÁÈy(2
-82/òìšÀ·ÄŒÃ#óª·Žð–äÑŠÐÙ•°‹ÁÈy(2
-82+¢ØþËÄÝßíyóª·Žð–äÑŠÐÙ•°‹ÁÈy(282"йʢäÞ†#½³ úùš±KÐÙ•°‹ÁÈy(82I¾Œ…û±ªÓþν³ úùš±KŒÓÜ¢¾ÌÊ"ûÄߪæþªâÚ(282HÞ­ûÅŠëŽî½³ úùš±KǮ›ŸÊŸäâ"ª–¨Œ×ÿ¹¡k(282HÚÇÍý›ôÍô_½³ úùš±Kÿ‚¾žÃ“’§õ"÷‘–ä–Œ¿¯(282Gá”ܰ§¼Üï{½³ úùš±K˜ý˜‘¢ŒÐÀI"Ïä†÷ɯ(282IŒú’ìÌšŒÿ½³ úùš±Kì‘áÒîŸÙÍá"Ÿ¡ªˆëôùÇ(282HðÒ¬¼ïˆâ½³ úùš±Kôé‹¿¿¸ßÄ"½šòÐ䤿Œ(282Hˆ¼ÂÁŒ‚ªŠE½³ úùš±K‰±Öйˆ–Ôõ"é’¬¸ç¼‡Óª(282 ðÚžºÖèà몖¨Œ×ÿ¹¡k(282"…ïèÙŸåóþÎûÄߪæþªâÚ(282!ÆÉ¨‡âž¯‰÷‘–ä–Œ¿¯(282"Õ™õê×Ì·›‹Ïä†÷ɯ(282!Þíó¾ó¿ÚªˆëôùÇ(282!ž¥ÌÔѾۛL½šòÐ䤿Œ(282!„±ÂææÄÁOé’¬¸ç¼‡Óª(282+¦‚ýª¬¢˜þǪ–¨Œ×ÿ¹¡kÐÙ•°‹ÁÈy(282+Ó®¿Œïɳ=ûÄߪæþªâÚÐÙ•°‹ÁÈy(282+ØŽ„Øø¨²c÷‘–ä–Œ¿¯ÐÙ•°‹ÁÈy(282,ýŒ®ê£ÀËŠÏä†÷ɯÐÙ•°‹ÁÈy(282+’ÐÝç’묩uŸ¡ªˆëôùÇÐÙ•°‹ÁÈy(282,ÌÅ„„ŒúÔÞ ½šòÐ䤿ŒÐÙ•°‹ÁÈy(282,ÿªØ¦ƒ®èý»é’¬¸ç¼‡ÓªÐÙ•°‹ÁÈy(282#©Ô†«¹ÛÈÊœä”Û›ÅËèÄÐÙ•°‹ÁÈy(82,‡¼ã™“ЧÓœä”Û›ÅËèÄÐÙ•°‹ÁÈy(2 82#ëÜÄêÖª©ÞùÃýب°Ï=ÐÙ•°‹ÁÈy(82I¬Í˜ÝïÚÈéùÃýب°Ï=ŒÓÜ¢¾ÌÊ"ûÄߪæþªâÚ(282Hã;ܲÍË®øùÃýب°Ï=Ǯ›ŸÊŸäâ"ª–¨Œ×ÿ¹¡k(282IÌ™¹ý¢ÞúŒ…ùÃýب°Ï=ÿ‚¾žÃ“’§õ"÷‘–ä–Œ¿¯(282GÚ´¯Ðèà £YùÃýب°Ï=˜ý˜‘¢ŒÐÀI"Ïä†÷ɯ(282IƒÈæÑ€¸µ§µùÃýب°Ï=ì‘áÒîŸÙÍá"Ÿ¡ªˆëôùÇ(282Gׇã É­ÈùÃýب°Ï=ôé‹¿¿¸ßÄ"½šòÐ䤿Œ(282HÁµÏ›é¥¸ãUùÃýب°Ï=‰±Öйˆ–Ôõ"é’¬¸ç¼‡Óª(282"§±¿Œ·¾íé„ò݃‰…Ï™sÐÙ•°‹ÁÈy(82I®‰Å„ÿ··„ò݃‰…Ï™sŒÓÜ¢¾ÌÊ"ûÄߪæþªâÚ(282H°ªåÛòÿ™˜„ò݃‰…Ï™sǮ›ŸÊŸäâ"ª–¨Œ×ÿ¹¡k(282HÖïˆÇ÷ðî’
-„ò݃‰…Ï™sÿ‚¾žÃ“’§õ"÷‘–ä–Œ¿¯(282Gæü•о°‹„ò݃‰…Ï™s˜ý˜‘¢ŒÐÀI"Ïä†÷ɯ(282HáŒêË ûÜÝ „ò݃‰…Ï™sì‘áÒîŸÙÍá"Ÿ¡ªˆëôùÇ(282Gµü­ŒºÊ¥„ò݃‰…Ï™sôé‹¿¿¸ßÄ"½šòÐ䤿Œ(282HÏææŸÞñ˜È'„ò݃‰…Ï™s‰±Öйˆ–Ôõ"é’¬¸ç¼‡Óª(282#䪧¸ëð»ÍÖ“®ß®þÏ¿ÐÙ•°‹ÁÈy(82HâÈòŸ‚Ϫ¶;“®ß®þÏ¿ŒÓÜ¢¾ÌÊ"ûÄߪæþªâÚ(282GÅöôŽåËà@“®ß®þÏ¿Ǯ›ŸÊŸäâ"ª–¨Œ×ÿ¹¡k(282H±¤ñþÜÀ«‡-“®ß®þÏ¿ÿ‚¾žÃ“’§õ"÷‘–ä–Œ¿¯(282GЇ¶­ÇéíËI“®ß®þÏ¿˜ý˜‘¢ŒÐÀI"Ïä†÷ɯ(282H¶ÛŽˆÊÜÇÔ
-“®ß®þÏ¿ì‘áÒîŸÙÍá"Ÿ¡ªˆëôùÇ(282Gñå°ì’³¯Ç“®ß®þÏ¿ôé‹¿¿¸ßÄ"½šòÐ䤿Œ(282H¥×©ë¹ÖÕÅb“®ß®þÏ¿‰±Öйˆ–Ôõ"é’¬¸ç¼‡Óª(282#¼ù´–ºîª¡Ÿ¤øÝŽ£î“KÐÙ•°‹ÁÈy(82H…üÖ½ßÇЃqŸ¤øÝŽ£î“KŒÓÜ¢¾ÌÊ"ûÄߪæþªâÚ(282GÀê÷ÅÒ×´øŸ¤øÝŽ£î“KǮ›ŸÊŸäâ"ª–¨Œ×ÿ¹¡k(282Iô ¨ø­Í¹€Ÿ¤øÝŽ£î“Kÿ‚¾žÃ“’§õ"÷‘–ä–Œ¿¯(282HÍÆýö®£ÏåËŸ¤øÝŽ£î“K˜ý˜‘¢ŒÐÀI"Ïä†÷ɯ(282H¿¾Š “ʽ៤øÝŽ£î“Kì‘áÒîŸÙÍá"Ÿ¡ªˆëôùÇ(282GºÉ¬¦“ÆçÜpŸ¤øÝŽ£î“Kôé‹¿¿¸ßÄ"½šòÐ䤿Œ(282H•úŸþî¯ø6Ÿ¤øÝŽ£î“K‰±Öйˆ–Ôõ"é’¬¸ç¼‡Óª(28:â鿨ŒÙœ®‘*:ÔØ’¯—꓌’ („:ðÿÈ€ÀíÐð© (¬:ì¹ó¢â¯¢ÚÌ (Ü :ôïÆ þ©ƒ„ø (À :õµ…çÈηŽB (¤ :¸Î½Èìù„ (:¶›èõÖð®÷m (è:¨ÆºÀõµÈï¹ (”
-:ãï©Ê½˜š¡® (¼:¥Ã¯œí…â¥w (ø
-:å½ÈÂÏò“Þó (ˆ:¶Æèܦ™¥ìß(
-(
-(
-(
-(
- B.ª ÿçû¤éåˆ!ÂŒÝëð ¢Ý›ºô¿Úó¾k2
-B"󄽾؜ߞ}™ºŽÔ–í”"žÈ¶ž•ÞŠè(
-B-âÓ»ä¾ÙÙ9!µêЊîÄa鮣öü©µ2
-B,·æúŸÌ½‚¡ûó⿼‘ÿÿƒ«ŸˆÇŽ¿¡
diff --git a/cmds/statsd/tools/dogfood/res/values/strings.xml b/cmds/statsd/tools/dogfood/res/values/strings.xml
deleted file mode 100644
index 60948a181a1b..000000000000
--- a/cmds/statsd/tools/dogfood/res/values/strings.xml
+++ /dev/null
@@ -1,57 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-** http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
--->
-<resources>
-
- <string name="app_name">Statsd Dogfood</string>
-
- <string name="statsd_running">Statsd Running</string>
- <string name="statsd_not_running">Statsd NOT Running</string>
-
- <string name="push_config">Push baseline config</string>
- <string name="set_receiver">Set pendingintent</string>
- <string name="remove_receiver">Remove pendingintent</string>
-
- <string name="app_a_foreground">App A foreground</string>
- <string name="app_b_foreground">App B foreground</string>
-
-
- <string name="app_a_get_wl1">App A get wl_1</string>
- <string name="app_a_release_wl1">App A release wl_1</string>
-
- <string name="app_a_get_wl2">App A get wl_2</string>
- <string name="app_a_release_wl2">App A release wl_2</string>
-
- <string name="app_b_get_wl1">App B get wl_1</string>
- <string name="app_b_release_wl1">App B release wl_1</string>
-
- <string name="app_b_get_wl2">App B get wl_2</string>
- <string name="app_b_release_wl2">App B release wl_2</string>
-
- <string name="plug">Plug</string>
- <string name="unplug">Unplug</string>
-
- <string name="screen_on">Screen On</string>
- <string name="screen_off">Screen Off</string>
-
- <string name="custom_start">App hook start</string>
- <string name="custom_stop">App hook stop</string>
-
- <string name="dump">DumpReport</string>
- <string name="report_header">Report details</string>
-</resources>
diff --git a/cmds/statsd/tools/dogfood/src/com/android/statsd/dogfood/DisplayProtoUtils.java b/cmds/statsd/tools/dogfood/src/com/android/statsd/dogfood/DisplayProtoUtils.java
deleted file mode 100644
index b6b16e40a4b2..000000000000
--- a/cmds/statsd/tools/dogfood/src/com/android/statsd/dogfood/DisplayProtoUtils.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.dogfood;
-
-import android.text.format.DateFormat;
-
-import com.android.os.StatsLog;
-
-import java.util.List;
-
-public class DisplayProtoUtils {
- public static void displayLogReport(StringBuilder sb, StatsLog.ConfigMetricsReportList reports) {
- sb.append("ConfigKey: ");
- if (reports.hasConfigKey()) {
- com.android.os.StatsLog.ConfigMetricsReportList.ConfigKey key = reports.getConfigKey();
- sb.append("\tuid: ").append(key.getUid()).append(" name: ").append(key.getId())
- .append("\n");
- }
-
- for (StatsLog.ConfigMetricsReport report : reports.getReportsList()) {
- sb.append("StatsLogReport size: ").append(report.getMetricsCount()).append("\n");
- sb.append("Last report time:").append(getDateStr(report.getLastReportElapsedNanos())).
- append("\n");
- sb.append("Current report time:").append(getDateStr(report.getCurrentReportElapsedNanos())).
- append("\n");
- for (StatsLog.StatsLogReport log : report.getMetricsList()) {
- sb.append("\n\n");
- sb.append("metric id: ").append(log.getMetricId()).append("\n");
-
- switch (log.getDataCase()) {
- case DURATION_METRICS:
- sb.append("Duration metric data\n");
- displayDurationMetricData(sb, log);
- break;
- case EVENT_METRICS:
- sb.append("Event metric data\n");
- displayEventMetricData(sb, log);
- break;
- case COUNT_METRICS:
- sb.append("Count metric data\n");
- displayCountMetricData(sb, log);
- break;
- case GAUGE_METRICS:
- sb.append("Gauge metric data\n");
- displayGaugeMetricData(sb, log);
- break;
- case VALUE_METRICS:
- sb.append("Value metric data\n");
- displayValueMetricData(sb, log);
- break;
- case DATA_NOT_SET:
- sb.append("No metric data\n");
- break;
- }
- }
- }
- }
-
- public static String getDateStr(long nanoSec) {
- return DateFormat.format("dd/MM hh:mm:ss", nanoSec/1000000).toString();
- }
-
- private static void displayDimension(StringBuilder sb, StatsLog.DimensionsValue dimensionValue) {
- sb.append(dimensionValue.getField()).append(":");
- if (dimensionValue.hasValueBool()) {
- sb.append(dimensionValue.getValueBool());
- } else if (dimensionValue.hasValueFloat()) {
- sb.append(dimensionValue.getValueFloat());
- } else if (dimensionValue.hasValueInt()) {
- sb.append(dimensionValue.getValueInt());
- } else if (dimensionValue.hasValueStr()) {
- sb.append(dimensionValue.getValueStr());
- } else if (dimensionValue.hasValueTuple()) {
- sb.append("{");
- for (StatsLog.DimensionsValue child :
- dimensionValue.getValueTuple().getDimensionsValueList()) {
- displayDimension(sb, child);
- }
- sb.append("}");
- }
- sb.append(" ");
- }
-
- public static void displayDurationMetricData(StringBuilder sb, StatsLog.StatsLogReport log) {
- StatsLog.StatsLogReport.DurationMetricDataWrapper durationMetricDataWrapper
- = log.getDurationMetrics();
- sb.append("Dimension size: ").append(durationMetricDataWrapper.getDataCount()).append("\n");
- for (StatsLog.DurationMetricData duration : durationMetricDataWrapper.getDataList()) {
- sb.append("dimension_in_what: ");
- displayDimension(sb, duration.getDimensionsInWhat());
- sb.append("\n");
- if (duration.hasDimensionsInCondition()) {
- sb.append("dimension_in_condition: ");
- displayDimension(sb, duration.getDimensionsInCondition());
- sb.append("\n");
- }
-
- for (StatsLog.DurationBucketInfo info : duration.getBucketInfoList()) {
- sb.append("\t[").append(getDateStr(info.getStartBucketElapsedNanos())).append("-")
- .append(getDateStr(info.getEndBucketElapsedNanos())).append("] -> ")
- .append(info.getDurationNanos()).append(" ns\n");
- }
- }
- }
-
- public static void displayEventMetricData(StringBuilder sb, StatsLog.StatsLogReport log) {
- sb.append("Contains ").append(log.getEventMetrics().getDataCount()).append(" events\n");
- StatsLog.StatsLogReport.EventMetricDataWrapper eventMetricDataWrapper =
- log.getEventMetrics();
- for (StatsLog.EventMetricData event : eventMetricDataWrapper.getDataList()) {
- sb.append(getDateStr(event.getElapsedTimestampNanos())).append(": ");
- sb.append(event.getAtom().getPushedCase().toString()).append("\n");
- }
- }
-
- public static void displayCountMetricData(StringBuilder sb, StatsLog.StatsLogReport log) {
- StatsLog.StatsLogReport.CountMetricDataWrapper countMetricDataWrapper
- = log.getCountMetrics();
- sb.append("Dimension size: ").append(countMetricDataWrapper.getDataCount()).append("\n");
- for (StatsLog.CountMetricData count : countMetricDataWrapper.getDataList()) {
- sb.append("dimension_in_what: ");
- displayDimension(sb, count.getDimensionsInWhat());
- sb.append("\n");
- if (count.hasDimensionsInCondition()) {
- sb.append("dimension_in_condition: ");
- displayDimension(sb, count.getDimensionsInCondition());
- sb.append("\n");
- }
-
- for (StatsLog.CountBucketInfo info : count.getBucketInfoList()) {
- sb.append("\t[").append(getDateStr(info.getStartBucketElapsedNanos())).append("-")
- .append(getDateStr(info.getEndBucketElapsedNanos())).append("] -> ")
- .append(info.getCount()).append("\n");
- }
- }
- }
-
- public static void displayGaugeMetricData(StringBuilder sb, StatsLog.StatsLogReport log) {
- sb.append("Display me!");
- }
-
- public static void displayValueMetricData(StringBuilder sb, StatsLog.StatsLogReport log) {
- sb.append("Display me!");
- }
-}
diff --git a/cmds/statsd/tools/dogfood/src/com/android/statsd/dogfood/MainActivity.java b/cmds/statsd/tools/dogfood/src/com/android/statsd/dogfood/MainActivity.java
deleted file mode 100644
index 4f4dd011e419..000000000000
--- a/cmds/statsd/tools/dogfood/src/com/android/statsd/dogfood/MainActivity.java
+++ /dev/null
@@ -1,361 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.dogfood;
-
-import android.app.Activity;
-import android.app.PendingIntent;
-import android.app.IntentService;
-import android.app.StatsManager;
-import android.app.StatsManager.StatsUnavailableException;
-import android.content.Context;
-import android.content.Intent;
-import android.content.res.Resources;
-import android.os.Bundle;
-import android.util.Log;
-import android.util.StatsLog;
-import android.view.View;
-import android.widget.TextView;
-import android.widget.Toast;
-import android.os.IStatsManager;
-import android.os.ServiceManager;
-
-import java.io.InputStream;
-
-import static com.android.statsd.dogfood.DisplayProtoUtils.displayLogReport;
-
-public class MainActivity extends Activity {
- private final static String TAG = "StatsdDogfood";
- private final static long CONFIG_ID = 987654321;
-
- final int[] mUids = {11111111, 2222222};
- StatsManager mStatsManager;
- TextView mReportText;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- setContentView(R.layout.activity_main);
-
- findViewById(R.id.app_a_wake_lock_acquire1).setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- onWakeLockAcquire(0, "wl_1");
- }
- });
-
- findViewById(R.id.app_b_wake_lock_acquire1).setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- onWakeLockAcquire(1, "wl_1");
- }
- });
-
- findViewById(R.id.app_a_wake_lock_acquire2).setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- onWakeLockAcquire(0, "wl_2");
- }
- });
-
- findViewById(R.id.app_b_wake_lock_acquire2).setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- onWakeLockAcquire(1, "wl_2");
- }
- });
-
- findViewById(R.id.app_a_wake_lock_release1).setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- onWakeLockRelease(0, "wl_1");
- }
- });
-
-
- findViewById(R.id.app_b_wake_lock_release1).setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- onWakeLockRelease(1, "wl_1");
- }
- });
-
- findViewById(R.id.app_a_wake_lock_release2).setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- onWakeLockRelease(0, "wl_2");
- }
- });
-
-
- findViewById(R.id.app_b_wake_lock_release2).setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- onWakeLockRelease(1, "wl_2");
- }
- });
-
-
- findViewById(R.id.plug).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED,
- StatsLog.PLUGGED_STATE_CHANGED__STATE__BATTERY_PLUGGED_AC);
- }
- });
-
- findViewById(R.id.unplug).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED,
- StatsLog.PLUGGED_STATE_CHANGED__STATE__BATTERY_PLUGGED_NONE);
- }
- });
-
- findViewById(R.id.screen_on).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- StatsLog.write(StatsLog.SCREEN_STATE_CHANGED,
- StatsLog.SCREEN_STATE_CHANGED__STATE__DISPLAY_STATE_ON);
- }
- });
-
- findViewById(R.id.screen_off).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- StatsLog.write(StatsLog.SCREEN_STATE_CHANGED,
- StatsLog.SCREEN_STATE_CHANGED__STATE__DISPLAY_STATE_OFF);
- }
- });
-
- findViewById(R.id.custom_start).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- StatsLog.logStart(8);
- }
- });
-
- findViewById(R.id.custom_stop).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- StatsLog.logStop(8);
- }
- });
-
- mReportText = (TextView) findViewById(R.id.report_text);
-
- findViewById(R.id.dump).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (!statsdRunning()) {
- return;
- }
- if (mStatsManager != null) {
- try {
- byte[] data = mStatsManager.getReports(CONFIG_ID);
- if (data != null) {
- displayData(data);
- return;
- }
- } catch (StatsUnavailableException e) {
- Log.e(TAG, "Failed to get data from statsd", e);
- }
- mReportText.setText("Failed!");
- }
- }
- });
-
- findViewById(R.id.push_config).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- try {
- if (!statsdRunning()) {
- return;
- }
- Resources res = getResources();
- InputStream inputStream = res.openRawResource(R.raw.statsd_baseline_config);
-
- byte[] config = new byte[inputStream.available()];
- inputStream.read(config);
- if (mStatsManager != null) {
- try {
- mStatsManager.addConfig(CONFIG_ID, config);
- Toast.makeText(
- MainActivity.this, "Config pushed", Toast.LENGTH_LONG).show();
- } catch (StatsUnavailableException | IllegalArgumentException e) {
- Toast.makeText(MainActivity.this, "Config push FAILED!",
- Toast.LENGTH_LONG).show();
- }
- }
- } catch (Exception e) {
- Toast.makeText(MainActivity.this, "failed to read config", Toast.LENGTH_LONG);
- }
- }
- });
-
- PendingIntent pi = PendingIntent.getService(this, 0,
- new Intent(this, ReceiverIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT);
- findViewById(R.id.set_receiver).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- try {
- if (!statsdRunning()) {
- return;
- }
- if (mStatsManager != null) {
- try {
- mStatsManager.setFetchReportsOperation(pi, CONFIG_ID);
- Toast.makeText(MainActivity.this,
- "Receiver specified to pending intent", Toast.LENGTH_LONG)
- .show();
- } catch (StatsUnavailableException e) {
- Toast.makeText(MainActivity.this, "Statsd did not set receiver",
- Toast.LENGTH_LONG)
- .show();
- }
- }
- } catch (Exception e) {
- Toast.makeText(MainActivity.this, "failed to set receiver", Toast.LENGTH_LONG);
- }
- }
- });
- findViewById(R.id.remove_receiver).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- try {
- if (!statsdRunning()) {
- return;
- }
- if (mStatsManager != null) {
- try {
- mStatsManager.setFetchReportsOperation(null, CONFIG_ID);
- Toast.makeText(MainActivity.this, "Receiver remove", Toast.LENGTH_LONG)
- .show();
- } catch (StatsUnavailableException e) {
- Toast.makeText(MainActivity.this, "Statsd did not remove receiver",
- Toast.LENGTH_LONG)
- .show();
- }
- }
- } catch (Exception e) {
- Toast.makeText(
- MainActivity.this, "failed to remove receiver", Toast.LENGTH_LONG);
- }
- }
- });
- mStatsManager = (StatsManager) getSystemService("stats");
- }
-
- private boolean statsdRunning() {
- if (IStatsManager.Stub.asInterface(ServiceManager.getService("stats")) == null) {
- Log.d(TAG, "Statsd not running");
- Toast.makeText(MainActivity.this, "Statsd NOT running!", Toast.LENGTH_LONG).show();
- return false;
- }
- return true;
- }
-
- @Override
- public void onNewIntent(Intent intent) {
- Log.d(TAG, "new intent: " + intent.getIntExtra("pkg", 0));
- int pkg = intent.getIntExtra("pkg", 0);
- String name = intent.getStringExtra("name");
- if (intent.hasExtra("acquire")) {
- onWakeLockAcquire(pkg, name);
- } else if (intent.hasExtra("release")) {
- onWakeLockRelease(pkg, name);
- }
- }
-
- private void displayData(byte[] data) {
- com.android.os.StatsLog.ConfigMetricsReportList reports = null;
- boolean good = false;
- if (data != null) {
- try {
- reports = com.android.os.StatsLog.ConfigMetricsReportList.parseFrom(data);
- good = true;
- } catch (com.google.protobuf.InvalidProtocolBufferException e) {
- // display it in the text view.
- }
- }
- int size = data == null ? 0 : data.length;
- StringBuilder sb = new StringBuilder();
- sb.append(good ? "Proto parsing OK!" : "Proto parsing Error!");
- sb.append(" size:").append(size).append("\n");
-
- if (good && reports != null) {
- displayLogReport(sb, reports);
- mReportText.setText(sb.toString());
- }
- }
-
-
- private void onWakeLockAcquire(int id, String name) {
- if (id > 1) {
- Log.d(TAG, "invalid pkg id");
- return;
- }
- int[] uids = new int[]{mUids[id]};
- String[] tags = new String[]{"acquire"};
- StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, uids, tags,
- StatsLog.WAKELOCK_STATE_CHANGED__TYPE__PARTIAL_WAKE_LOCK, name,
- StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
- StringBuilder sb = new StringBuilder();
- sb.append("StagsLog.write(10, ").append(mUids[id]).append(", ").append(0)
- .append(", ").append(name).append(", 1);");
- Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
- }
-
- private void onWakeLockRelease(int id, String name) {
- if (id > 1) {
- Log.d(TAG, "invalid pkg id");
- return;
- }
- int[] uids = new int[]{mUids[id]};
- String[] tags = new String[]{"release"};
- StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, uids, tags,
- StatsLog.WAKELOCK_STATE_CHANGED__TYPE__PARTIAL_WAKE_LOCK, name,
- StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
- StringBuilder sb = new StringBuilder();
- sb.append("StagsLog.write(10, ").append(mUids[id]).append(", ").append(0)
- .append(", ").append(name).append(", 0);");
- Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
- }
-
- public static class ReceiverIntentService extends IntentService {
- public ReceiverIntentService() {
- super("ReceiverIntentService");
- }
-
- /**
- * The IntentService calls this method from the default worker thread with
- * the intent that started the service. When this method returns, IntentService
- * stops the service, as appropriate.
- */
- @Override
- protected void onHandleIntent(Intent intent) {
- Log.i(TAG, "Received notification that we should call getData");
- }
- }
-}
diff --git a/cmds/statsd/tools/loadtest/Android.bp b/cmds/statsd/tools/loadtest/Android.bp
deleted file mode 100644
index bf87fc51dce1..000000000000
--- a/cmds/statsd/tools/loadtest/Android.bp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (C) 2017 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//
-
-android_app {
- name: "StatsdLoadtest",
- platform_apis: true,
-
- srcs: ["src/**/*.java"],
-
- resource_dirs: ["res"],
- static_libs: [
- "platformprotoslite",
- "statsdprotolite",
- ],
-
- certificate: "platform",
- privileged: true,
- dex_preopt: {
- enabled: false,
- },
- optimize: {
- enabled: false,
- },
-}
diff --git a/cmds/statsd/tools/loadtest/AndroidManifest.xml b/cmds/statsd/tools/loadtest/AndroidManifest.xml
deleted file mode 100644
index 2bf8ca95d846..000000000000
--- a/cmds/statsd/tools/loadtest/AndroidManifest.xml
+++ /dev/null
@@ -1,44 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-** http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
--->
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.statsd.loadtest"
- android:sharedUserId="android.uid.system"
- android:versionCode="1"
- android:versionName="1.0" >
-
- <uses-permission android:name="android.permission.DUMP" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name" >
- <activity
- android:name=".LoadtestActivity"
- android:label="@string/app_name"
- android:launchMode="singleTop" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <receiver android:name=".LoadtestActivity$PusherAlarmReceiver" />
- <receiver android:name=".LoadtestActivity$StopperAlarmReceiver"/>
- <receiver android:name=".PerfData$PerfAlarmReceiver"/>
- </application>
-</manifest>
diff --git a/cmds/statsd/tools/loadtest/res/drawable-hdpi/ic_launcher.png b/cmds/statsd/tools/loadtest/res/drawable-hdpi/ic_launcher.png
deleted file mode 100644
index 55621cc1074f..000000000000
--- a/cmds/statsd/tools/loadtest/res/drawable-hdpi/ic_launcher.png
+++ /dev/null
Binary files differ
diff --git a/cmds/statsd/tools/loadtest/res/drawable-mdpi/ic_launcher.png b/cmds/statsd/tools/loadtest/res/drawable-mdpi/ic_launcher.png
deleted file mode 100644
index 11ec2068be19..000000000000
--- a/cmds/statsd/tools/loadtest/res/drawable-mdpi/ic_launcher.png
+++ /dev/null
Binary files differ
diff --git a/cmds/statsd/tools/loadtest/res/drawable-xhdpi/ic_launcher.png b/cmds/statsd/tools/loadtest/res/drawable-xhdpi/ic_launcher.png
deleted file mode 100644
index 7c02b784aa5d..000000000000
--- a/cmds/statsd/tools/loadtest/res/drawable-xhdpi/ic_launcher.png
+++ /dev/null
Binary files differ
diff --git a/cmds/statsd/tools/loadtest/res/drawable-xxhdpi/ic_launcher.png b/cmds/statsd/tools/loadtest/res/drawable-xxhdpi/ic_launcher.png
deleted file mode 100644
index 915d91441349..000000000000
--- a/cmds/statsd/tools/loadtest/res/drawable-xxhdpi/ic_launcher.png
+++ /dev/null
Binary files differ
diff --git a/cmds/statsd/tools/loadtest/res/layout/activity_loadtest.xml b/cmds/statsd/tools/loadtest/res/layout/activity_loadtest.xml
deleted file mode 100644
index d6f804734385..000000000000
--- a/cmds/statsd/tools/loadtest/res/layout/activity_loadtest.xml
+++ /dev/null
@@ -1,208 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-** http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
--->
-<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
-
- <LinearLayout
- android:id="@+id/outside"
- android:clickable="true"
- android:focusable="true"
- android:focusableInTouchMode="true"
- android:gravity="center"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_marginRight="10dp"
- android:layout_marginLeft="10dp"
- android:orientation="vertical">
- <requestFocus />
-
- <LinearLayout
- android:gravity="center"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="horizontal">
- <TextView
- android:textSize="30dp"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:text="@string/replication_label" />
- <EditText
- android:id="@+id/replication"
- android:inputType="number"
- android:layout_weight="1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:maxLength="4"
- android:text="@integer/replication_default"
- android:textSize="30dp"/>
- </LinearLayout>
-
- <LinearLayout
- android:gravity="center"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="horizontal">
- <TextView
- android:textSize="30dp"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:text="@string/bucket_label" />
- <Spinner
- android:id="@+id/bucket_spinner"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:prompt="@string/bucket_label"/>
- </LinearLayout>
-
- <LinearLayout
- android:gravity="center"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="horizontal">
- <TextView
- android:textSize="30dp"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:text="@string/period_label" />
- <EditText
- android:id="@+id/period"
- android:inputType="number"
- android:layout_weight="1"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:maxLength="3"
- android:text="@integer/period_default"
- android:textSize="30dp"/>
- </LinearLayout>
-
- <LinearLayout
- android:gravity="center"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="horizontal">
- <TextView
- android:textSize="30dp"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:text="@string/burst_label" />
- <EditText
- android:id="@+id/burst"
- android:inputType="number"
- android:layout_weight="1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:maxLength="4"
- android:text="@integer/burst_default"
- android:textSize="30dp"/>
- </LinearLayout>
-
- <LinearLayout
- android:gravity="center"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="horizontal">
- <TextView
- android:textSize="30dp"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:text="@string/duration_label" />
- <EditText
- android:id="@+id/duration"
- android:inputType="number"
- android:layout_weight="1"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:maxLength="4"
- android:text="@integer/duration_default"
- android:textSize="30dp"/>
- </LinearLayout>
- <CheckBox
- android:id="@+id/placebo"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/placebo"
- android:checked="false" />
-
- <LinearLayout
- android:gravity="center"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
- <CheckBox
- android:id="@+id/include_count"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/count"
- android:checked="true"/>
- <CheckBox
- android:id="@+id/include_duration"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/duration"
- android:checked="true"/>
- <CheckBox
- android:id="@+id/include_event"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/event"
- android:checked="true"/>
- <CheckBox
- android:id="@+id/include_value"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/value"
- android:checked="true"/>
- <CheckBox
- android:id="@+id/include_gauge"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/gauge"
- android:checked="true"/>
- </LinearLayout>
-
- <Space
- android:layout_width="1dp"
- android:layout_height="30dp"/>
-
- <Button
- android:id="@+id/start_stop"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:background="#ffff0000"
- android:text="@string/start"
- android:textSize="50dp"/>
-
- <Space
- android:layout_width="1dp"
- android:layout_height="30dp"/>
-
- <Space
- android:layout_width="1dp"
- android:layout_height="30dp"/>
-
- <TextView
- android:id="@+id/report_text"
- android:gravity="center"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
-
- </LinearLayout>
-
-</ScrollView>
diff --git a/cmds/statsd/tools/loadtest/res/layout/spinner_item.xml b/cmds/statsd/tools/loadtest/res/layout/spinner_item.xml
deleted file mode 100644
index b03da06f7a77..000000000000
--- a/cmds/statsd/tools/loadtest/res/layout/spinner_item.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<TextView
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:textSize="30dp"
- android:gravity="left"
- android:padding="5dip"
- />
diff --git a/cmds/statsd/tools/loadtest/res/raw/loadtest_config b/cmds/statsd/tools/loadtest/res/raw/loadtest_config
deleted file mode 100755
index 24221908cbeb..000000000000
--- a/cmds/statsd/tools/loadtest/res/raw/loadtest_config
+++ /dev/null
Binary files differ
diff --git a/cmds/statsd/tools/loadtest/res/values/integers.xml b/cmds/statsd/tools/loadtest/res/values/integers.xml
deleted file mode 100644
index c2407d3b85f2..000000000000
--- a/cmds/statsd/tools/loadtest/res/values/integers.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-** http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
--->
-<resources>
- <integer name="burst_default">1</integer>
- <integer name="period_default">2</integer>
- <integer name="replication_default">1</integer>
- <integer name="duration_default">240</integer>
-</resources>
diff --git a/cmds/statsd/tools/loadtest/res/values/strings.xml b/cmds/statsd/tools/loadtest/res/values/strings.xml
deleted file mode 100644
index e8ae3f82a7e3..000000000000
--- a/cmds/statsd/tools/loadtest/res/values/strings.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2007, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-** http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
--->
-<resources>
- <string name="app_name">Statsd Loadtest</string>
- <string name="bucket_label">bucket size (mins):&#160;</string>
- <string name="burst_label">burst:&#160;</string>
- <string name="bucket_default">FIVE_MINUTES</string>
- <string name="placebo">placebo</string>
- <string name="period_label">logging period (secs):&#160;</string>
- <string name="replication_label">metric replication:&#160;</string>
- <string name="duration_label">test duration (mins):&#160;</string>
- <string name="start"> &#160;Start&#160; </string>
- <string name="stop"> &#160;Stop&#160; </string>
- <string name="count"> count </string>
- <string name="duration"> duration </string>
- <string name="event"> event </string>
- <string name="value"> value </string>
- <string name="gauge"> gauge </string>
-
-</resources>
diff --git a/cmds/statsd/tools/loadtest/run_loadtest.sh b/cmds/statsd/tools/loadtest/run_loadtest.sh
deleted file mode 100755
index 3c93a0613183..000000000000
--- a/cmds/statsd/tools/loadtest/run_loadtest.sh
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/bin/sh
-#
-# Script that measures statsd's PSS under an increasing number of metrics.
-
-# Globals.
-pss=""
-pid=""
-
-# Starts the loadtest.
-start_loadtest() {
- echo "Starting loadtest"
- adb shell am start -n com.android.statsd.loadtest/.LoadtestActivity --es "type" "start"
-}
-
-# Stops the loadtest.
-stop_loadtest() {
- echo "Stopping loadtest"
- adb shell am start -n com.android.statsd.loadtest/.LoadtestActivity --es "type" "stop"
-}
-
-# Sets the metrics replication.
-# Arguments:
-# $1: The replication factor.
-set_replication() {
- adb shell am start -n com.android.statsd.loadtest/.LoadtestActivity --es "type" "set_replication" --ei "replication" "${1}"
- echo "Replication set to ${1}"
-}
-
-# Reads statsd's pid and PSS.
-update_pid_and_pss() {
- # Command that reads the PSS for statsd. This also gives us its pid.
- get_mem=$(adb shell dumpsys meminfo |grep statsd)
- # Looks for statsd's pid.
- regex="([0-9,]+)K: statsd \(pid ([0-9]+)\).*"
- if [[ $get_mem =~ $regex ]]; then
- pss=$(echo "${BASH_REMATCH[1]}" | tr -d , | sed 's/\.//g')
- pid=$(echo "${BASH_REMATCH[2]}")
- else
- echo $cmd doesnt match $regex
- fi
-}
-
-# Kills statsd.
-# Assumes the pid has been set.
-kill_statsd() {
- echo "Killing statsd (pid ${pid})"
- adb shell kill -9 "${pid}"
-}
-
-# Main loop.
-main() {
- start_time=$(date +%s)
- values=()
- stop_loadtest
-
- echo ""
- echo "********************* NEW LOADTEST ************************"
- update_pid_and_pss
- for replication in 1 2 4 8 16 32 64 128 256 512 1024 2048 4096
- do
- echo "**** Starting test at replication ${replication} ****"
-
- # (1) Restart statsd. This will ensure its state is empty.
- kill_statsd
- sleep 3 # wait a bit for it to restart
- update_pid_and_pss
- echo "Before the test, statsd's PSS is ${pss}"
-
- # (2) Set the replication.
- set_replication "${replication}"
- sleep 1 # wait a bit
-
- # (3) Start the loadtest.
- start_loadtest
-
- # (4) Wait several seconds, then read the PSS.
- sleep 100 && update_pid_and_pss
- echo "During the test, statsd's PSS is ${pss}"
- values+=(${pss})
-
- echo "Values: ${values[@]}"
-
- # (5) Stop loadtest.
- stop_loadtest
- sleep 2
-
- echo ""
- done
-
- end_time=$(date +%s)
- echo "Completed loadtest in $((${end_time} - ${start_time})) seconds."
-
- values_as_str=$(IFS=$'\n'; echo "${values[*]}")
- echo "The PSS values are:"
- echo "${values_as_str}"
- echo ""
-}
-
-main
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/BatteryDataRecorder.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/BatteryDataRecorder.java
deleted file mode 100644
index bab0c1e3f540..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/BatteryDataRecorder.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.annotation.Nullable;
-import android.content.Context;
-import android.util.Log;
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-import java.text.ParseException;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class BatteryDataRecorder extends PerfDataRecorder {
- private static final String TAG = "loadtest.BatteryDataRecorder";
- private static final String DUMP_FILENAME = TAG + "_dump.tmp";
-
- public BatteryDataRecorder(boolean placebo, int replication, TimeUnit bucket, long periodSecs,
- int burst, boolean includeCountMetric, boolean includeDurationMetric,
- boolean includeEventMetric, boolean includeValueMetric, boolean includeGaugeMetric) {
- super(placebo, replication, bucket, periodSecs, burst, includeCountMetric,
- includeDurationMetric, includeEventMetric, includeValueMetric, includeGaugeMetric);
- }
-
- @Override
- public void startRecording(Context context) {
- // Reset batterystats.
- runDumpsysStats(context, DUMP_FILENAME, "batterystats", "--reset");
- }
-
- @Override
- public void onAlarm(Context context) {
- // Nothing to do as for battery, the whole data is in the final dumpsys call.
- }
-
- @Override
- public void stopRecording(Context context) {
- StringBuilder sb = new StringBuilder();
- // Don't use --checkin.
- runDumpsysStats(context, DUMP_FILENAME, "batterystats");
- readDumpData(context, DUMP_FILENAME, new BatteryStatsParser(), sb);
- writeData(context, "battery_", "time,battery_level", sb);
- }
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/BatteryStatsParser.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/BatteryStatsParser.java
deleted file mode 100644
index 203d97acefd8..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/BatteryStatsParser.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.annotation.Nullable;
-import android.util.Log;
-import java.text.ParseException;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class BatteryStatsParser implements PerfParser {
-
- private static final Pattern LINE_PATTERN =
- Pattern.compile("\\s*\\+*(\\S*)\\s\\(\\d+\\)\\s(\\d\\d\\d)\\s.*");
- private static final Pattern TIME_PATTERN =
- Pattern.compile("(\\d+)?(h)?(\\d+)?(m)?(\\d+)?(s)?(\\d+)?(ms)?");
- private static final String TAG = "loadtest.BatteryStatsParser";
-
- private boolean mHistoryStarted;
- private boolean mHistoryEnded;
-
- public BatteryStatsParser() {
- }
-
- @Override
- @Nullable
- public String parseLine(String line) {
- if (mHistoryEnded) {
- return null;
- }
- if (!mHistoryStarted) {
- if (line.contains("Battery History")) {
- mHistoryStarted = true;
- }
- return null;
- }
- if (line.isEmpty()) {
- mHistoryEnded = true;
- return null;
- }
- Matcher lineMatcher = LINE_PATTERN.matcher(line);
- if (lineMatcher.find() && lineMatcher.group(1) != null && lineMatcher.group(2) != null) {
- if (lineMatcher.group(1).equals("0")) {
- return "0," + lineMatcher.group(2) + "\n";
- } else {
- Matcher timeMatcher = TIME_PATTERN.matcher(lineMatcher.group(1));
- if (timeMatcher.find()) {
- Long time = getTime(lineMatcher.group(1));
- if (time != null) {
- return time + "," + lineMatcher.group(2) + "\n";
- } else {
- return null; // bad time
- }
- } else {
- return null; // bad or no time
- }
- }
- }
- return null;
- }
-
- @Nullable
- private Long getTime(String group) {
- if ("0".equals(group)) {
- return 0L;
- }
- Matcher timeMatcher = TIME_PATTERN.matcher(group);
- if (!timeMatcher.find()) {
- return null;
- }
-
- // Get rid of "ms".
- String[] matches = group.split("ms", -1);
- if (matches.length > 1) {
- group = matches[0];
- }
-
- long time = 0L;
- matches = group.split("h");
- if (matches.length > 1) {
- time += Long.parseLong(matches[0]) * 60 * 60 * 1000; // hours
- group = matches[1];
- }
- matches = group.split("m");
- if (matches.length > 1) {
- time += Long.parseLong(matches[0]) * 60 * 1000; // minutes
- group = matches[1];
- }
- matches = group.split("s");
- if (matches.length > 1) {
- time += Long.parseLong(matches[0]) * 1000; // seconds
- group = matches[1];
- }
-
- if (!group.isEmpty()) {
- time += Long.parseLong(group); // milliseconds
- }
- return time;
- }
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/ConfigFactory.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/ConfigFactory.java
deleted file mode 100644
index 2e0161be8096..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/ConfigFactory.java
+++ /dev/null
@@ -1,314 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.util.Log;
-
-import com.android.internal.os.StatsdConfigProto.Predicate;
-import com.android.internal.os.StatsdConfigProto.CountMetric;
-import com.android.internal.os.StatsdConfigProto.DurationMetric;
-import com.android.internal.os.StatsdConfigProto.MetricConditionLink;
-import com.android.internal.os.StatsdConfigProto.EventMetric;
-import com.android.internal.os.StatsdConfigProto.GaugeMetric;
-import com.android.internal.os.StatsdConfigProto.ValueMetric;
-import com.android.internal.os.StatsdConfigProto.FieldValueMatcher;
-import com.android.internal.os.StatsdConfigProto.AtomMatcher;
-import com.android.internal.os.StatsdConfigProto.SimplePredicate;
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-
-import java.io.InputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Creates StatsdConfig protos for loadtesting.
- */
-public class ConfigFactory {
- public static class ConfigMetadata {
- public final byte[] bytes;
- public final int numMetrics;
-
- public ConfigMetadata(byte[] bytes, int numMetrics) {
- this.bytes = bytes;
- this.numMetrics = numMetrics;
- }
- }
-
- public static final long CONFIG_ID = 123456789;
-
- private static final String TAG = "loadtest.ConfigFactory";
-
- private final StatsdConfig mTemplate;
-
- public ConfigFactory(Context context) {
- // Read the config template from the resoures.
- Resources res = context.getResources();
- byte[] template = null;
- StatsdConfig templateProto = null;
- try {
- InputStream inputStream = res.openRawResource(R.raw.loadtest_config);
- template = new byte[inputStream.available()];
- inputStream.read(template);
- templateProto = StatsdConfig.parseFrom(template);
- } catch (IOException e) {
- Log.e(TAG, "Unable to read or parse loadtest config template. Using an empty config.");
- }
- mTemplate = templateProto == null ? StatsdConfig.newBuilder().build() : templateProto;
-
- Log.d(TAG, "Loadtest template config: " + mTemplate);
- }
-
- /**
- * Generates a config.
- *
- * All configs are based on the same template.
- * That template is designed to make the most use of the set of atoms that {@code SequencePusher}
- * pushes, and to exercise as many of the metrics features as possible.
- * Furthermore, by passing a replication factor to this method, one can artificially inflate
- * the number of metrics in the config. One can also adjust the bucket size for aggregate
- * metrics.
- *
- * @param replication The number of times each metric is replicated in the config.
- * If the config template has n metrics, the generated config will have n * replication
- * ones
- * @param bucketMillis The bucket size, in milliseconds, for aggregate metrics
- * @param placebo If true, only return an empty config
- * @return The serialized config and the number of metrics.
- */
- public ConfigMetadata getConfig(int replication, TimeUnit bucket, boolean placebo,
- boolean includeCount, boolean includeDuration, boolean includeEvent,
- boolean includeValue, boolean includeGauge) {
- StatsdConfig.Builder config = StatsdConfig.newBuilder()
- .setId(CONFIG_ID);
- if (placebo) {
- replication = 0; // Config will be empty, aside from a name.
- }
- int numMetrics = 0;
- for (int i = 0; i < replication; i++) {
- // metrics
- if (includeEvent) {
- for (EventMetric metric : mTemplate.getEventMetricList()) {
- addEventMetric(metric, i, config);
- numMetrics++;
- }
- }
- if (includeCount) {
- for (CountMetric metric : mTemplate.getCountMetricList()) {
- addCountMetric(metric, i, bucket, config);
- numMetrics++;
- }
- }
- if (includeDuration) {
- for (DurationMetric metric : mTemplate.getDurationMetricList()) {
- addDurationMetric(metric, i, bucket, config);
- numMetrics++;
- }
- }
- if (includeGauge) {
- for (GaugeMetric metric : mTemplate.getGaugeMetricList()) {
- addGaugeMetric(metric, i, bucket, config);
- numMetrics++;
- }
- }
- if (includeValue) {
- for (ValueMetric metric : mTemplate.getValueMetricList()) {
- addValueMetric(metric, i, bucket, config);
- numMetrics++;
- }
- }
- // predicates
- for (Predicate predicate : mTemplate.getPredicateList()) {
- addPredicate(predicate, i, config);
- }
- // matchers
- for (AtomMatcher matcher : mTemplate.getAtomMatcherList()) {
- addMatcher(matcher, i, config);
- }
- }
-
- Log.d(TAG, "Loadtest config is : " + config.build());
- Log.d(TAG, "Generated config has " + numMetrics + " metrics");
-
- return new ConfigMetadata(config.build().toByteArray(), numMetrics);
- }
-
- /**
- * Creates {@link MetricConditionLink}s that are identical to the one passed to this method,
- * except that the names are appended with the provided suffix.
- */
- private List<MetricConditionLink> getLinks(
- List<MetricConditionLink> links, int suffix) {
- List<MetricConditionLink> newLinks = new ArrayList();
- for (MetricConditionLink link : links) {
- newLinks.add(link.toBuilder()
- .setCondition(link.getCondition() + suffix)
- .build());
- }
- return newLinks;
- }
-
- /**
- * Creates an {@link EventMetric} based on the template. Makes sure that all names are appended
- * with the provided suffix. Then adds that metric to the config.
- */
- private void addEventMetric(EventMetric template, int suffix, StatsdConfig.Builder config) {
- EventMetric.Builder metric = template.toBuilder()
- .setId(template.getId() + suffix)
- .setWhat(template.getWhat() + suffix);
- if (template.hasCondition()) {
- metric.setCondition(template.getCondition() + suffix);
- }
- if (template.getLinksCount() > 0) {
- List<MetricConditionLink> links = getLinks(template.getLinksList(), suffix);
- metric.clearLinks();
- metric.addAllLinks(links);
- }
- config.addEventMetric(metric);
- }
-
- /**
- * Creates a {@link CountMetric} based on the template. Makes sure that all names are appended
- * with the provided suffix, and overrides the bucket size. Then adds that metric to the config.
- */
- private void addCountMetric(CountMetric template, int suffix, TimeUnit bucket,
- StatsdConfig.Builder config) {
- CountMetric.Builder metric = template.toBuilder()
- .setId(template.getId() + suffix)
- .setWhat(template.getWhat() + suffix);
- if (template.hasCondition()) {
- metric.setCondition(template.getCondition() + suffix);
- }
- if (template.getLinksCount() > 0) {
- List<MetricConditionLink> links = getLinks(template.getLinksList(), suffix);
- metric.clearLinks();
- metric.addAllLinks(links);
- }
- metric.setBucket(bucket);
- config.addCountMetric(metric);
- }
-
- /**
- * Creates a {@link DurationMetric} based on the template. Makes sure that all names are appended
- * with the provided suffix, and overrides the bucket size. Then adds that metric to the config.
- */
- private void addDurationMetric(DurationMetric template, int suffix, TimeUnit bucket,
- StatsdConfig.Builder config) {
- DurationMetric.Builder metric = template.toBuilder()
- .setId(template.getId() + suffix)
- .setWhat(template.getWhat() + suffix);
- if (template.hasCondition()) {
- metric.setCondition(template.getCondition() + suffix);
- }
- if (template.getLinksCount() > 0) {
- List<MetricConditionLink> links = getLinks(template.getLinksList(), suffix);
- metric.clearLinks();
- metric.addAllLinks(links);
- }
- metric.setBucket(bucket);
- config.addDurationMetric(metric);
- }
-
- /**
- * Creates a {@link GaugeMetric} based on the template. Makes sure that all names are appended
- * with the provided suffix, and overrides the bucket size. Then adds that metric to the config.
- */
- private void addGaugeMetric(GaugeMetric template, int suffix, TimeUnit bucket,
- StatsdConfig.Builder config) {
- GaugeMetric.Builder metric = template.toBuilder()
- .setId(template.getId() + suffix)
- .setWhat(template.getWhat() + suffix);
- if (template.hasCondition()) {
- metric.setCondition(template.getCondition() + suffix);
- }
- if (template.getLinksCount() > 0) {
- List<MetricConditionLink> links = getLinks(template.getLinksList(), suffix);
- metric.clearLinks();
- metric.addAllLinks(links);
- }
- metric.setBucket(bucket);
- config.addGaugeMetric(metric);
- }
-
- /**
- * Creates a {@link ValueMetric} based on the template. Makes sure that all names are appended
- * with the provided suffix, and overrides the bucket size. Then adds that metric to the config.
- */
- private void addValueMetric(ValueMetric template, int suffix, TimeUnit bucket,
- StatsdConfig.Builder config) {
- ValueMetric.Builder metric = template.toBuilder()
- .setId(template.getId() + suffix)
- .setWhat(template.getWhat() + suffix);
- if (template.hasCondition()) {
- metric.setCondition(template.getCondition() + suffix);
- }
- if (template.getLinksCount() > 0) {
- List<MetricConditionLink> links = getLinks(template.getLinksList(), suffix);
- metric.clearLinks();
- metric.addAllLinks(links);
- }
- metric.setBucket(bucket);
- config.addValueMetric(metric);
- }
-
- /**
- * Creates a {@link Predicate} based on the template. Makes sure that all names
- * are appended with the provided suffix. Then adds that predicate to the config.
- */
- private void addPredicate(Predicate template, int suffix, StatsdConfig.Builder config) {
- Predicate.Builder predicate = template.toBuilder()
- .setId(template.getId() + suffix);
- if (template.hasCombination()) {
- Predicate.Combination.Builder cb = template.getCombination().toBuilder()
- .clearPredicate();
- for (long child : template.getCombination().getPredicateList()) {
- cb.addPredicate(child + suffix);
- }
- predicate.setCombination(cb.build());
- }
- if (template.hasSimplePredicate()) {
- SimplePredicate.Builder sc = template.getSimplePredicate().toBuilder()
- .setStart(template.getSimplePredicate().getStart() + suffix)
- .setStop(template.getSimplePredicate().getStop() + suffix);
- if (template.getSimplePredicate().hasStopAll()) {
- sc.setStopAll(template.getSimplePredicate().getStopAll() + suffix);
- }
- predicate.setSimplePredicate(sc.build());
- }
- config.addPredicate(predicate);
- }
-
- /**
- * Creates a {@link AtomMatcher} based on the template. Makes sure that all names
- * are appended with the provided suffix. Then adds that matcher to the config.
- */
- private void addMatcher(AtomMatcher template, int suffix, StatsdConfig.Builder config) {
- AtomMatcher.Builder matcher = template.toBuilder()
- .setId(template.getId() + suffix);
- if (template.hasCombination()) {
- AtomMatcher.Combination.Builder cb = template.getCombination().toBuilder()
- .clearMatcher();
- for (long child : template.getCombination().getMatcherList()) {
- cb.addMatcher(child + suffix);
- }
- matcher.setCombination(cb);
- }
- config.addAtomMatcher(matcher);
- }
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/DisplayProtoUtils.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/DisplayProtoUtils.java
deleted file mode 100644
index d55f3f31fd9f..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/DisplayProtoUtils.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.text.format.DateFormat;
-
-import com.android.os.StatsLog;
-
-import java.util.List;
-
-public class DisplayProtoUtils {
- private static final int MAX_NUM_METRICS_TO_DISPLAY = 10;
-
- public static void displayLogReport(StringBuilder sb, StatsLog.ConfigMetricsReportList reports) {
- sb.append("******************** Report ********************\n");
- if (reports.hasConfigKey()) {
- sb.append("ConfigKey: ");
- com.android.os.StatsLog.ConfigMetricsReportList.ConfigKey key = reports.getConfigKey();
- sb.append("\tuid: ").append(key.getUid()).append(" id: ").append(key.getId())
- .append("\n");
- }
-
- int numMetrics = 0;
- for (StatsLog.ConfigMetricsReport report : reports.getReportsList()) {
- sb.append("StatsLogReport size: ").append(report.getMetricsCount()).append("\n");
- sb.append("Last report time:").append(getDateStr(report.getLastReportElapsedNanos())).
- append("\n");
- sb.append("Current report time:").append(getDateStr(report.getCurrentReportElapsedNanos())).
- append("\n");
- for (StatsLog.StatsLogReport log : report.getMetricsList()) {
- numMetrics++;
- if (numMetrics > MAX_NUM_METRICS_TO_DISPLAY) {
- sb.append("... output truncated\n");
- sb.append("************************************************");
- return;
- }
- sb.append("\n");
- sb.append("metric id: ").append(log.getMetricId()).append("\n");
-
- switch (log.getDataCase()) {
- case DURATION_METRICS:
- sb.append("Duration metric data\n");
- displayDurationMetricData(sb, log);
- break;
- case EVENT_METRICS:
- sb.append("Event metric data\n");
- displayEventMetricData(sb, log);
- break;
- case COUNT_METRICS:
- sb.append("Count metric data\n");
- displayCountMetricData(sb, log);
- break;
- case GAUGE_METRICS:
- sb.append("Gauge metric data\n");
- displayGaugeMetricData(sb, log);
- break;
- case VALUE_METRICS:
- sb.append("Value metric data\n");
- displayValueMetricData(sb, log);
- break;
- case DATA_NOT_SET:
- sb.append("No metric data\n");
- break;
- }
- }
- }
- sb.append("************************************************");
- }
-
- public static String getDateStr(long nanoSec) {
- return DateFormat.format("dd/MM hh:mm:ss", nanoSec/1000000).toString();
- }
-
- private static void displayDimension(StringBuilder sb, StatsLog.DimensionsValue dimensionValue) {
- sb.append(dimensionValue.getField()).append(":");
- if (dimensionValue.hasValueBool()) {
- sb.append(dimensionValue.getValueBool());
- } else if (dimensionValue.hasValueFloat()) {
- sb.append(dimensionValue.getValueFloat());
- } else if (dimensionValue.hasValueInt()) {
- sb.append(dimensionValue.getValueInt());
- } else if (dimensionValue.hasValueStr()) {
- sb.append(dimensionValue.getValueStr());
- } else if (dimensionValue.hasValueTuple()) {
- sb.append("{");
- for (StatsLog.DimensionsValue child :
- dimensionValue.getValueTuple().getDimensionsValueList()) {
- displayDimension(sb, child);
- }
- sb.append("}");
- }
- sb.append(" ");
- }
-
- public static void displayDurationMetricData(StringBuilder sb, StatsLog.StatsLogReport log) {
- StatsLog.StatsLogReport.DurationMetricDataWrapper durationMetricDataWrapper
- = log.getDurationMetrics();
- sb.append("Dimension size: ").append(durationMetricDataWrapper.getDataCount()).append("\n");
- for (StatsLog.DurationMetricData duration : durationMetricDataWrapper.getDataList()) {
- sb.append("dimension_in_what: ");
- displayDimension(sb, duration.getDimensionsInWhat());
- sb.append("\n");
- if (duration.hasDimensionsInCondition()) {
- sb.append("dimension_in_condition: ");
- displayDimension(sb, duration.getDimensionsInCondition());
- sb.append("\n");
- }
-
- for (StatsLog.DurationBucketInfo info : duration.getBucketInfoList()) {
- sb.append("\t[").append(getDateStr(info.getStartBucketElapsedNanos())).append("-")
- .append(getDateStr(info.getEndBucketElapsedNanos())).append("] -> ")
- .append(info.getDurationNanos()).append(" ns\n");
- }
- }
- }
-
- public static void displayEventMetricData(StringBuilder sb, StatsLog.StatsLogReport log) {
- sb.append("Contains ").append(log.getEventMetrics().getDataCount()).append(" events\n");
- StatsLog.StatsLogReport.EventMetricDataWrapper eventMetricDataWrapper =
- log.getEventMetrics();
- for (StatsLog.EventMetricData event : eventMetricDataWrapper.getDataList()) {
- sb.append(getDateStr(event.getElapsedTimestampNanos())).append(": ");
- sb.append(event.getAtom().getPushedCase().toString()).append("\n");
- }
- }
-
- public static void displayCountMetricData(StringBuilder sb, StatsLog.StatsLogReport log) {
- StatsLog.StatsLogReport.CountMetricDataWrapper countMetricDataWrapper
- = log.getCountMetrics();
- sb.append("Dimension size: ").append(countMetricDataWrapper.getDataCount()).append("\n");
- for (StatsLog.CountMetricData count : countMetricDataWrapper.getDataList()) {
- sb.append("dimension_in_what: ");
- displayDimension(sb, count.getDimensionsInWhat());
- sb.append("\n");
- if (count.hasDimensionsInCondition()) {
- sb.append("dimension_in_condition: ");
- displayDimension(sb, count.getDimensionsInCondition());
- sb.append("\n");
- }
-
- for (StatsLog.CountBucketInfo info : count.getBucketInfoList()) {
- sb.append("\t[").append(getDateStr(info.getStartBucketElapsedNanos())).append("-")
- .append(getDateStr(info.getEndBucketElapsedNanos())).append("] -> ")
- .append(info.getCount()).append("\n");
- }
- }
- }
-
- public static void displayGaugeMetricData(StringBuilder sb, StatsLog.StatsLogReport log) {
- sb.append("Display me!");
- }
-
- public static void displayValueMetricData(StringBuilder sb, StatsLog.StatsLogReport log) {
- sb.append("Display me!");
- }
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/LoadtestActivity.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/LoadtestActivity.java
deleted file mode 100644
index 769f78c726e8..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/LoadtestActivity.java
+++ /dev/null
@@ -1,756 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.annotation.Nullable;
-import android.app.Activity;
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.app.StatsManager;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.graphics.Color;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.IStatsManager;
-import android.os.PowerManager;
-import android.os.PowerManager.WakeLock;
-import android.os.ServiceManager;
-import android.os.SystemClock;
-import android.text.Editable;
-import android.text.TextWatcher;
-import android.util.Log;
-import android.util.StatsLog;
-import android.view.View;
-import android.view.inputmethod.InputMethodManager;
-import android.view.MotionEvent;
-import android.view.View.OnFocusChangeListener;
-import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.CheckBox;
-import android.widget.EditText;
-import android.widget.Spinner;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import com.android.os.StatsLog.ConfigMetricsReport;
-import com.android.os.StatsLog.ConfigMetricsReportList;
-import com.android.os.StatsLog.StatsdStatsReport;
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Runs a load test for statsd.
- * How it works:
- * <ul>
- * <li> Sets up and pushes a custom config with metrics that exercise a large swath of code paths.
- * <li> Periodically logs certain atoms into logd.
- * <li> Impact on battery can be printed to logcat, or a bug report can be filed and analyzed
- * in battery Historian.
- * </ul>
- * The load depends on how demanding the config is, as well as how frequently atoms are pushsed
- * to logd. Those are all controlled by 4 adjustable parameters:
- * <ul>
- * <li> The 'replication' parameter artificially multiplies the number of metrics in the config.
- * <li> The bucket size controls the time-bucketing the aggregate metrics.
- * <li> The period parameter controls how frequently atoms are pushed to logd.
- * <li> The 'burst' parameter controls how many atoms are pushed at the same time (per period).
- * </ul>
- */
-public class LoadtestActivity extends Activity implements AdapterView.OnItemSelectedListener {
-
- private static final String TAG = "loadtest.LoadtestActivity";
- public static final String TYPE = "type";
- private static final String PUSH_ALARM = "push_alarm";
- public static final String PERF_ALARM = "perf_alarm";
- private static final String SET_REPLICATION = "set_replication";
- private static final String REPLICATION = "replication";
- private static final String START = "start";
- private static final String STOP = "stop";
- private static final Map<String, TimeUnit> TIME_UNIT_MAP = initializeTimeUnitMap();
- private static final List<String> TIME_UNIT_LABELS = initializeTimeUnitLabels();
-
- public final static class PusherAlarmReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- Intent activityIntent = new Intent(context, LoadtestActivity.class);
- activityIntent.putExtra(TYPE, PUSH_ALARM);
- context.startActivity(activityIntent);
- }
- }
-
- public final static class StopperAlarmReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- Intent activityIntent = new Intent(context, LoadtestActivity.class);
- activityIntent.putExtra(TYPE, STOP);
- context.startActivity(activityIntent);
- }
- }
-
- private static Map<String, TimeUnit> initializeTimeUnitMap() {
- Map<String, TimeUnit> labels = new HashMap();
- labels.put("1m", TimeUnit.ONE_MINUTE);
- labels.put("5m", TimeUnit.FIVE_MINUTES);
- labels.put("10m", TimeUnit.TEN_MINUTES);
- labels.put("30m", TimeUnit.THIRTY_MINUTES);
- labels.put("1h", TimeUnit.ONE_HOUR);
- labels.put("3h", TimeUnit.THREE_HOURS);
- labels.put("6h", TimeUnit.SIX_HOURS);
- labels.put("12h", TimeUnit.TWELVE_HOURS);
- labels.put("1d", TimeUnit.ONE_DAY);
- labels.put("1s", TimeUnit.CTS);
- return labels;
- }
-
- private static List<String> initializeTimeUnitLabels() {
- List<String> labels = new ArrayList();
- labels.add("1s");
- labels.add("1m");
- labels.add("5m");
- labels.add("10m");
- labels.add("30m");
- labels.add("1h");
- labels.add("3h");
- labels.add("6h");
- labels.add("12h");
- labels.add("1d");
- return labels;
- }
-
- private AlarmManager mAlarmMgr;
-
- /**
- * Used to periodically log atoms to logd.
- */
- private PendingIntent mPushPendingIntent;
-
- /**
- * Used to end the loadtest.
- */
- private PendingIntent mStopPendingIntent;
-
- private Button mStartStop;
- private EditText mReplicationText;
- private Spinner mBucketSpinner;
- private EditText mPeriodText;
- private EditText mBurstText;
- private EditText mDurationText;
- private TextView mReportText;
- private CheckBox mPlaceboCheckBox;
- private CheckBox mCountMetricCheckBox;
- private CheckBox mDurationMetricCheckBox;
- private CheckBox mEventMetricCheckBox;
- private CheckBox mValueMetricCheckBox;
- private CheckBox mGaugeMetricCheckBox;
-
- /**
- * When the load test started.
- */
- private long mStartedTimeMillis;
-
- /**
- * For measuring perf data.
- */
- private PerfData mPerfData;
-
- /**
- * For communicating with statsd.
- */
- private StatsManager mStatsManager;
-
- private PowerManager mPowerManager;
- private WakeLock mWakeLock;
-
- /**
- * If true, we only measure the effect of the loadtest infrastructure. No atom are pushed and
- * the configuration is empty.
- */
- private boolean mPlacebo;
-
- /**
- * Whether to include CountMetric in the config.
- */
- private boolean mIncludeCountMetric;
-
- /**
- * Whether to include DurationMetric in the config.
- */
- private boolean mIncludeDurationMetric;
-
- /**
- * Whether to include EventMetric in the config.
- */
- private boolean mIncludeEventMetric;
-
- /**
- * Whether to include ValueMetric in the config.
- */
- private boolean mIncludeValueMetric;
-
- /**
- * Whether to include GaugeMetric in the config.
- */
- private boolean mIncludeGaugeMetric;
-
- /**
- * The burst size.
- */
- private int mBurst;
-
- /**
- * The metrics replication.
- */
- private int mReplication;
-
- /**
- * The period, in seconds, at which batches of atoms are pushed.
- */
- private long mPeriodSecs;
-
- /**
- * The bucket size, in minutes, for aggregate metrics.
- */
- private TimeUnit mBucket;
-
- /**
- * The duration, in minutes, of the loadtest.
- */
- private long mDurationMins;
-
- /**
- * Whether the loadtest has started.
- */
- private boolean mStarted = false;
-
- /**
- * Orchestrates the logging of pushed events into logd.
- */
- private SequencePusher mPusher;
-
- /**
- * Generates statsd configs.
- */
- private ConfigFactory mFactory;
-
- /**
- * For intra-minute periods.
- */
- private final Handler mHandler = new Handler();
-
- /**
- * Number of metrics in the current config.
- */
- private int mNumMetrics;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- Log.d(TAG, "Starting loadtest Activity");
-
- setContentView(R.layout.activity_loadtest);
- mReportText = (TextView) findViewById(R.id.report_text);
- initBurst();
- initReplication();
- initBucket();
- initPeriod();
- initDuration();
- initPlacebo();
- initMetricWhitelist();
-
- // Hide the keyboard outside edit texts.
- findViewById(R.id.outside).setOnTouchListener(new View.OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- InputMethodManager imm =
- (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
- if (getCurrentFocus() != null) {
- imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
- }
- return true;
- }
- });
-
- mStartStop = findViewById(R.id.start_stop);
- mStartStop.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (mStarted) {
- stopLoadtest();
- } else {
- startLoadtest();
- }
- }
- });
-
- mAlarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
- mStatsManager = (StatsManager) getSystemService("stats");
- mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
- mFactory = new ConfigFactory(this);
- stopLoadtest();
- mReportText.setText("");
- }
-
- @Override
- public void onNewIntent(Intent intent) {
- String type = intent.getStringExtra(TYPE);
- if (type == null) {
- return;
- }
- switch (type) {
- case PERF_ALARM:
- onPerfAlarm();
- break;
- case PUSH_ALARM:
- onAlarm();
- break;
- case SET_REPLICATION:
- if (intent.hasExtra(REPLICATION)) {
- setReplication(intent.getIntExtra(REPLICATION, 0));
- }
- break;
- case START:
- startLoadtest();
- break;
- case STOP:
- stopLoadtest();
- break;
- default:
- throw new IllegalArgumentException("Unknown type: " + type);
- }
- }
-
- @Override
- public void onDestroy() {
- Log.d(TAG, "Destroying");
- mPerfData.onDestroy();
- stopLoadtest();
- clearConfigs();
- super.onDestroy();
- }
-
- @Nullable
- public StatsdStatsReport getMetadata() {
- if (!statsdRunning()) {
- return null;
- }
- if (mStatsManager != null) {
- byte[] data;
- try {
- data = mStatsManager.getStatsMetadata();
- } catch (StatsManager.StatsUnavailableException e) {
- Log.e(TAG, "Failed to get data from statsd", e);
- return null;
- }
- if (data != null) {
- StatsdStatsReport report = null;
- boolean good = false;
- try {
- return StatsdStatsReport.parseFrom(data);
- } catch (com.google.protobuf.InvalidProtocolBufferException e) {
- Log.d(TAG, "Bad StatsdStatsReport");
- }
- }
- }
- return null;
- }
-
- @Nullable
- public List<ConfigMetricsReport> getData() {
- if (!statsdRunning()) {
- return null;
- }
- if (mStatsManager != null) {
- byte[] data;
- try {
- data = mStatsManager.getReports(ConfigFactory.CONFIG_ID);
- } catch (StatsManager.StatsUnavailableException e) {
- Log.e(TAG, "Failed to get data from statsd", e);
- return null;
- }
- if (data != null) {
- ConfigMetricsReportList reports = null;
- try {
- reports = ConfigMetricsReportList.parseFrom(data);
- Log.d(TAG, "Num reports: " + reports.getReportsCount());
- StringBuilder sb = new StringBuilder();
- DisplayProtoUtils.displayLogReport(sb, reports);
- Log.d(TAG, sb.toString());
- } catch (com.google.protobuf.InvalidProtocolBufferException e) {
- Log.d(TAG, "Invalid data");
- }
- if (reports != null) {
- return reports.getReportsList();
- }
- }
- }
- return null;
- }
-
- @Override
- public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
- String item = parent.getItemAtPosition(position).toString();
-
- mBucket = TIME_UNIT_MAP.get(item);
- }
-
- @Override
- public void onNothingSelected(AdapterView<?> parent) {
- // Another interface callback
- }
-
- private void onPerfAlarm() {
- if (mPerfData != null) {
- mPerfData.onAlarm(this);
- }
- // Piggy-back on that alarm to show the elapsed time.
- long elapsedTimeMins = (long) Math.floor(
- (SystemClock.elapsedRealtime() - mStartedTimeMillis) / 60 / 1000);
- mReportText.setText("Loadtest in progress.\n"
- + "num metrics =" + mNumMetrics
- + "\nElapsed time = " + elapsedTimeMins + " min(s)");
- }
-
- private void onAlarm() {
- Log.d(TAG, "ON ALARM");
-
- // Set the next task.
- scheduleNext();
-
- // Do the work.
- mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "StatsdLoadTest");
- mWakeLock.acquire();
- if (mPusher != null) {
- mPusher.next();
- }
- mWakeLock.release();
- mWakeLock = null;
- }
-
- /**
- * Schedules the next cycle of pushing atoms into logd.
- */
- private void scheduleNext() {
- Intent intent = new Intent(this, PusherAlarmReceiver.class);
- intent.putExtra(TYPE, PUSH_ALARM);
- mPushPendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
- long nextTime = SystemClock.elapsedRealtime() + mPeriodSecs * 1000;
- mAlarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextTime, mPushPendingIntent);
- }
-
- private synchronized void startLoadtest() {
- if (mStarted) {
- return;
- }
-
- // Clean up the state.
- stopLoadtest();
-
- // Prepare to push a sequence of atoms to logd.
- mPusher = new SequencePusher(mBurst, mPlacebo);
-
- // Create a config and push it to statsd.
- if (!setConfig(mFactory.getConfig(mReplication, mBucket, mPlacebo,
- mIncludeCountMetric, mIncludeDurationMetric, mIncludeEventMetric,
- mIncludeValueMetric, mIncludeGaugeMetric))) {
- return;
- }
-
- // Remember to stop in the future.
- Intent intent = new Intent(this, StopperAlarmReceiver.class);
- intent.putExtra(TYPE, STOP);
- mStopPendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
- long nextTime = SystemClock.elapsedRealtime() + mDurationMins * 60 * 1000;
- mAlarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextTime, mStopPendingIntent);
-
- // Log atoms.
- scheduleNext();
-
- // Start tracking performance.
- mPerfData = new PerfData(this, mPlacebo, mReplication, mBucket, mPeriodSecs, mBurst,
- mIncludeCountMetric, mIncludeDurationMetric, mIncludeEventMetric, mIncludeValueMetric,
- mIncludeGaugeMetric);
- mPerfData.startRecording(this);
-
- mReportText.setText("Loadtest in progress.\nnum metrics =" + mNumMetrics);
- mStartedTimeMillis = SystemClock.elapsedRealtime();
-
- updateStarted(true);
- }
-
- private synchronized void stopLoadtest() {
- if (mPushPendingIntent != null) {
- Log.d(TAG, "Canceling pre-existing push alarm");
- mAlarmMgr.cancel(mPushPendingIntent);
- mPushPendingIntent = null;
- }
- if (mStopPendingIntent != null) {
- Log.d(TAG, "Canceling pre-existing stop alarm");
- mAlarmMgr.cancel(mStopPendingIntent);
- mStopPendingIntent = null;
- }
- if (mWakeLock != null) {
- mWakeLock.release();
- mWakeLock = null;
- }
- if (mPerfData != null) {
- mPerfData.stopRecording(this);
- mPerfData.onDestroy();
- mPerfData = null;
- }
-
- // Obtain the latest data and display it.
- getData();
-
- long elapsedTimeMins = (long) Math.floor(
- (SystemClock.elapsedRealtime() - mStartedTimeMillis) / 60 / 1000);
- mReportText.setText("Loadtest ended. Elapsed time = " + elapsedTimeMins + " min(s)");
- clearConfigs();
- updateStarted(false);
- }
-
- private synchronized void updateStarted(boolean started) {
- mStarted = started;
- mStartStop.setBackgroundColor(started ?
- Color.parseColor("#FFFF0000") : Color.parseColor("#FF00FF00"));
- mStartStop.setText(started ? getString(R.string.stop) : getString(R.string.start));
- updateControlsEnabled();
- }
-
- private void updateControlsEnabled() {
- mBurstText.setEnabled(!mPlacebo && !mStarted);
- mReplicationText.setEnabled(!mPlacebo && !mStarted);
- mPeriodText.setEnabled(!mStarted);
- mBucketSpinner.setEnabled(!mPlacebo && !mStarted);
- mDurationText.setEnabled(!mStarted);
- mPlaceboCheckBox.setEnabled(!mStarted);
-
- boolean enabled = !mStarted && !mPlaceboCheckBox.isChecked();
- mCountMetricCheckBox.setEnabled(enabled);
- mDurationMetricCheckBox.setEnabled(enabled);
- mEventMetricCheckBox.setEnabled(enabled);
- mValueMetricCheckBox.setEnabled(enabled);
- mGaugeMetricCheckBox.setEnabled(enabled);
- }
-
- private boolean statsdRunning() {
- if (IStatsManager.Stub.asInterface(ServiceManager.getService("stats")) == null) {
- Log.d(TAG, "Statsd not running");
- Toast.makeText(LoadtestActivity.this, "Statsd NOT running!", Toast.LENGTH_LONG).show();
- return false;
- }
- return true;
- }
-
- private int sanitizeInt(int val, int min, int max) {
- if (val > max) {
- val = max;
- } else if (val < min) {
- val = min;
- }
- return val;
- }
-
- private void clearConfigs() {
- // TODO: Clear all configs instead of specific ones.
- if (mStatsManager != null) {
- if (mStarted) {
- try {
- mStatsManager.removeConfig(ConfigFactory.CONFIG_ID);
- Log.d(TAG, "Removed loadtest statsd configs.");
- } catch (StatsManager.StatsUnavailableException e) {
- Log.e(TAG, "Failed to remove loadtest configs.", e);
- }
- }
- }
- }
-
- private boolean setConfig(ConfigFactory.ConfigMetadata configData) {
- if (mStatsManager != null) {
- try {
- mStatsManager.addConfig(ConfigFactory.CONFIG_ID, configData.bytes);
- mNumMetrics = configData.numMetrics;
- Log.d(TAG, "Config pushed to statsd");
- return true;
- } catch (StatsManager.StatsUnavailableException | IllegalArgumentException e) {
- Log.e(TAG, "Failed to push config to statsd", e);
- }
- }
- return false;
- }
-
- private synchronized void setReplication(int replication) {
- if (mStarted) {
- return;
- }
- mReplicationText.setText("" + replication);
- }
-
- private synchronized void setPeriodSecs(long periodSecs) {
- mPeriodSecs = periodSecs;
- }
-
- private synchronized void setBurst(int burst) {
- mBurst = burst;
- }
-
- private synchronized void setDurationMins(long durationMins) {
- mDurationMins = durationMins;
- }
-
-
- private void handleFocus(EditText editText) {
- /*
- editText.setOnFocusChangeListener(new OnFocusChangeListener() {
- @Override
- public void onFocusChange(View v, boolean hasFocus) {
- if (!hasFocus && editText.getText().toString().isEmpty()) {
- editText.setText("-1", TextView.BufferType.EDITABLE);
- }
- }
- });
- */
- }
-
- private void initBurst() {
- mBurst = getResources().getInteger(R.integer.burst_default);
- mBurstText = (EditText) findViewById(R.id.burst);
- mBurstText.addTextChangedListener(new NumericalWatcher(mBurstText, 0, 1000) {
- @Override
- public void onNewValue(int newValue) {
- setBurst(newValue);
- }
- });
- handleFocus(mBurstText);
- }
-
- private void initReplication() {
- mReplication = getResources().getInteger(R.integer.replication_default);
- mReplicationText = (EditText) findViewById(R.id.replication);
- mReplicationText.addTextChangedListener(new NumericalWatcher(mReplicationText, 1, 4096) {
- @Override
- public void onNewValue(int newValue) {
- mReplication = newValue;
- }
- });
- handleFocus(mReplicationText);
- }
-
- private void initBucket() {
- String defaultValue = getResources().getString(R.string.bucket_default);
- mBucket = TimeUnit.valueOf(defaultValue);
- mBucketSpinner = (Spinner) findViewById(R.id.bucket_spinner);
-
- ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
- this, R.layout.spinner_item, TIME_UNIT_LABELS);
-
- mBucketSpinner.setAdapter(dataAdapter);
- mBucketSpinner.setOnItemSelectedListener(this);
-
- for (String label : TIME_UNIT_MAP.keySet()) {
- if (defaultValue.equals(TIME_UNIT_MAP.get(label).toString())) {
- mBucketSpinner.setSelection(dataAdapter.getPosition(label));
- }
- }
- }
-
- private void initPeriod() {
- mPeriodSecs = getResources().getInteger(R.integer.period_default);
- mPeriodText = (EditText) findViewById(R.id.period);
- mPeriodText.addTextChangedListener(new NumericalWatcher(mPeriodText, 1, 60) {
- @Override
- public void onNewValue(int newValue) {
- setPeriodSecs(newValue);
- }
- });
- handleFocus(mPeriodText);
- }
-
- private void initDuration() {
- mDurationMins = getResources().getInteger(R.integer.duration_default);
- mDurationText = (EditText) findViewById(R.id.duration);
- mDurationText.addTextChangedListener(new NumericalWatcher(mDurationText, 1, 24 * 60) {
- @Override
- public void onNewValue(int newValue) {
- setDurationMins(newValue);
- }
- });
- handleFocus(mDurationText);
- }
-
- private void initPlacebo() {
- mPlaceboCheckBox = findViewById(R.id.placebo);
- mPlacebo = false;
- mPlaceboCheckBox.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- mPlacebo = mPlaceboCheckBox.isChecked();
- updateControlsEnabled();
- }
- });
- }
-
- private void initMetricWhitelist() {
- mCountMetricCheckBox = findViewById(R.id.include_count);
- mCountMetricCheckBox.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- mIncludeCountMetric = mCountMetricCheckBox.isChecked();
- }
- });
- mDurationMetricCheckBox = findViewById(R.id.include_duration);
- mDurationMetricCheckBox.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- mIncludeDurationMetric = mDurationMetricCheckBox.isChecked();
- }
- });
- mEventMetricCheckBox = findViewById(R.id.include_event);
- mEventMetricCheckBox.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- mIncludeEventMetric = mEventMetricCheckBox.isChecked();
- }
- });
- mValueMetricCheckBox = findViewById(R.id.include_value);
- mValueMetricCheckBox.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- mIncludeValueMetric = mValueMetricCheckBox.isChecked();
- }
- });
- mGaugeMetricCheckBox = findViewById(R.id.include_gauge);
- mGaugeMetricCheckBox.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- mIncludeGaugeMetric = mGaugeMetricCheckBox.isChecked();
- }
- });
-
- mIncludeCountMetric = mCountMetricCheckBox.isChecked();
- mIncludeDurationMetric = mDurationMetricCheckBox.isChecked();
- mIncludeEventMetric = mEventMetricCheckBox.isChecked();
- mIncludeValueMetric = mValueMetricCheckBox.isChecked();
- mIncludeGaugeMetric = mGaugeMetricCheckBox.isChecked();
- }
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/MemInfoParser.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/MemInfoParser.java
deleted file mode 100644
index 01eebf2ad1cf..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/MemInfoParser.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.annotation.Nullable;
-import android.os.SystemClock;
-import android.util.Log;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/** Parses PSS info from dumpsys meminfo */
-public class MemInfoParser implements PerfParser {
-
- private static final Pattern LINE_PATTERN =
- Pattern.compile("\\s*(\\d*,*\\d*)K:\\s(\\S*)\\s\\.*");
- private static final String PSS_BY_PROCESS = "Total PSS by process:";
- private static final String TAG = "loadtest.MemInfoParser";
-
- private boolean mPssStarted;
- private boolean mPssEnded;
- private final long mStartTimeMillis;
-
- public MemInfoParser(long startTimeMillis) {
- mStartTimeMillis = startTimeMillis;
- }
-
- @Override
- @Nullable
- public String parseLine(String line) {
- if (mPssEnded) {
- return null;
- }
- if (!mPssStarted) {
- if (line.contains(PSS_BY_PROCESS)) {
- mPssStarted = true;
- }
- return null;
- }
- if (line.isEmpty()) {
- mPssEnded = true;
- return null;
- }
- Matcher lineMatcher = LINE_PATTERN.matcher(line);
- if (lineMatcher.find() && lineMatcher.group(1) != null && lineMatcher.group(2) != null) {
- if (lineMatcher.group(2).equals("statsd")) {
- long timeDeltaMillis = SystemClock.elapsedRealtime() - mStartTimeMillis;
- return timeDeltaMillis + "," + convertToPss(lineMatcher.group(1));
- }
- }
- return null;
- }
-
- private String convertToPss(String input) {
- return input.replace(",", "");
- }
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/MemoryDataRecorder.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/MemoryDataRecorder.java
deleted file mode 100644
index af7bd4d35966..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/MemoryDataRecorder.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.content.Context;
-import android.os.SystemClock;
-import android.util.Log;
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-
-public class MemoryDataRecorder extends PerfDataRecorder {
- private static final String TAG = "loadtest.MemoryDataDataRecorder";
- private static final String DUMP_FILENAME = TAG + "_dump.tmp";
-
- private long mStartTimeMillis;
- private StringBuilder mSb;
-
- public MemoryDataRecorder(boolean placebo, int replication, TimeUnit bucket, long periodSecs,
- int burst, boolean includeCountMetric, boolean includeDurationMetric,
- boolean includeEventMetric, boolean includeValueMetric, boolean includeGaugeMetric) {
- super(placebo, replication, bucket, periodSecs, burst, includeCountMetric,
- includeDurationMetric, includeEventMetric, includeValueMetric, includeGaugeMetric);
- }
-
- @Override
- public void startRecording(Context context) {
- mStartTimeMillis = SystemClock.elapsedRealtime();
- mSb = new StringBuilder();
- }
-
- @Override
- public void onAlarm(Context context) {
- runDumpsysStats(context, DUMP_FILENAME, "meminfo");
- readDumpData(context, DUMP_FILENAME, new MemInfoParser(mStartTimeMillis), mSb);
- }
-
- @Override
- public void stopRecording(Context context) {
- writeData(context, "meminfo_", "time,pss", mSb);
- }
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/NumericalWatcher.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/NumericalWatcher.java
deleted file mode 100644
index 555e6dd2d99d..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/NumericalWatcher.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.text.Editable;
-import android.text.TextWatcher;
-import android.util.Log;
-import android.widget.TextView;
-
-public abstract class NumericalWatcher implements TextWatcher {
-
- private static final String TAG = "loadtest.NumericalWatcher";
-
- private final TextView mTextView;
- private final int mMin;
- private final int mMax;
- private int currentValue = -1;
-
- public NumericalWatcher(TextView textView, int min, int max) {
- mTextView = textView;
- mMin = min;
- mMax = max;
- }
-
- public abstract void onNewValue(int newValue);
-
- @Override
- final public void afterTextChanged(Editable editable) {
- String s = mTextView.getText().toString();
- if (s.isEmpty()) {
- return;
- }
- int unsanitized = Integer.parseInt(s);
- int newValue = sanitize(unsanitized);
- if (currentValue != newValue || unsanitized != newValue) {
- currentValue = newValue;
- editable.clear();
- editable.append(newValue + "");
- }
- onNewValue(newValue);
- }
-
- @Override
- final public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
-
- @Override
- final public void onTextChanged(CharSequence s, int start, int before, int count) {}
-
- private int sanitize(int val) {
- if (val > mMax) {
- val = mMax;
- } else if (val < mMin) {
- val = mMin;
- }
- return val;
- }
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/PerfData.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/PerfData.java
deleted file mode 100644
index 7a01adedfaa4..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/PerfData.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-
-import android.annotation.Nullable;
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.os.SystemClock;
-import android.util.Log;
-
-import java.util.HashSet;
-import java.util.Set;
-
-/** Prints some information about the device via Dumpsys in order to evaluate health metrics. */
-public class PerfData extends PerfDataRecorder {
-
- private static final String TAG = "loadtest.PerfData";
-
- /** Polling period for performance snapshots like memory. */
- private static final long POLLING_PERIOD_MILLIS = 1 * 60 * 1000;
-
- public final static class PerfAlarmReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- Intent activityIntent = new Intent(context, LoadtestActivity.class);
- activityIntent.putExtra(LoadtestActivity.TYPE, LoadtestActivity.PERF_ALARM);
- context.startActivity(activityIntent);
- }
- }
-
- private AlarmManager mAlarmMgr;
-
- /** Used to periodically poll some dumpsys data. */
- private PendingIntent mPendingIntent;
-
- private final Set<PerfDataRecorder> mRecorders;
-
- public PerfData(LoadtestActivity loadtestActivity, boolean placebo, int replication,
- TimeUnit bucket, long periodSecs, int burst, boolean includeCountMetric,
- boolean includeDurationMetric, boolean includeEventMetric, boolean includeValueMetric,
- boolean includeGaugeMetric) {
- super(placebo, replication, bucket, periodSecs, burst, includeCountMetric,
- includeDurationMetric, includeEventMetric, includeValueMetric, includeGaugeMetric);
- mRecorders = new HashSet();
- mRecorders.add(new BatteryDataRecorder(placebo, replication, bucket, periodSecs, burst,
- includeCountMetric, includeDurationMetric, includeEventMetric, includeValueMetric,
- includeGaugeMetric));
- mRecorders.add(new MemoryDataRecorder(placebo, replication, bucket, periodSecs, burst,
- includeCountMetric, includeDurationMetric, includeEventMetric, includeValueMetric,
- includeGaugeMetric));
- mRecorders.add(new StatsdStatsRecorder(loadtestActivity, placebo, replication, bucket,
- periodSecs, burst, includeCountMetric, includeDurationMetric, includeEventMetric,
- includeValueMetric, includeGaugeMetric));
- mRecorders.add(new ValidationRecorder(loadtestActivity, placebo, replication, bucket,
- periodSecs, burst, includeCountMetric, includeDurationMetric, includeEventMetric,
- includeValueMetric, includeGaugeMetric));
- mAlarmMgr = (AlarmManager) loadtestActivity.getSystemService(Context.ALARM_SERVICE);
- }
-
- public void onDestroy() {
- if (mPendingIntent != null) {
- mAlarmMgr.cancel(mPendingIntent);
- mPendingIntent = null;
- }
- }
-
- @Override
- public void startRecording(Context context) {
- Intent intent = new Intent(context, PerfAlarmReceiver.class);
- intent.putExtra(LoadtestActivity.TYPE, LoadtestActivity.PERF_ALARM);
- mPendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
- mAlarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, -1 /* now */,
- POLLING_PERIOD_MILLIS, mPendingIntent);
-
- for (PerfDataRecorder recorder : mRecorders) {
- recorder.startRecording(context);
- }
- }
-
- @Override
- public void onAlarm(Context context) {
- for (PerfDataRecorder recorder : mRecorders) {
- recorder.onAlarm(context);
- }
- }
-
- @Override
- public void stopRecording(Context context) {
- if (mPendingIntent != null) {
- mAlarmMgr.cancel(mPendingIntent);
- mPendingIntent = null;
- }
-
- for (PerfDataRecorder recorder : mRecorders) {
- recorder.stopRecording(context);
- }
- }
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/PerfDataRecorder.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/PerfDataRecorder.java
deleted file mode 100644
index 8613ac1c4796..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/PerfDataRecorder.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.annotation.Nullable;
-import android.content.Context;
-import android.os.Environment;
-import android.util.Log;
-import android.os.Debug;
-
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-import java.io.BufferedReader;
-import java.io.Closeable;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.InputStreamReader;
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-public abstract class PerfDataRecorder {
- private static final String TAG = "loadtest.PerfDataRecorder";
-
- protected final String mTimeAsString;
- protected final String mColumnSuffix;
-
- protected PerfDataRecorder(boolean placebo, int replication, TimeUnit bucket, long periodSecs,
- int burst, boolean includeCountMetric, boolean includeDurationMetric,
- boolean includeEventMetric, boolean includeValueMetric, boolean includeGaugeMetric) {
- mTimeAsString = new SimpleDateFormat("YYYY_MM_dd_HH_mm_ss").format(new Date());
- mColumnSuffix = getColumnSuffix(placebo, replication, bucket, periodSecs, burst,
- includeCountMetric, includeDurationMetric, includeEventMetric, includeValueMetric,
- includeGaugeMetric);
- }
-
- /** Starts recording performance data. */
- public abstract void startRecording(Context context);
-
- /** Called periodically. For the recorder to sample data, if needed. */
- public abstract void onAlarm(Context context);
-
- /** Stops recording performance data, and writes it to disk. */
- public abstract void stopRecording(Context context);
-
- /** Runs the dumpsys command. */
- protected void runDumpsysStats(Context context, String dumpFilename, String cmd,
- String... args) {
- boolean success = false;
- // Call dumpsys Dump statistics to a file.
- FileOutputStream fo = null;
- try {
- fo = context.openFileOutput(dumpFilename, Context.MODE_PRIVATE);
- if (!Debug.dumpService(cmd, fo.getFD(), args)) {
- Log.w(TAG, "Dumpsys failed.");
- }
- success = true;
- } catch (IOException | SecurityException | NullPointerException e) {
- // SecurityException may occur when trying to dump multi-user info.
- // NPE can occur during dumpService (root cause unknown).
- throw new RuntimeException(e);
- } finally {
- closeQuietly(fo);
- }
- }
-
- /**
- * Reads a text file and parses each line, one by one. The result of the parsing is stored
- * in the passed {@link StringBuffer}.
- */
- protected void readDumpData(Context context, String dumpFilename, PerfParser parser,
- StringBuilder sb) {
- FileInputStream fi = null;
- BufferedReader br = null;
- try {
- fi = context.openFileInput(dumpFilename);
- br = new BufferedReader(new InputStreamReader(fi));
- String line = br.readLine();
- while (line != null) {
- String recordLine = parser.parseLine(line);
- if (recordLine != null) {
- sb.append(recordLine).append('\n');
- }
- line = br.readLine();
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- } finally {
- closeQuietly(br);
- }
- }
-
- /** Writes CSV data to a file. */
- protected void writeData(Context context, String filePrefix, String columnPrefix,
- StringBuilder sb) {
- File dataFile = new File(getStorageDir(), filePrefix + mTimeAsString + ".csv");
-
- FileWriter writer = null;
- try {
- writer = new FileWriter(dataFile);
- writer.append(columnPrefix + mColumnSuffix + "\n");
- writer.append(sb.toString());
- writer.flush();
- Log.d(TAG, "Finished writing data at " + dataFile.getAbsolutePath());
- } catch (IOException e) {
- throw new RuntimeException(e);
- } finally {
- closeQuietly(writer);
- }
- }
-
- /** Gets the suffix to use in the column name for perf data. */
- private String getColumnSuffix(boolean placebo, int replication, TimeUnit bucket,
- long periodSecs, int burst, boolean includeCountMetric, boolean includeDurationMetric,
- boolean includeEventMetric, boolean includeValueMetric, boolean includeGaugeMetric) {
- if (placebo) {
- return "_placebo_p=" + periodSecs;
- }
- StringBuilder sb = new StringBuilder()
- .append("_r=" + replication)
- .append("_bkt=" + bucket)
- .append("_p=" + periodSecs)
- .append("_bst=" + burst)
- .append("_m=");
- if (includeCountMetric) {
- sb.append("c");
- }
- if (includeEventMetric) {
- sb.append("e");
- }
- if (includeDurationMetric) {
- sb.append("d");
- }
- if (includeGaugeMetric) {
- sb.append("g");
- }
- if (includeValueMetric) {
- sb.append("v");
- }
- return sb.toString();
- }
-
- private File getStorageDir() {
- File file = new File(Environment.getExternalStoragePublicDirectory(
- Environment.DIRECTORY_DOCUMENTS), "loadtest/" + mTimeAsString);
- if (!file.mkdirs()) {
- Log.e(TAG, "Directory not created");
- }
- return file;
- }
-
- private void closeQuietly(@Nullable Closeable c) {
- if (c != null) {
- try {
- c.close();
- } catch (IOException ignore) {
- }
- }
- }
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/PerfParser.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/PerfParser.java
deleted file mode 100644
index e000918fa0f7..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/PerfParser.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.annotation.Nullable;
-
-public interface PerfParser {
-
- /**
- * Parses one line of the dumpsys output, and returns a string to write to the data file,
- * or null if no string should be written.
- */
- @Nullable String parseLine(String line);
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/SequencePusher.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/SequencePusher.java
deleted file mode 100644
index 5dcce9acb401..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/SequencePusher.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.util.Log;
-import android.util.StatsLog;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Manages the pushing of atoms into logd for loadtesting.
- * We rely on small number of pushed atoms, and a config with metrics based on those atoms.
- * The atoms are:
- * <ul>
- * <li> BatteryLevelChanged - For EventMetric, CountMetric and GaugeMetric (no dimensions).
- * <li> BleScanResultReceived - For CountMetric and ValueMetric, sliced by uid.
- * <li> ChargingStateChanged - For DurationMetric (no dimension).
- * <li> GpsScanStateChanged - For DurationMetric, sliced by uid.
- * <li> ScreenStateChanged - For Conditions with no dimensions.
- * <li> AudioStateChanged - For Conditions with dimensions (uid).
- * </ul>
- * The sequence is played over and over at a given frequency.
- */
-public class SequencePusher {
- private static final String TAG = "SequencePusher";
-
- /** Some atoms are pushed in burst of {@code mBurst} events. */
- private final int mBurst;
-
- /** If this is true, we don't log anything in logd. */
- private final boolean mPlacebo;
-
- /** Current state in the automaton. */
- private int mCursor = 0;
-
- public SequencePusher(int burst, boolean placebo) {
- mBurst = burst;
- mPlacebo = placebo;
- }
-
- /**
- * Pushes the next atom to logd.
- * This follows a small automaton which makes the right events and conditions overlap:
- * (0) Push a burst of BatteryLevelChanged atoms.
- * (1) Push a burst of BleScanResultReceived atoms.
- * (2) Push ChargingStateChanged with BATTERY_STATUS_CHARGING once.
- * (3) Push a burst of GpsScanStateChanged atoms with ON, with a different uid each time.
- * (4) Push ChargingStateChanged with BATTERY_STATUS_NOT_CHARGING once.
- * (5) Push a burst GpsScanStateChanged atoms with OFF, with a different uid each time.
- * (6) Push ScreenStateChanged with STATE_ON once.
- * (7) Push a burst of AudioStateChanged with ON, with a different uid each time.
- * (8) Repeat steps (0)-(5).
- * (9) Push ScreenStateChanged with STATE_OFF once.
- * (10) Push a burst of AudioStateChanged with OFF, with a different uid each time.
- * and repeat.
- */
- public void next() {
- Log.d(TAG, "Next step: " + mCursor);
- if (mPlacebo) {
- return;
- }
- switch (mCursor) {
- case 0:
- case 8:
- for (int i = 0; i < mBurst; i++) {
- StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, 50 + i /* battery_level */);
- }
- break;
- case 1:
- case 9:
- for (int i = 0; i < mBurst; i++) {
- StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED, i /* uid */,
- 100 /* num_of_results */);
- }
- break;
- case 2:
- case 10:
- StatsLog.write(StatsLog.CHARGING_STATE_CHANGED,
- StatsLog.CHARGING_STATE_CHANGED__STATE__BATTERY_STATUS_CHARGING
- /* charging_state */);
- break;
- case 3:
- case 11:
- for (int i = 0; i < mBurst; i++) {
- StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, i /* uid */,
- StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON /* state */);
- }
- break;
- case 4:
- case 12:
- StatsLog.write(StatsLog.CHARGING_STATE_CHANGED,
- StatsLog.CHARGING_STATE_CHANGED__STATE__BATTERY_STATUS_NOT_CHARGING
- /* charging_state */);
- break;
- case 5:
- case 13:
- for (int i = 0; i < mBurst; i++) {
- StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, i /* uid */,
- StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF /* state */);
- }
- break;
- case 6:
- StatsLog.write(StatsLog.SCREEN_STATE_CHANGED,
- StatsLog.SCREEN_STATE_CHANGED__STATE__DISPLAY_STATE_ON /* display_state */);
- break;
- case 7:
- for (int i = 0; i < mBurst; i++) {
- StatsLog.write(StatsLog.AUDIO_STATE_CHANGED, i /* uid */,
- StatsLog.AUDIO_STATE_CHANGED__STATE__ON /* state */);
- }
- break;
- case 14:
- StatsLog.write(StatsLog.SCREEN_STATE_CHANGED,
- StatsLog.SCREEN_STATE_CHANGED__STATE__DISPLAY_STATE_OFF /* display_state */);
- break;
- case 15:
- for (int i = 0; i < mBurst; i++) {
- StatsLog.write(StatsLog.AUDIO_STATE_CHANGED, i /* uid */,
- StatsLog.AUDIO_STATE_CHANGED__STATE__OFF /* state */);
- }
- break;
- default:
- }
- mCursor++;
- if (mCursor > 15) {
- mCursor = 0;
- }
- }
-
- /**
- * Properly finishes in order to be close all conditions and durations.
- */
- public void finish() {
- // Screen goes back to off. This will ensure that conditions get back to false.
- StatsLog.write(StatsLog.SCREEN_STATE_CHANGED,
- StatsLog.SCREEN_STATE_CHANGED__STATE__DISPLAY_STATE_OFF /* display_state */);
- for (int i = 0; i < mBurst; i++) {
- StatsLog.write(StatsLog.AUDIO_STATE_CHANGED, i /* uid */,
- StatsLog.AUDIO_STATE_CHANGED__STATE__OFF /* state */);
- }
- // Stop charging, to ensure the corresponding durations are closed.
- StatsLog.write(StatsLog.CHARGING_STATE_CHANGED,
- StatsLog.CHARGING_STATE_CHANGED__STATE__BATTERY_STATUS_NOT_CHARGING
- /* charging_state */);
- // Stop scanning GPS, to ensure the corresponding conditions get back to false.
- for (int i = 0; i < mBurst; i++) {
- StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, i /* uid */,
- StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF /* state */);
- }
- }
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/StatsdStatsRecorder.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/StatsdStatsRecorder.java
deleted file mode 100644
index 3939e7e0b2fa..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/StatsdStatsRecorder.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.content.Context;
-import com.android.os.StatsLog.StatsdStatsReport;
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-
-public class StatsdStatsRecorder extends PerfDataRecorder {
- private static final String TAG = "loadtest.StatsdStatsRecorder";
-
- private final LoadtestActivity mLoadtestActivity;
-
- public StatsdStatsRecorder(LoadtestActivity loadtestActivity, boolean placebo, int replication,
- TimeUnit bucket, long periodSecs, int burst, boolean includeCountMetric,
- boolean includeDurationMetric, boolean includeEventMetric, boolean includeValueMetric,
- boolean includeGaugeMetric) {
- super(placebo, replication, bucket, periodSecs, burst, includeCountMetric,
- includeDurationMetric, includeEventMetric, includeValueMetric, includeGaugeMetric);
- mLoadtestActivity = loadtestActivity;
- }
-
- @Override
- public void startRecording(Context context) {
- // Nothing to do.
- }
-
- @Override
- public void onAlarm(Context context) {
- // Nothing to do.
- }
-
- @Override
- public void stopRecording(Context context) {
- StatsdStatsReport metadata = mLoadtestActivity.getMetadata();
- if (metadata != null) {
- int numConfigs = metadata.getConfigStatsCount();
- StringBuilder sb = new StringBuilder();
- StatsdStatsReport.ConfigStats configStats = metadata.getConfigStats(numConfigs - 1);
- sb.append("metric_count,")
- .append(configStats.getMetricCount() + "\n")
- .append("condition_count,")
- .append(configStats.getConditionCount() + "\n")
- .append("matcher_count,")
- .append(configStats.getMatcherCount() + "\n");
- writeData(context, "statsdstats_", "stat,value", sb);
- }
- }
-}
diff --git a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/ValidationRecorder.java b/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/ValidationRecorder.java
deleted file mode 100644
index d9f0ca9d2461..000000000000
--- a/cmds/statsd/tools/loadtest/src/com/android/statsd/loadtest/ValidationRecorder.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.statsd.loadtest;
-
-import android.content.Context;
-import android.util.Log;
-import com.android.os.StatsLog.ConfigMetricsReport;
-import com.android.os.StatsLog.EventMetricData;
-import com.android.os.StatsLog.StatsLogReport;
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Checks the correctness of the stats.
- */
-public class ValidationRecorder extends PerfDataRecorder {
- private static final String TAG = "loadtest.ValidationRecorder";
-
- private final LoadtestActivity mLoadtestActivity;
-
- public ValidationRecorder(LoadtestActivity loadtestActivity, boolean placebo, int replication,
- TimeUnit bucket, long periodSecs, int burst, boolean includeCountMetric,
- boolean includeDurationMetric, boolean includeEventMetric, boolean includeValueMetric,
- boolean includeGaugeMetric) {
- super(placebo, replication, bucket, periodSecs, burst, includeCountMetric,
- includeDurationMetric, includeEventMetric, includeValueMetric, includeGaugeMetric);
- mLoadtestActivity = loadtestActivity;
- }
-
- @Override
- public void startRecording(Context context) {
- // Nothing to do.
- }
-
- @Override
- public void onAlarm(Context context) {
- validateData();
- }
-
- @Override
- public void stopRecording(Context context) {
- validateData();
- }
-
- private void validateData() {
- // The code below is commented out because it calls getData, which has the side-effect
- // of clearing statsd's data buffer.
- /*
- List<ConfigMetricsReport> reports = mLoadtestActivity.getData();
- if (reports != null) {
- Log.d(TAG, "GOT DATA");
- for (ConfigMetricsReport report : reports) {
- for (StatsLogReport logReport : report.getMetricsList()) {
- if (!logReport.hasMetricId()) {
- Log.e(TAG, "Metric missing name.");
- }
- }
- }
- }
- */
- }
-
- private void validateEventBatteryLevelChanges(StatsLogReport logReport) {
- Log.d(TAG, "Validating " + logReport.getMetricId());
- if (logReport.hasEventMetrics()) {
- Log.d(TAG, "Num events captured: " + logReport.getEventMetrics().getDataCount());
- for (EventMetricData data : logReport.getEventMetrics().getDataList()) {
- Log.d(TAG, " Event : " + data.getAtom());
- }
- } else {
- Log.d(TAG, "Metric is invalid");
- }
- }
-
- private void validateEventBatteryLevelChangesWhileScreenIsOn(StatsLogReport logReport) {
- Log.d(TAG, "Validating " + logReport.getMetricId());
- }
-}