Skip to content

Commit

Permalink
Merge pull request #3 from Meesho/bump-gradle-version
Browse files Browse the repository at this point in the history
Memory leak fixes
  • Loading branch information
vshali authored Apr 11, 2023
2 parents ab97b61 + a445724 commit 6799edb
Show file tree
Hide file tree
Showing 37 changed files with 266 additions and 180 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@
import static com.facebook.battery.metrics.appwakeup.AppWakeupMetrics.WakeupDetails;
import static com.facebook.battery.metrics.core.Utilities.checkNotNull;

import android.content.Context;
import android.os.SystemClock;
import com.facebook.battery.metrics.core.SystemMetricsCollector;
import com.facebook.battery.metrics.core.SystemMetricsLogger;
import com.facebook.infer.annotation.ThreadSafe;

import javax.annotation.Nullable;

/**
* This class is used to record and aggregate the wakeups in the app. It exposes methods to record
* start {@link #recordWakeupStart(AppWakeupMetrics.WakeupReason, String)} and end {@link
Expand All @@ -34,7 +37,7 @@ public AppWakeupMetricsCollector() {

@Override
@ThreadSafe(enableChecks = false)
public synchronized boolean getSnapshot(AppWakeupMetrics snapshot) {
public synchronized boolean getSnapshot(AppWakeupMetrics snapshot, @Nullable Context context) {
checkNotNull(snapshot, "Null value passed to getSnapshot!");
// TODO: Optimize by taking intersection of the two lists
snapshot.appWakeups.clear();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,16 @@
import android.app.PendingIntent;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.content.Context;
import android.os.SystemClock;
import android.util.SparseArray;
import androidx.annotation.GuardedBy;
import com.facebook.battery.metrics.core.SystemMetricsCollector;
import com.facebook.infer.annotation.Nullsafe;
import com.facebook.infer.annotation.ThreadSafe;

import javax.annotation.Nullable;

/**
* Records information about Bluetooth LE scans, meant to be used with {@link BluetoothLeScanner}.
*
Expand Down Expand Up @@ -55,7 +58,7 @@ public long getTotalDuration() {
private final ScanMetrics mOpportunisticScan = new ScanMetrics();

@Override
public synchronized boolean getSnapshot(BluetoothMetrics snapshot) {
public synchronized boolean getSnapshot(BluetoothMetrics snapshot, @Nullable Context context) {
checkNotNull(snapshot, "Null value passed to getSnapshot!");
snapshot.bleScanCount = mNonOpportunisticScan.count;
snapshot.bleOpportunisticScanCount = mOpportunisticScan.count;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import static com.facebook.battery.metrics.core.Utilities.checkNotNull;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraDevice;
Expand All @@ -22,6 +23,8 @@
import com.facebook.battery.metrics.core.SystemMetricsLogger;
import com.facebook.infer.annotation.ThreadSafe;

import javax.annotation.Nullable;

/**
* CameraMetricsCollector internally maintains how long the camera was open and previewed; this is
* simply a helper class to maintain state and can't automatically instrument camera usage.
Expand Down Expand Up @@ -64,7 +67,7 @@ public class CameraMetricsCollector extends SystemMetricsCollector<CameraMetrics
public CameraMetricsCollector() {}

@Override
public synchronized boolean getSnapshot(CameraMetrics snapshot) {
public synchronized boolean getSnapshot(CameraMetrics snapshot, @Nullable Context context) {
checkNotNull(snapshot, "Null value passed to getSnapshot!");
if (!mIsEnabled) {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@

import static com.facebook.battery.metrics.core.Utilities.checkNotNull;

import android.content.Context;

import androidx.collection.SimpleArrayMap;
import com.facebook.battery.metrics.core.SystemMetrics;
import com.facebook.battery.metrics.core.SystemMetricsCollector;
import com.facebook.battery.metrics.core.VisibleToAvoidSynthetics;
import com.facebook.infer.annotation.ThreadSafe;

import javax.annotation.Nullable;

/**
* Composite metrics collector allows batching and using several Metrics Collectors together, keyed
* by the SystemMetrics they're attached to.
Expand Down Expand Up @@ -81,11 +85,12 @@ public <S extends SystemMetrics<S>, T extends SystemMetricsCollector<S>> T getMe
* collectors are expected to report any errors they might encounter.
*
* @param snapshot snapshot to reuse
* @param context
* @return whether _any_ underlying snapshot succeeded
*/
@Override
@ThreadSafe(enableChecks = false)
public boolean getSnapshot(CompositeMetrics snapshot) {
public boolean getSnapshot(CompositeMetrics snapshot, @Nullable Context context) {
checkNotNull(snapshot, "Null value passed to getSnapshot!");
boolean result = false;
SimpleArrayMap<Class<? extends SystemMetrics>, SystemMetrics> snapshotMetrics =
Expand All @@ -96,7 +101,7 @@ public boolean getSnapshot(CompositeMetrics snapshot) {
boolean snapshotResult = false;
if (collector != null) {
SystemMetrics metric = snapshot.getMetric(metricsClass);
snapshotResult = collector.getSnapshot(metric);
snapshotResult = collector.getSnapshot(metric, null);
}
snapshot.setIsValid(metricsClass, snapshotResult);
result |= snapshotResult;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
public class StatefulSystemMetricsCollector<
R extends SystemMetrics<R>, S extends SystemMetricsCollector<R>> {

private final S mCollector;
private S mCollector;
private final R mDiff;

private R mCurr;
Expand All @@ -44,7 +44,7 @@ public class StatefulSystemMetricsCollector<
public StatefulSystemMetricsCollector(S collector) {
this(
collector, collector.createMetrics(), collector.createMetrics(), collector.createMetrics());
mIsValid &= collector.getSnapshot(mPrev);
mIsValid &= collector.getSnapshot(mPrev, null);
}

/**
Expand Down Expand Up @@ -82,12 +82,16 @@ public R getLatestDiffAndReset() {
/** Get a diff form the previous baseline. */
@Nullable
public R getLatestDiff() {
mIsValid &= mCollector.getSnapshot(this.mCurr);
mIsValid &= mCollector.getSnapshot(this.mCurr, null);
if (!mIsValid) {
return null;
}

mCurr.diff(mPrev, mDiff);
return mDiff;
}

public void clearCollectors(){
mCollector = null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@

package com.facebook.battery.metrics.core;

import android.content.Context;

import javax.annotation.Nullable;

/**
* Takes snapshots of a given metric. There are generally two types of metrics collectors - - those
* that depend on an underlying api, such as the {@link
Expand All @@ -22,10 +26,11 @@ public abstract class SystemMetricsCollector<T extends SystemMetrics> {
* by the caller requesting getSnapshot.
*
* @param snapshot snapshot on which the data will be written
* @param context
* @return true if the snapshot has been updated with valid data.
* @throws IllegalArgumentException if snapshot == null.
*/
public abstract boolean getSnapshot(T snapshot);
public abstract boolean getSnapshot(T snapshot, @Nullable Context context);

/**
* Creates an empty instance of the corresponding system metrics.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import static com.facebook.battery.metrics.core.Utilities.checkNotNull;

import android.content.Context;
import android.util.SparseIntArray;
import androidx.annotation.VisibleForTesting;
import com.facebook.battery.metrics.core.ProcFileReader;
Expand Down Expand Up @@ -43,7 +44,7 @@ public class CpuFrequencyMetricsCollector extends SystemMetricsCollector<CpuFreq

@Override
@ThreadSafe(enableChecks = false)
public boolean getSnapshot(CpuFrequencyMetrics snapshot) {
public boolean getSnapshot(CpuFrequencyMetrics snapshot, @Nullable Context context) {
checkNotNull(snapshot, "Null value passed to getSnapshot!");
boolean hasAnyValid = false;
for (int i = 0, cores = getTotalCores(); i < cores; i++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@

import static com.facebook.battery.metrics.core.Utilities.checkNotNull;

import android.content.Context;

import androidx.annotation.VisibleForTesting;
import com.facebook.battery.metrics.core.ProcFileReader;
import com.facebook.battery.metrics.core.SystemMetricsCollector;
import com.facebook.battery.metrics.core.SystemMetricsLogger;
import com.facebook.battery.metrics.core.VisibleToAvoidSynthetics;
import com.facebook.infer.annotation.ThreadSafe;

import javax.annotation.Nullable;

/**
* Collects data about cpu metrics.
*
Expand Down Expand Up @@ -44,7 +48,7 @@ public CpuMetricsCollector() {}

@Override
@ThreadSafe(enableChecks = false)
public boolean getSnapshot(CpuMetrics snapshot) {
public boolean getSnapshot(CpuMetrics snapshot, @Nullable Context context) {
checkNotNull(snapshot, "Null value passed to getSnapshot!");

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import android.os.BatteryManager;
import android.os.SystemClock;
import androidx.annotation.Nullable;

import com.facebook.battery.metrics.core.SystemMetricsCollector;
import com.facebook.battery.metrics.core.SystemMetricsLogger;
import com.facebook.battery.metrics.core.VisibleToAvoidSynthetics;
Expand All @@ -32,7 +33,7 @@ public class DeviceBatteryMetricsCollector extends SystemMetricsCollector<Device
private static final String TAG = "DeviceBatteryMetricsCollector";
static int UNKNOWN_LEVEL = -1;

private final Context mContext;
private Context mContext;

@GuardedBy("this")
@VisibleToAvoidSynthetics
Expand All @@ -50,6 +51,40 @@ public class DeviceBatteryMetricsCollector extends SystemMetricsCollector<Device
@VisibleToAvoidSynthetics
boolean mIsCurrentlyCharging;

BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long now = SystemClock.elapsedRealtime();
synchronized (DeviceBatteryMetricsCollector.this) {
switch (intent.getAction()) {
case Intent.ACTION_POWER_CONNECTED:
if (!mIsCurrentlyCharging) {
mBatteryRealtimeMs += (now - mLastUpdateMs);
} else {
// This should not happen
mChargingRealtimeMs += (now - mLastUpdateMs);
logIncorrectSequence("CONNECTED", now);
}
mIsCurrentlyCharging = true;
break;

case Intent.ACTION_POWER_DISCONNECTED:
if (mIsCurrentlyCharging) {
mChargingRealtimeMs += (now - mLastUpdateMs);
} else {
// This should not happen
mBatteryRealtimeMs += (now - mLastUpdateMs);
logIncorrectSequence("DISCONNECTED", now);
}
mIsCurrentlyCharging = false;
break;
default:
}
mLastUpdateMs = now;
}
}
};

public DeviceBatteryMetricsCollector(Context context) {
mContext = context;

Expand All @@ -64,46 +99,15 @@ public DeviceBatteryMetricsCollector(Context context) {

// Register the receiver for power connected and disconnected
// This is not very accurate after targeting SDK 26

context.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long now = SystemClock.elapsedRealtime();
synchronized (DeviceBatteryMetricsCollector.this) {
switch (intent.getAction()) {
case Intent.ACTION_POWER_CONNECTED:
if (!mIsCurrentlyCharging) {
mBatteryRealtimeMs += (now - mLastUpdateMs);
} else {
// This should not happen
mChargingRealtimeMs += (now - mLastUpdateMs);
logIncorrectSequence("CONNECTED", now);
}
mIsCurrentlyCharging = true;
break;

case Intent.ACTION_POWER_DISCONNECTED:
if (mIsCurrentlyCharging) {
mChargingRealtimeMs += (now - mLastUpdateMs);
} else {
// This should not happen
mBatteryRealtimeMs += (now - mLastUpdateMs);
logIncorrectSequence("DISCONNECTED", now);
}
mIsCurrentlyCharging = false;
break;
default:
}
mLastUpdateMs = now;
}
}
},
myReceiver,
intentFilter);
}

@Override
@ThreadSafe(enableChecks = false)
public boolean getSnapshot(DeviceBatteryMetrics snapshot) {
public boolean getSnapshot(DeviceBatteryMetrics snapshot, @javax.annotation.Nullable Context context) {
checkNotNull(snapshot, "Null value passed to getSnapshot!");
snapshot.batteryLevelPct = getBatteryLevel(getBatteryIntent());
long now = SystemClock.elapsedRealtime();
Expand Down Expand Up @@ -167,4 +171,13 @@ void logIncorrectSequence(String intentType, long now) {
SystemMetricsLogger.wtf(
TAG, "Consecutive " + intentType + "broadcasts: (" + mLastUpdateMs + ", " + now + ")");
}

public void cleanUp() {
try {
mContext.unregisterReceiver(myReceiver);
mContext = null;
} catch (IllegalArgumentException e) {
SystemMetricsLogger.wtf(TAG, "Receiver not registered 123");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

import static com.facebook.battery.metrics.core.Utilities.checkNotNull;

import android.content.Context;

import androidx.annotation.GuardedBy;
import com.facebook.battery.metrics.core.ProcFileReader;
import com.facebook.battery.metrics.core.SystemMetricsCollector;
Expand All @@ -17,6 +19,8 @@
import com.facebook.infer.annotation.ThreadSafe;
import java.nio.CharBuffer;

import javax.annotation.Nullable;

@Nullsafe(Nullsafe.Mode.LOCAL)
@ThreadSafe
public class DiskMetricsCollector extends SystemMetricsCollector<DiskMetrics> {
Expand All @@ -37,7 +41,7 @@ public class DiskMetricsCollector extends SystemMetricsCollector<DiskMetrics> {

@Override
@ThreadSafe(enableChecks = false)
public synchronized boolean getSnapshot(DiskMetrics snapshot) {
public synchronized boolean getSnapshot(DiskMetrics snapshot, @Nullable Context context) {
checkNotNull(snapshot, "Null value passed to getSnapshot!");
if (!mIsEnabled) {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
import com.facebook.battery.metrics.core.SystemMetricsLogger;
import com.facebook.infer.annotation.ThreadSafe;

import javax.annotation.Nullable;

@RequiresApi(api = Build.VERSION_CODES.N)
@ThreadSafe(enableChecks = false)
public class HealthStatsMetricsCollector extends SystemMetricsCollector<HealthStatsMetrics> {
Expand All @@ -30,7 +32,7 @@ public HealthStatsMetricsCollector(Context context) {
@Override
@SuppressWarnings("CatchGeneralException")
// because takeMyUidSnapshot wraps RemoteException in a RuntimeException
public boolean getSnapshot(HealthStatsMetrics snapshot) {
public boolean getSnapshot(HealthStatsMetrics snapshot, @Nullable Context context) {
try {
snapshot.set(mSystemHealthManager.takeMyUidSnapshot());
return true;
Expand Down
Loading

0 comments on commit 6799edb

Please sign in to comment.