parseutils

package
v0.0.0-...-d2356ba Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 19, 2017 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package parseutils contains the state machine logic to analyze battery history.

Index

Constants

View Source
const (
	FormatBatteryLevel = "batteryLevel"
	FormatTotalTime    = "totalTime"

	BatteryStatsCheckinVersion = "9"
	HistoryStringPool          = "hsp"
	HistoryData                = "h"

	// Battery history event names.
	BatteryLevel  = "Battery Level"
	Charging      = "Charging on"
	Foreground    = "Foreground process"
	LongWakelocks = "Long Wakelocks"
	Plugged       = "Plugged"
	Top           = "Top app"
)

These constants should be kept consistent with BatteryStats.java.

Variables

View Source
var (
	// ResetRE is a regular expression to match RESET event.
	ResetRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," + HistoryData + "," +
		"(?P<timeDelta>\\d+)" + ":RESET:TIME:(?P<timeStamp>\\d+)")

	// ShutdownRE is a regular expression to match SHUTDOWN event.
	ShutdownRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," + HistoryData + "," +
		"(?P<timeDelta>\\d+)" + ":SHUTDOWN")

	// StartRE is a regular expression to match START event.
	StartRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," + HistoryData + "," +
		"(?P<timeDelta>\\d+):" + "START")

	// TimeRE is a regular expression to match TIME event.
	TimeRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," + HistoryData + "," +
		"(?P<timeDelta>\\d+)" + ":TIME:(?P<timeStamp>\\d+)")

	// GenericHistoryLineRE is a regular expression to match any of the history lines.
	GenericHistoryLineRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," +
		HistoryData + "," + "(?P<timeDelta>\\d+).*")

	// GenericHistoryStringPoolLineRE is a regular expression to match any of the history string pool lines.
	GenericHistoryStringPoolLineRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," +
		HistoryStringPool + "," + "(?P<index>\\d+),(?P<uid>-?\\d+),(?P<service>.+)")

	// VersionLineRE is a regular expression to match the vers statement in the history log.
	VersionLineRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + `,\d+,i,vers,(?P<version>\d+),\d+,.*`)

	// DataRE is a regular expression to match the data event log.
	DataRE = regexp.MustCompile("(?P<transition>[+-]?)" + "(?P<key>\\w+)" + "(,?(=?(?P<value>\\S+))?)")

	// OverflowRE is a regular expression that matches OVERFLOW event.
	OverflowRE = regexp.MustCompile("^" + BatteryStatsCheckinVersion + "," + HistoryData + "," +
		"\\d+:\\*OVERFLOW\\*")

	// CheckinApkLineRE is a regular expression that matches the "apk" line in a checkin log.
	CheckinApkLineRE = regexp.MustCompile("(\\d+,)?(?P<uid>\\d+),l,apk,\\d+,(?P<pkgName>[^,]+),.*")
)

Functions

func BatteryLevelSummariesToCSV

func BatteryLevelSummariesToCSV(buf io.Writer, summaries *[]ActivitySummary, printDimensions bool)

BatteryLevelSummariesToCSV writes level summary CSV for the visualization.

Types

type ActivitySummary

type ActivitySummary struct {
	Reason              string
	Active              bool
	StartTimeMs         int64 // Millis
	EndTimeMs           int64 // Millis
	InitialBatteryLevel int
	FinalBatteryLevel   int
	SummaryFormat       string

	PluggedInSummary     Dist
	ScreenOnSummary      Dist
	MobileRadioOnSummary Dist
	WifiOnSummary        Dist
	CPURunningSummary    Dist

	GpsOnSummary           Dist
	SensorOnSummary        Dist
	WifiScanSummary        Dist
	WifiFullLockSummary    Dist
	WifiRadioSummary       Dist
	WifiRunningSummary     Dist
	WifiMulticastOnSummary Dist

	AudioOnSummary        Dist
	CameraOnSummary       Dist
	VideoOnSummary        Dist
	LowPowerModeOnSummary Dist
	FlashlightOnSummary   Dist
	ChargingOnSummary     Dist

	PhoneCallSummary Dist
	PhoneScanSummary Dist

	BLEScanSummary Dist

	// Stats for total syncs without breaking down by apps.
	TotalSyncSummary Dist

	// Stats for each individual state.
	DataConnectionSummary    map[string]Dist // LTE, HSPA
	ConnectivitySummary      map[string]Dist
	ForegroundProcessSummary map[string]Dist
	ActiveProcessSummary     map[string]Dist
	LongWakelockSummary      map[string]Dist
	TopApplicationSummary    map[string]Dist
	PerAppSyncSummary        map[string]Dist
	WakeupReasonSummary      map[string]Dist
	ScheduledJobSummary      map[string]Dist
	TmpWhiteListSummary      map[string]Dist
	IdleModeSummary          map[string]Dist

	HealthSummary              map[string]Dist
	PlugTypeSummary            map[string]Dist
	ChargingStatusSummary      map[string]Dist // c, d, n, f
	PhoneStateSummary          map[string]Dist
	WakeLockSummary            map[string]Dist
	WakeLockDetailedSummary    map[string]Dist
	WifiSupplSummary           map[string]Dist
	PhoneSignalStrengthSummary map[string]Dist
	WifiSignalStrengthSummary  map[string]Dist
	UserRunningSummary         map[string]Dist
	UserForegroundSummary      map[string]Dist

	// DpstStatsSummary and DcpuStatsSummary shows details of
	// app cpu usage and proc stats in each battery steps.
	DpstStatsSummary  []DPST
	DcpuStatsSummary  []DCPU
	PowerStateSummary []PowerState

	// An aggregated summary for DpstStatsSummary and
	// DcpuStatsSummary in the whole summary duration.
	DpstOverallSummary map[string]time.Duration
	DcpuOverallSummary map[string]time.Duration

	PowerStateOverallSummary map[string]PowerState

	// device state for debug
	AlarmSummary map[string]Dist

	Date string
}

ActivitySummary contains battery statistics during an aggregation interval. Each entry in here should have a corresponding value in session.proto:Summary.

func (*ActivitySummary) Print

func (s *ActivitySummary) Print(b io.Writer)

Print outputs a string containing aggregated battery stats.

type AnalysisReport

type AnalysisReport struct {
	ReportVersion     int32
	Summaries         []ActivitySummary
	TimestampsAltered bool
	OutputBuffer      bytes.Buffer
	IdxMap            map[string]ServiceUID
	Errs              []error
	OverflowMs        int64
	// The keys are the unix timestamp in ms, and the values are the human readable time deltas.
	TimeToDelta map[string]string
}

AnalysisReport contains fields that are created as a result of analyzing and parsing a history.

func AnalyzeHistory

func AnalyzeHistory(csvWriter io.Writer, history, format string, pum PackageUIDMapping, scrubPII bool) *AnalysisReport

AnalyzeHistory takes as input a complete history log and desired summary format. It then analyzes the log line by line (delimited by newline characters). No summaries (before an OVERFLOW line) are excluded/filtered out.

type AppCPUUsage

type AppCPUUsage struct {
	UID        string
	UserTime   time.Duration
	SystemTime time.Duration
	// contains filtered or unexported fields
}

AppCPUUsage is per app cpu usage in DCPU. It also implements the csv.EntryState interface.

func (*AppCPUUsage) GetKey

func (p *AppCPUUsage) GetKey(metric string) csv.Key

GetKey returns the unique identifier for the entry.

func (*AppCPUUsage) GetStartTime

func (p *AppCPUUsage) GetStartTime() int64

GetStartTime returns the start time of the entry.

func (*AppCPUUsage) GetType

func (p *AppCPUUsage) GetType() string

GetType returns the type of the entry.

func (*AppCPUUsage) GetValue

func (p *AppCPUUsage) GetValue() string

GetValue returns the stored value of the entry.

type DCPU

type DCPU struct {
	BatteryLevel int // BatteryLevel here is the starting battery level before battery drop.
	Start        int64
	Duration     time.Duration
	// We name the following fields exactly the same as in BatteryStats.java.
	// In Battery History, time spent in user space and the kernel since the last step.
	UserTime   time.Duration
	SystemTime time.Duration

	// Top three apps using CPU in the last step.
	CPUUtilizers []AppCPUUsage
}

DCPU are CPU related statistics that detail the entire previous discharge step. Each DCPU comes after the change of Battery Level, it records detailed information about app and corresponding userTime and systemTime for each battery level step.

type DPST

type DPST struct {
	BatteryLevel int // BatteryLevel here is the starting battery level before battery drop.
	Start        int64
	Duration     time.Duration
	// We name the following fields exactly the same as in BatteryStats.java.
	// Information from /proc/stat.
	StatUserTime    time.Duration
	StatSystemTime  time.Duration
	StatIOWaitTime  time.Duration
	StatIrqTime     time.Duration
	StatSoftIrqTime time.Duration
	StatIdlTime     time.Duration
}

DPST are Process related statistics that detail the entire previous discharge step. Each DPST comes after the change of Battery Level, it records detailed information about Proc/stats for each battery level step.

type DeviceState

type DeviceState struct {
	CurrentTime        int64
	LastWakeupTime     int64         // To deal with asynchronous arrival of wake reasons
	LastWakeupDuration time.Duration // To deal with asynchronous arrival

	// The power state summary is printed as an aggregate since boot, so we need to track
	// the cummulative in order to split the summary per battery level or discharge session.
	CummulativePowerState map[string]*PowerState
	// The first Power State value logged in the report. Used to provide a base reference for the timeline values.
	InitialPowerState map[string]*PowerState

	// Instanteous state
	Temperature   tsInt
	Voltage       tsInt
	BatteryLevel  tsInt
	Brightness    tsInt
	CoulombCharge tsInt

	PhoneState          tsString
	DataConnection      tsString // hspa, hspap, lte
	PlugType            tsString
	ChargingStatus      tsString
	Health              tsString
	WifiSuppl           tsString // dsc, scan, group, compl
	PhoneSignalStrength tsString
	WifiSignalStrength  tsString
	UserRunning         tsString
	UserForeground      tsString
	IdleMode            tsString

	// Device State metrics from BatteryStats
	CPURunning      tsBool
	SensorOn        tsBool
	GpsOn           tsBool
	WifiFullLock    tsBool
	WifiScan        tsBool
	WifiMulticastOn tsBool
	MobileRadioOn   tsBool
	WifiOn          tsBool
	WifiRadio       tsBool
	WifiRunning     tsBool
	PhoneScanning   tsBool
	BLEScanning     tsBool
	ScreenOn        tsBool
	Plugged         tsBool
	PhoneInCall     tsBool
	WakeLockHeld    tsBool
	FlashlightOn    tsBool
	ChargingOn      tsBool
	CameraOn        tsBool
	VideoOn         tsBool
	AudioOn         tsBool
	LowPowerModeOn  tsBool

	WakeLockHolder ServiceUID
	WakeupReason   ServiceUID

	// Map of uid -> serviceUID for all active entities
	ActiveProcessMap     map[string]*ServiceUID
	AppSyncingMap        map[string]*ServiceUID
	ForegroundProcessMap map[string]*ServiceUID
	TopApplicationMap    map[string]*ServiceUID // There can only be one on top, so the map will have just one entry
	// Connectivity changes are represented in the history log like other applications.
	// For example, we get lines like 9,hsp,3,1,"CONNECTED" and 9,hsp,28,1,"DISCONNECTED",
	// so they are processed and read into ServiceUID objects by the code down in
	// analyzeHistoryLine. So even though changes aren't specific to an app, for the sake
	// of simplicity, they are processed like the rest.
	ConnectivityMap map[string]*ServiceUID
	LongWakelockMap map[string]*ServiceUID
	ScheduledJobMap map[string]*ServiceUID
	TmpWhiteListMap map[string]*ServiceUID // TmpWhiteList contains apps that are given temporary network access after receiving a high priority GCM message.

	// If wakelock_in events are not available, then only the first entity to acquire a
	// wakelock gets charged, so the map will have just one entry
	WakeLockMap map[string]*ServiceUID

	// device state for a debugging event
	AlarmMap map[string]*ServiceUID

	// Statistics that detail the entire previous discharge step
	DpstStats DPST
	DcpuStats DCPU

	// Not implemented yet
	BluetoothOn tsBool
	// contains filtered or unexported fields
}

DeviceState maintains the instantaneous state of the device created using battery history events.

All fields of this type must have corresponding initialization code in initStartTimeForAllStates()

type Dist

type Dist struct {
	Num           int32
	TotalDuration time.Duration
	MaxDuration   time.Duration
}

Dist is a distribution summary for a battery metric.

type MultiDist

type MultiDist struct {
	Name string
	Stat Dist
}

MultiDist is a named distribution summary for a battery metric.

type PackageUIDMapping

type PackageUIDMapping struct {
	// contains filtered or unexported fields
}

PackageUIDMapping contains a series of mapping between package names and their UIDs.

func UIDAndPackageNameMapping

func UIDAndPackageNameMapping(checkin string, pkgs []*usagepb.PackageInfo) (PackageUIDMapping, []error)

UIDAndPackageNameMapping builds a mapping of UIDs to package names and package names to UIDs. For shared UIDs in the UID to package name map, package names will be combined and delineated by ';'. For logs with multiple users, the package name to UID map will only include the app UID (which excludes the user ID).

type PowerState

type PowerState struct {

	// Level of the power state. A higher level represents a deeper (less power consuming) state.
	Level int32
	// Name of the power state.
	Name string
	// Voters for this particular power state.
	Voters []Voter
	// Time spent in this state
	Time time.Duration
	// Count is how many times this state was entered.
	Count int32
	// contains filtered or unexported fields
}

PowerState represents one of the low power states that the CPU can go into.

func (*PowerState) GetKey

func (p *PowerState) GetKey(metric string) csv.Key

GetKey returns the unique identifier for the entry.

func (*PowerState) GetStartTime

func (p *PowerState) GetStartTime() int64

GetStartTime returns the start time of the entry.

func (*PowerState) GetType

func (p *PowerState) GetType() string

GetType returns the type of the entry.

func (*PowerState) GetValue

func (p *PowerState) GetValue() string

GetValue returns the stored value of the entry.

type ServiceUID

type ServiceUID struct {
	Start int64
	// We are treating UIDs as strings.
	Service, UID string
	Pkg          *usagepb.PackageInfo
}

ServiceUID contains the identifying service for battery operations.

func (*ServiceUID) GetKey

func (s *ServiceUID) GetKey(desc string) csv.Key

GetKey returns the unique identifier for the entry. UIDs can have multiple service names, and different UIDs can use the same service name, so we use the UID/Service name pair as the key.

func (*ServiceUID) GetStartTime

func (s *ServiceUID) GetStartTime() int64

GetStartTime returns the start time of the entry.

func (*ServiceUID) GetType

func (s *ServiceUID) GetType() string

GetType returns the type of the entry.

func (*ServiceUID) GetValue

func (s *ServiceUID) GetValue() string

GetValue returns the stored service for the entry.

type SortByTimeAndCount

type SortByTimeAndCount []MultiDist

SortByTimeAndCount sorts MultiDist in descending order of TotalDuration.

func (SortByTimeAndCount) Len

func (a SortByTimeAndCount) Len() int

func (SortByTimeAndCount) Less

func (a SortByTimeAndCount) Less(i, j int) bool

func (SortByTimeAndCount) Swap

func (a SortByTimeAndCount) Swap(i, j int)

type Voter

type Voter struct {
	// Name of the voter.
	Name string
	// Time the voter spent voting for its power state.
	Time time.Duration
	// How many times the voter had a 'yes' vote.
	Count int32
}

Voter represents a voter for one of the low power states.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL