facebookincubator / Battery-Metrics

Library that helps in instrumenting battery related system metrics.
MIT License
745 stars 79 forks source link

How Facebook use Battery-Metrics? #20

Closed shwenzhang closed 6 years ago

shwenzhang commented 6 years ago

Unlike other battery metrics library, they would hook such as PowerManager、AlarmManager。 We don't need to do anything to use it. I wonder how facebook use this library, use redex to change method during compile time? replay these method manually?

kunalb commented 6 years ago

Hi! BatteryMetrics relies on hooking up some components (like camera, wakelocks -- they rely on battery metrics being informed by calling functions on the CameraMetricsCollector, WakelockMetricsCollector) manually and some metrics are captured automatically (like cpu and network).

Within Facebook we have instrumentation around all these system api calls that also toggles data collection in the battery metrics library. Does that help?

[Could you also give me examples of other battery metrics libraries?]

kunalb commented 6 years ago

Also, for some of the apis we do use bytecode rewriting to make sure all api calls are transparently captured -- using the same mechanism outlined in https://code.fb.com/android/performance-instrumentation-for-android-apps/

That has been significantly less fragile as compared to maintaining the instrumentation by hand, so we've slowly been trying to get everything instrumented this way. Unfortunately, that also makes attribution harder.

shwenzhang commented 6 years ago

Thanks for reply. Currently, we use proxy hook for POWER_SERVICE、ALARM_SERVICE、LOCATION_SERVICE、SENSOR_SERVICE....
But I think it is not a good way after Android P, I would try to use base class or asm method instead.

shwenzhang commented 6 years ago

By the way, java bytecode rewriter as below sounds wonderful, is it a open source project?

new EntryExitRule.Builder()
  .setMatcherConfiguration(
    subclassesOf(
      getObjectType("android/app/Activity")
    ).withMethods(
      getMethod("void onCreate(android.os.Bundle)"),
      getMethod("void onRestart()"),
      getMethod("void onStart()"),
      getMethod("void onResume()"),
      getMethod("void onPause()"),
      getMethod("void onStop()"),
      getMethod("void onDestroy()")))
  .setDetourType(LOG_UTILS_TYPE)
  .setDetourMethodEntry(LOG_METHOD_ACTIVITY_START)
  .setDetourMethodExit(LOG_METHOD_ACTIVITY_END)
  .setCategory(Categories.LIFECYCLE)
  .build()

And I found InstrumentPass within Redex, it seems to be a davlik bytecode rewriter? I wonder Facebook use which one of them?or both?

kunalb commented 6 years ago

I just checked: unfortunately it's not open source at the moment.

We use both that bytecode rewriting and dex rewriting/redex, but for battery we only use the first one at the moment.