Merge "Add a mechanism to log battery usage periodic job events" into udc-qpr-dev

This commit is contained in:
Treehugger Robot
2023-07-11 06:09:54 +00:00
committed by Android (Google) Code Review
17 changed files with 306 additions and 39 deletions

View File

@@ -289,12 +289,14 @@ public class AdvancedPowerUsageDetail extends DashboardFragment implements
mLogStringBuilder.append(", onPause mode = ").append(selectedPreference);
logMetricCategory(selectedPreference);
BatteryHistoricalLogUtil.writeLog(
getContext().getApplicationContext(),
Action.LEAVE,
BatteryHistoricalLogUtil.getPackageNameWithUserId(
mBatteryOptimizeUtils.getPackageName(), UserHandle.myUserId()),
mLogStringBuilder.toString());
mExecutor.execute(() -> {
BatteryOptimizeLogUtils.writeLog(
getContext().getApplicationContext(),
Action.LEAVE,
BatteryOptimizeLogUtils.getPackageNameWithUserId(
mBatteryOptimizeUtils.getPackageName(), UserHandle.myUserId()),
mLogStringBuilder.toString());
});
Log.d(TAG, "Leave with mode: " + selectedPreference);
}

View File

@@ -199,7 +199,7 @@ public final class BatteryBackupHelper implements BackupHelper {
info.packageName + DELIMITER_MODE + optimizationMode;
builder.append(packageOptimizeMode + DELIMITER);
Log.d(TAG, "backupOptimizationMode: " + packageOptimizeMode);
BatteryHistoricalLogUtil.writeLog(
BatteryOptimizeLogUtils.writeLog(
sharedPreferences, Action.BACKUP, info.packageName,
/* actionDescription */ "mode: " + optimizationMode);
backupCount++;
@@ -275,7 +275,7 @@ public final class BatteryBackupHelper implements BackupHelper {
/** Dump the app optimization mode backup history data. */
public static void dumpHistoricalData(Context context, PrintWriter writer) {
BatteryHistoricalLogUtil.printBatteryOptimizeHistoricalLog(
BatteryOptimizeLogUtils.printBatteryOptimizeHistoricalLog(
getSharedPreferences(context), writer);
}

View File

@@ -20,23 +20,25 @@ import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import androidx.annotation.VisibleForTesting;
import com.android.settings.fuelgauge.BatteryOptimizeHistoricalLogEntry.Action;
import com.android.settings.fuelgauge.batteryusage.ConvertUtils;
import com.google.common.annotations.VisibleForTesting;
import java.io.PrintWriter;
import java.util.List;
/** Writes and reads a historical log of battery related state change events. */
public final class BatteryHistoricalLogUtil {
public final class BatteryOptimizeLogUtils {
private static final String TAG = "BatteryOptimizeLogUtils";
private static final String BATTERY_OPTIMIZE_FILE_NAME = "battery_optimize_historical_logs";
private static final String LOGS_KEY = "battery_optimize_logs_key";
private static final String TAG = "BatteryHistoricalLogUtil";
@VisibleForTesting
static final int MAX_ENTRIES = 40;
private BatteryOptimizeLogUtils() {}
/** Writes a log entry for battery optimization mode. */
static void writeLog(
Context context, Action action, String packageName, String actionDescription) {
@@ -67,7 +69,7 @@ public final class BatteryHistoricalLogUtil {
newLogBuilder.addLogEntry(logEntry);
String loggingContent =
Base64.encodeToString(newLogBuilder.build().toByteArray(), Base64.DEFAULT);
Base64.encodeToString(newLogBuilder.build().toByteArray(), Base64.DEFAULT);
sharedPreferences
.edit()
.putString(LOGS_KEY, loggingContent)
@@ -94,7 +96,7 @@ public final class BatteryHistoricalLogUtil {
if (logEntryList.isEmpty()) {
writer.println("\tnothing to dump");
} else {
writer.println("0:UNKNOWN 1:RESTRICTED 2:UNRESTRICTED 3:OPTIMIZED");
writer.println("0:UNKNOWN 1:RESTRICTED 2:UNRESTRICTED 3:OPTIMIZED");
logEntryList.forEach(entry -> writer.println(toString(entry)));
}
}
@@ -113,6 +115,7 @@ public final class BatteryHistoricalLogUtil {
@VisibleForTesting
static SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences(BATTERY_OPTIMIZE_FILE_NAME, Context.MODE_PRIVATE);
return context.getApplicationContext()
.getSharedPreferences(BATTERY_OPTIMIZE_FILE_NAME, Context.MODE_PRIVATE);
}
}

View File

@@ -245,7 +245,7 @@ public class BatteryOptimizeUtils {
Context context, int appStandbyMode, boolean allowListed, int uid, String packageName,
BatteryUtils batteryUtils, PowerAllowlistBackend powerAllowlistBackend,
Action action) {
final String packageNameKey = BatteryHistoricalLogUtil
final String packageNameKey = BatteryOptimizeLogUtils
.getPackageNameWithUserId(packageName, UserHandle.myUserId());
try {
batteryUtils.setForceAppStandby(uid, packageName, appStandbyMode);
@@ -259,7 +259,7 @@ public class BatteryOptimizeUtils {
appStandbyMode = -1;
Log.e(TAG, "set OPTIMIZATION MODE failed for " + packageName, e);
}
BatteryHistoricalLogUtil.writeLog(
BatteryOptimizeLogUtils.writeLog(
context,
action,
packageNameKey,

View File

@@ -355,7 +355,7 @@ public class BatteryUtils {
@SuppressWarnings("unchecked")
public static <T extends MessageLite> T parseProtoFromString(
String serializedProto, T protoClass) {
if (serializedProto.isEmpty()) {
if (serializedProto == null || serializedProto.isEmpty()) {
return (T) protoClass.getDefaultInstanceForType();
}
try {

View File

@@ -23,6 +23,9 @@ import android.util.Log;
import androidx.annotation.VisibleForTesting;
import com.android.settings.fuelgauge.BatteryUsageHistoricalLogEntry.Action;
import com.android.settings.fuelgauge.batteryusage.bugreport.BatteryUsageLogUtils;
import java.util.List;
import java.util.function.Supplier;
@@ -46,6 +49,7 @@ public final class BatteryUsageDataLoader {
@VisibleForTesting
static void loadUsageData(final Context context, final boolean isFullChargeStart) {
BatteryUsageLogUtils.writeLog(context, Action.FETCH_USAGE_DATA, "");
final long start = System.currentTimeMillis();
final BatteryUsageStats batteryUsageStats = DataProcessor.getBatteryUsageStats(context);
final List<BatteryEntry> batteryEntryList =

View File

@@ -24,6 +24,8 @@ import android.os.Looper;
import android.util.Log;
import com.android.settings.core.instrumentation.ElapsedTimeUtils;
import com.android.settings.fuelgauge.BatteryUsageHistoricalLogEntry.Action;
import com.android.settings.fuelgauge.batteryusage.bugreport.BatteryUsageLogUtils;
import com.android.settings.overlay.FeatureFactory;
import java.time.Duration;
@@ -79,8 +81,9 @@ public final class BootBroadcastReceiver extends BroadcastReceiver {
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
final Intent recheckIntent = new Intent(ACTION_PERIODIC_JOB_RECHECK);
recheckIntent.setClass(context, BootBroadcastReceiver.class);
mHandler.postDelayed(() -> context.sendBroadcast(recheckIntent),
getRescheduleTimeForBootAction(context));
final long delayedTime = getRescheduleTimeForBootAction(context);
mHandler.postDelayed(() -> context.sendBroadcast(recheckIntent), delayedTime);
BatteryUsageLogUtils.writeLog(context, Action.RECHECK_JOB, "delay:" + delayedTime);
} else if (ACTION_SETUP_WIZARD_FINISHED.equals(action)) {
ElapsedTimeUtils.storeSuwFinishedTimestamp(context, System.currentTimeMillis());
}

View File

@@ -34,7 +34,9 @@ import android.util.Log;
import androidx.annotation.VisibleForTesting;
import com.android.settings.fuelgauge.BatteryUsageHistoricalLogEntry.Action;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.fuelgauge.batteryusage.bugreport.BatteryUsageLogUtils;
import com.android.settings.fuelgauge.batteryusage.db.BatteryStateDatabase;
import com.android.settingslib.fuelgauge.BatteryStatus;
@@ -395,6 +397,7 @@ public final class DatabaseUtils {
int size = 1;
final ContentResolver resolver = context.getContentResolver();
String errorMessage = "";
// Inserts all ContentValues into battery provider.
if (!valuesList.isEmpty()) {
final ContentValues[] valuesArray = new ContentValues[valuesList.size()];
@@ -404,7 +407,8 @@ public final class DatabaseUtils {
Log.d(TAG, "insert() battery states data into database with isFullChargeStart:"
+ isFullChargeStart);
} catch (Exception e) {
Log.e(TAG, "bulkInsert() battery states data into database error:\n" + e);
errorMessage = e.toString();
Log.e(TAG, "bulkInsert() data into database error:\n" + errorMessage);
}
} else {
// Inserts one fake data into battery provider.
@@ -424,11 +428,16 @@ public final class DatabaseUtils {
+ isFullChargeStart);
} catch (Exception e) {
Log.e(TAG, "insert() data into database error:\n" + e);
errorMessage = e.toString();
Log.e(TAG, "insert() data into database error:\n" + errorMessage);
}
valuesList.add(contentValues);
}
resolver.notifyChange(BATTERY_CONTENT_URI, /*observer=*/ null);
BatteryUsageLogUtils.writeLog(
context,
Action.INSERT_USAGE_DATA,
"size=" + size + " " + errorMessage);
Log.d(TAG, String.format("sendBatteryEntryData() size=%d in %d/ms",
size, (System.currentTimeMillis() - startTime)));
if (isFullChargeStart) {

View File

@@ -24,6 +24,8 @@ import android.util.Log;
import androidx.annotation.VisibleForTesting;
import com.android.settings.fuelgauge.BatteryUsageHistoricalLogEntry.Action;
import com.android.settings.fuelgauge.batteryusage.bugreport.BatteryUsageLogUtils;
import com.android.settings.overlay.FeatureFactory;
import java.time.Clock;
@@ -76,8 +78,11 @@ public final class PeriodicJobManager {
final long triggerAtMillis = getTriggerAtMillis(mContext, Clock.systemUTC(), fromBoot);
mAlarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
Log.d(TAG, "schedule next alarm job at "
+ ConvertUtils.utcToLocalTimeForLogging(triggerAtMillis));
final String utcToLocalTime = ConvertUtils.utcToLocalTimeForLogging(triggerAtMillis);
BatteryUsageLogUtils.writeLog(
mContext, Action.SCHEDULE_JOB, "triggerTime=" + utcToLocalTime);
Log.d(TAG, "schedule next alarm job at " + utcToLocalTime);
}
void cancelJob(PendingIntent pendingIntent) {

View File

@@ -22,6 +22,9 @@ import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.android.settings.fuelgauge.BatteryUsageHistoricalLogEntry.Action;
import com.android.settings.fuelgauge.batteryusage.bugreport.BatteryUsageLogUtils;
/** Receives the periodic alarm {@link PendingIntent} callback. */
public final class PeriodicJobReceiver extends BroadcastReceiver {
private static final String TAG = "PeriodicJobReceiver";
@@ -39,6 +42,7 @@ public final class PeriodicJobReceiver extends BroadcastReceiver {
Log.w(TAG, "do not refresh job for work profile action=" + action);
return;
}
BatteryUsageLogUtils.writeLog(context, Action.EXECUTE_JOB, "");
BatteryUsageDataLoader.enqueueWork(context, /*isFullChargeStart=*/ false);
AppUsageDataLoader.enqueueWork(context);
Log.d(TAG, "refresh periodic job from action=" + action);

View File

@@ -0,0 +1,104 @@
/*
* Copyright (C) 2023 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.settings.fuelgauge.batteryusage.bugreport;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import com.android.settings.fuelgauge.BatteryUsageHistoricalLog;
import com.android.settings.fuelgauge.BatteryUsageHistoricalLogEntry;
import com.android.settings.fuelgauge.BatteryUsageHistoricalLogEntry.Action;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.fuelgauge.batteryusage.ConvertUtils;
import com.google.common.annotations.VisibleForTesting;
import java.io.PrintWriter;
import java.util.List;
/** Writes and reads a historical log of battery usage periodic job events. */
public final class BatteryUsageLogUtils {
private static final String TAG = "BatteryUsageLogUtils";
private static final String BATTERY_USAGE_FILE_NAME = "battery_usage_historical_logs";
private static final String LOGS_KEY = "battery_usage_logs_key";
// 24 hours x 4 events every hour x 3 days
static final int MAX_ENTRIES = 288;
private BatteryUsageLogUtils() {}
/** Write the log into the {@link SharedPreferences}. */
public static void writeLog(Context context, Action action, String actionDescription) {
final SharedPreferences sharedPreferences = getSharedPreferences(context);
final BatteryUsageHistoricalLogEntry newLogEntry =
BatteryUsageHistoricalLogEntry.newBuilder()
.setTimestamp(System.currentTimeMillis())
.setAction(action)
.setActionDescription(actionDescription)
.build();
final BatteryUsageHistoricalLog existingLog =
parseLogFromString(sharedPreferences.getString(LOGS_KEY, ""));
final BatteryUsageHistoricalLog.Builder newLogBuilder = existingLog.toBuilder();
// Prune old entries to limit the max logging data count.
if (existingLog.getLogEntryCount() >= MAX_ENTRIES) {
newLogBuilder.removeLogEntry(0);
}
newLogBuilder.addLogEntry(newLogEntry);
final String loggingContent =
Base64.encodeToString(newLogBuilder.build().toByteArray(), Base64.DEFAULT);
sharedPreferences
.edit()
.putString(LOGS_KEY, loggingContent)
.apply();
}
/** Prints the historical log that has previously been stored by this utility. */
public static void printHistoricalLog(Context context, PrintWriter writer) {
final BatteryUsageHistoricalLog existingLog = parseLogFromString(
getSharedPreferences(context).getString(LOGS_KEY, ""));
final List<BatteryUsageHistoricalLogEntry> logEntryList = existingLog.getLogEntryList();
if (logEntryList.isEmpty()) {
writer.println("\tnothing to dump");
} else {
logEntryList.forEach(entry -> writer.println(toString(entry)));
}
}
@VisibleForTesting
static SharedPreferences getSharedPreferences(Context context) {
return context.getApplicationContext()
.getSharedPreferences(BATTERY_USAGE_FILE_NAME, Context.MODE_PRIVATE);
}
private static BatteryUsageHistoricalLog parseLogFromString(String storedLogs) {
return BatteryUtils.parseProtoFromString(
storedLogs, BatteryUsageHistoricalLog.getDefaultInstance());
}
private static String toString(BatteryUsageHistoricalLogEntry entry) {
final StringBuilder builder = new StringBuilder("\t")
.append(ConvertUtils.utcToLocalTimeForLogging(entry.getTimestamp()))
.append(" " + entry.getAction());
final String description = entry.getActionDescription();
if (description != null && !description.isEmpty()) {
builder.append(" " + description);
}
return builder.toString();
}
}

View File

@@ -39,6 +39,12 @@ public final class LogUtils {
private static final Duration DUMP_TIME_OFFSET_FOR_ENTRY = Duration.ofHours(4);
static void dumpBatteryUsageDatabaseHist(Context context, PrintWriter writer) {
// Dumps periodic job events.
writer.println("\nBattery PeriodicJob History:");
BatteryUsageLogUtils.printHistoricalLog(context, writer);
writer.flush();
// Dumps phenotype environments.
DatabaseUtils.dump(context, writer);
writer.flush();
final BatteryStateDao dao =
@@ -47,6 +53,7 @@ public final class LogUtils {
.batteryStateDao();
final long timeOffset =
Clock.systemUTC().millis() - DUMP_TIME_OFFSET.toMillis();
// Gets all distinct timestamps.
final List<Long> timestamps = dao.getDistinctTimestamps(timeOffset);
final int distinctCount = timestamps.size();