Only create ProtoOutputStream when onGetData() is called.

The exception is EventMetricProducer. Each EventMetricProducer will still have a ProtoOutputStream
Because LogEvent comes as a fixed 4K, it's more memory efficient to have an 8k ProtoOutputStream for
storing the events.

Also removed finish() api in MetricProducer, which was intended to use with Dropbox.

Test: statsd_test & dogfood app
Bug: 70393808
Change-Id: I2efe4ecc76a88060a9aa5eb49d1fa6ea60bc5da8
diff --git a/cmds/statsd/src/metrics/MetricsManager.cpp b/cmds/statsd/src/metrics/MetricsManager.cpp
index 9fdc6fa..0510fff 100644
--- a/cmds/statsd/src/metrics/MetricsManager.cpp
+++ b/cmds/statsd/src/metrics/MetricsManager.cpp
@@ -27,6 +27,11 @@
 #include "stats_util.h"
 
 #include <log/logprint.h>
+
+using android::util::FIELD_COUNT_REPEATED;
+using android::util::FIELD_TYPE_MESSAGE;
+using android::util::ProtoOutputStream;
+
 using std::make_unique;
 using std::set;
 using std::string;
@@ -37,6 +42,8 @@
 namespace os {
 namespace statsd {
 
+const int FIELD_ID_METRICS = 1;
+
 MetricsManager::MetricsManager(const ConfigKey& key, const StatsdConfig& config) : mConfigKey(key) {
     mConfigValid =
             initStatsdConfig(key, config, mTagIds, mAllAtomMatchers, mAllConditionTrackers,
@@ -65,21 +72,17 @@
     return mConfigValid;
 }
 
-void MetricsManager::finish() {
-    for (auto& metricProducer : mAllMetricProducers) {
-        metricProducer->finish();
-    }
-}
-
-vector<std::unique_ptr<vector<uint8_t>>> MetricsManager::onDumpReport() {
+void MetricsManager::onDumpReport(ProtoOutputStream* protoOutput) {
     VLOG("=========================Metric Reports Start==========================");
+    uint64_t dumpTimeStampNs = time(nullptr) * NS_PER_SEC;
     // one StatsLogReport per MetricProduer
-    vector<std::unique_ptr<vector<uint8_t>>> reportList;
     for (auto& metric : mAllMetricProducers) {
-        reportList.push_back(metric->onDumpReport());
+        long long token =
+                protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_METRICS);
+        metric->onDumpReport(dumpTimeStampNs, protoOutput);
+        protoOutput->end(token);
     }
     VLOG("=========================Metric Reports End==========================");
-    return reportList;
 }
 
 // Consume the stats log if it's interesting to this metric.