Thermal shutdown fix: cool down on writing to disk

Currently, statsd uses wall clock seconds to write data to disk. This
issue affects both thermal and normal shutdowns, because if two writes
occur in the same second, the more recent write will overwrite the older
write, erasing the actual data that we want.

For thermal shutdowns, we write twice. Once because of termination
signal received, and once because of binder death recipient from
statscompanion service.

For normal clean shutdowns, we write 3 times. In addition to the two
above, we write for the shutdown received signal.

This fix introduces a cool down period of 3 seconds between writing to
disk.

Bug: 112432890
Test: statsd unit tests
Test: statsd cts tests
Test: manually verified normal shutdown had 1 file written to disk
Test: manually verified thermal shutdown had 1 file written to disk
Change-Id: I4cd39de9063935e762ff7d00051ccc915f31e89a
diff --git a/cmds/statsd/src/StatsLogProcessor.cpp b/cmds/statsd/src/StatsLogProcessor.cpp
index e7f1caf..e7adba4 100644
--- a/cmds/statsd/src/StatsLogProcessor.cpp
+++ b/cmds/statsd/src/StatsLogProcessor.cpp
@@ -71,6 +71,9 @@
 
 #define STATS_DATA_DIR "/data/misc/stats-data"
 
+// Cool down period for writing data to disk to avoid overwriting files.
+#define WRITE_DATA_COOL_DOWN_SEC 5
+
 StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
                                      const sp<AlarmMonitor>& anomalyAlarmMonitor,
                                      const sp<AlarmMonitor>& periodicAlarmMonitor,
@@ -526,6 +529,16 @@
 
 void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason) {
     const int64_t timeNs = getElapsedRealtimeNs();
+    // Do not write to disk if we already have in the last few seconds.
+    // This is to avoid overwriting files that would have the same name if we
+    //   write twice in the same second.
+    if (static_cast<unsigned long long> (timeNs) <
+            mLastWriteTimeNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
+        ALOGI("Statsd skipping writing data to disk. Already wrote data in last %d seconds",
+                WRITE_DATA_COOL_DOWN_SEC);
+        return;
+    }
+    mLastWriteTimeNs = timeNs;
     for (auto& pair : mMetricsManagers) {
         WriteDataToDiskLocked(pair.first, timeNs, dumpReportReason);
     }
diff --git a/cmds/statsd/src/StatsLogProcessor.h b/cmds/statsd/src/StatsLogProcessor.h
index 9ed4ed0..86eb855 100644
--- a/cmds/statsd/src/StatsLogProcessor.h
+++ b/cmds/statsd/src/StatsLogProcessor.h
@@ -184,6 +184,9 @@
 
     long mLastPullerCacheClearTimeSec = 0;
 
+    // Last time we wrote data to disk.
+    int64_t mLastWriteTimeNs = 0;
+
 #ifdef VERY_VERBOSE_PRINTING
     bool mPrintAllLogs = false;
 #endif