This repository has been archived by the owner on Dec 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 963
/
Copy pathcheckin_parse.go
2633 lines (2454 loc) · 99.3 KB
/
checkin_parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 Google Inc. All Rights Reserved.
//
// 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 checkinparse contains functions to parse checkin report into batterystats proto.
package checkinparse
import (
"errors"
"fmt"
"math"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/golang/protobuf/proto"
"github.com/google/battery-historian/build"
"github.com/google/battery-historian/checkinutil"
"github.com/google/battery-historian/historianutils"
"github.com/google/battery-historian/packageutils"
"github.com/google/battery-historian/sliceparse"
bspb "github.com/google/battery-historian/pb/batterystats_proto"
sessionpb "github.com/google/battery-historian/pb/session_proto"
usagepb "github.com/google/battery-historian/pb/usagestats_proto"
)
const (
// minimum number of fields any type of battery stats have
minNumFields = 4
// Current range of supported/expected checkin versions.
minParseReportVersion = 11
maxParseReportVersion = 21
)
// Possible battery stats categories generated by on device java code.
const (
info = "i"
sinceCharged = "l" // SINCE_CHARGED: Since last charged: The only reliable value.
current = "c" // Deprecated
unplugged = "u" // Deprecated: SINCE_UNPLUGGED: Very unreliable and soon to be removed.
)
// String representations of categories the parsing code handles. Contains all
// categories defined in frameworks/base/core/java/android/os/BatteryStats.java
// unless explicitly stated.
const (
versionData = "vers"
uidData = "uid"
wakeupAlarmData = "wua"
apkData = "apk"
processData = "pr"
cpuData = "cpu"
sensorData = "sr"
vibratorData = "vib"
foregroundData = "fg"
stateTimeData = "st"
wakelockData = "wl"
syncData = "sy"
jobData = "jb"
kernelWakelockData = "kwl"
wakeupReasonData = "wr"
networkData = "nt"
userActivityData = "ua"
batteryData = "bt"
batteryDischargeData = "dc"
batteryLevelData = "lv"
globalWifiData = "gwfl"
globalWifiControllerData = "gwfcd"
wifiControllerData = "wfcd"
wifiData = "wfl"
bluetoothControllerData = "ble"
bluetoothMiscData = "blem"
globalBluetoothControllerData = "gble" // Previously globalBluetoothData
miscData = "m"
modemControllerData = "mcd"
globalModemControllerData = "gmcd"
globalNetworkData = "gn"
// HISTORY_STRING_POOL (hsp) is not included in the checkin log.
// HISTORY_DATA (h) is not included in the checkin log.
screenBrightnessData = "br"
signalStrengthTimeData = "sgt"
signalScanningTimeData = "sst"
signalStrengthCountData = "sgc"
dataConnectionTimeData = "dct"
dataConnectionCountData = "dcc"
wifiStateTimeData = "wst"
wifiStateCountData = "wsc"
wifiSupplStateTimeData = "wsst"
wifiSupplStateCountData = "wssc"
wifiSignalStrengthTimeData = "wsgt"
wifiSignalStrengthCountData = "wsgc"
bluetoothStateTimeData = "bst"
bluetoothStateCountData = "bsc"
powerUseSummaryData = "pws"
powerUseItemData = "pwi"
dischargeStepData = "dsd"
chargeStepData = "csd"
dischargeTimeRemainData = "dtr"
chargeTimeRemainData = "ctr"
flashlightData = "fla"
cameraData = "cam"
videoData = "vid"
audioData = "aud"
)
var (
powerUseItemNameMap = map[string]bspb.BatteryStats_System_PowerUseItem_Name{
"idle": bspb.BatteryStats_System_PowerUseItem_IDLE,
"cell": bspb.BatteryStats_System_PowerUseItem_CELL,
"phone": bspb.BatteryStats_System_PowerUseItem_PHONE,
"wifi": bspb.BatteryStats_System_PowerUseItem_WIFI,
"blue": bspb.BatteryStats_System_PowerUseItem_BLUETOOTH,
"scrn": bspb.BatteryStats_System_PowerUseItem_SCREEN,
"uid": bspb.BatteryStats_System_PowerUseItem_APP,
"user": bspb.BatteryStats_System_PowerUseItem_USER,
"unacc": bspb.BatteryStats_System_PowerUseItem_UNACCOUNTED,
"over": bspb.BatteryStats_System_PowerUseItem_OVERCOUNTED,
"???": bspb.BatteryStats_System_PowerUseItem_DEFAULT,
"flashlight": bspb.BatteryStats_System_PowerUseItem_FLASHLIGHT,
}
// sharedUIDLabelMap contains a mapping of known shared UID labels to predefined group names.
sharedUIDLabelMap = map[string]string{
"android.media": "MEDIA",
"android.uid.bluetooth": "BLUETOOTH",
"android.uid.nfc": "NFC",
"android.uid.phone": "RADIO", // Associated with UID 1001.
"android.uid.shared": "CONTACTS_PROVIDER", // "com.android.providers.contacts" is a prominent member of the UID group
"android.uid.shell": "SHELL",
"android.uid.system": "ANDROID_SYSTEM",
"android.uid.systemui": "SYSTEM_UI",
"com.google.android.calendar.uid.shared": "GOOGLE_CALENDAR",
"com.google.uid.shared": "GOOGLE_SERVICES",
}
// TODO: get rid of packageNameToSharedUIDMap
// Contains a mapping of known packages with their shared UIDs.
packageNameToSharedUIDMap = map[string]string{
// com.google.uid.shared
"com.google.android.apps.gtalkservice": "GOOGLE_SERVICES",
"com.google.android.backuptransport": "GOOGLE_SERVICES",
"com.google.android.gms": "GOOGLE_SERVICES",
"com.google.android.gms.car.userfeedback": "GOOGLE_SERVICES",
"com.google.android.googleapps": "GOOGLE_SERVICES",
"com.google.android.gsf": "GOOGLE_SERVICES",
"com.google.android.gsf.login": "GOOGLE_SERVICES",
"com.google.android.gsf.notouch": "GOOGLE_SERVICES",
"com.google.android.providers.gmail": "GOOGLE_SERVICES",
"com.google.android.sss.authbridge": "GOOGLE_SERVICES",
"com.google.gch.gateway": "GOOGLE_SERVICES",
// com.google.android.calendar.uid.shared
"com.android.calendar": "GOOGLE_CALENDAR",
"com.google.android.calendar": "GOOGLE_CALENDAR",
"com.google.android.syncadapters.calendar": "GOOGLE_CALENDAR",
// android.uid.system
"android": "ANDROID_SYSTEM",
"com.android.changesettings": "ANDROID_SYSTEM",
"com.android.inputdevices": "ANDROID_SYSTEM",
"com.android.keychain": "ANDROID_SYSTEM",
"com.android.location.fused": "ANDROID_SYSTEM",
"com.android.providers.settings": "ANDROID_SYSTEM",
"com.android.settings": "ANDROID_SYSTEM",
"com.google.android.canvas.settings": "ANDROID_SYSTEM",
"com.lge.SprintHiddenMenu": "ANDROID_SYSTEM",
"com.nvidia.tegraprofiler.security": "ANDROID_SYSTEM",
"com.qualcomm.atfwd": "ANDROID_SYSTEM",
"com.qualcomm.display": "ANDROID_SYSTEM",
// android.uid.phone, associated with UID 1001
"com.android.phone": "RADIO",
"com.android.providers.telephony": "RADIO",
"com.android.sdm.plugins.connmo": "RADIO",
"com.android.sdm.plugins.dcmo": "RADIO",
"com.android.sdm.plugins.sprintdm": "RADIO",
"com.htc.android.qxdm2sd": "RADIO",
"com.android.mms.service": "RADIO",
"com.android.server.telecom": "RADIO",
"com.android.sprint.lifetimedata": "RADIO",
"com.android.stk": "RADIO",
"com.motorola.service.ims": "RADIO",
"com.qualcomm.qti.imstestrunner": "RADIO",
"com.qualcomm.qti.rcsbootstraputil": "RADIO",
"com.qualcomm.qti.rcsimsbootstraputil": "RADIO",
"com.qualcomm.qcrilmsgtunnel": "RADIO",
"com.qualcomm.shutdownlistner": "RADIO",
"org.codeaurora.ims": "RADIO",
"com.asus.atcmd": "RADIO",
"com.mediatek.imeiwriter": "RADIO",
// android.uid.nfc
"com.android.nfc": "NFC",
"com.android.nfc3": "NFC",
"com.google.android.uiccwatchdog": "NFC",
// android.uid.shared
"com.android.contacts": "CONTACTS_PROVIDER",
"com.android.providers.applications": "CONTACTS_PROVIDER",
"com.android.providers.contacts": "CONTACTS_PROVIDER",
"com.android.providers.userdictionary": "CONTACTS_PROVIDER",
// android.media
"com.android.gallery": "MEDIA",
"com.android.providers.downloads": "MEDIA",
"com.android.providers.downloads.ui": "MEDIA",
"com.android.providers.drm": "MEDIA",
"com.android.providers.media": "MEDIA",
// android.uid.systemui
"com.android.keyguard": "SYSTEM_UI",
"com.android.systemui": "SYSTEM_UI",
// android.uid.bluetooth
"com.android.bluetooth": "BLUETOOTH",
// android.uid.shell
"com.android.shell": "SHELL",
}
// KnownUIDs lists all constant UIDs defined in system/core/include/private/android_filesystem_config.h.
// GIDs are excluded. These should never be renumbered.
KnownUIDs = map[int32]string{
0: "ROOT", // traditional unix root user
1000: "ANDROID_SYSTEM", // system server
1001: "RADIO", // telephony subsystem, RIL
1002: "BLUETOOTH", // bluetooth subsystem
1003: "GRAPHICS", // graphics devices
1004: "INPUT", // input devices
1005: "AUDIO", // audio devices
1006: "CAMERA", // camera devices
1007: "LOG", // log devices
1008: "COMPASS", // compass device
1009: "MOUNT", // mountd socket
1010: "WIFI", // wifi subsystem
1011: "ADB", // android debug bridge (adbd)
1012: "INSTALL", // group for installing packages
1013: "MEDIA", // mediaserver process
1014: "DHCP", // dhcp client
1015: "SDCARD_RW", // external storage write access
1016: "VPN", // vpn system
1017: "KEYSTORE", // keystore subsystem
1018: "USB", // USB devices
1019: "DRM", // DRM server
1020: "MDNSR", // MulticastDNSResponder (service discovery)
1021: "GPS", // GPS daemon
// 1022 is deprecated and unused
1023: "MEDIA_RW", // internal media storage write access
1024: "MTP", // MTP USB driver access
// 1025 is deprecated and unused
1026: "DRMRPC", // group for drm rpc
1027: "NFC", // nfc subsystem
1028: "SDCARD_R", // external storage read access
1029: "CLAT", // clat part of nat464
1030: "LOOP_RADIO", // loop radio devices
1031: "MEDIA_DRM", // MediaDrm plugins
1032: "PACKAGE_INFO", // access to installed package details
1033: "SDCARD_PICS", // external storage photos access
1034: "SDCARD_AV", // external storage audio/video access
1035: "SDCARD_ALL", // access all users external storage
1036: "LOGD", // log daemon
1037: "SHARED_RELRO", // creator of shared GNU RELRO files
1038: "DBUS", // dbus-daemon IPC broker process
1039: "TLSDATE", // tlsdate unprivileged user
1040: "MEDIA_EX", // mediaextractor process
1041: "AUDIOSERVER", // audioserver process
1042: "METRICS_COLL", // metrics_collector process
1043: "METRICSD", // metricsd process
1044: "WEBSERV", // webservd process
1045: "DEBUGGERD", // debuggerd unprivileged user
1046: "MEDIA_CODEC", // mediacodec process
1047: "CAMERASERVER", // cameraserver process
1048: "FIREWALL", // firewalld process
1049: "TRUNKS", // trunksd process (TPM daemon)
1050: "NVRAM", // Access-controlled NVRAM
1051: "DNS", // DNS resolution daemon (system: netd)
1052: "DNS_TETHER", // DNS resolution daemon (tether: dnsmasq)
1053: "WEBVIEW_ZYGOTE", // WebView zygote process
1054: "VEHICLE_NETWORK", // Vehicle network service
1055: "MEDIA_AUDIO", // GID for audio files on internal media storage
1056: "MEDIA_VIDEO", // GID for video files on internal media storage
1057: "MEDIA_IMAGE", // GID for image files on internal media storage
1058: "TOMBSTONED", // tombstoned user
1059: "MEDIA_OBB", // GID for OBB files on internal media storage
1060: "ESE", // embedded secure element (eSE) subsystem
1061: "OTA_UPDATE", // resource tracking UID for OTA updates
2000: "SHELL", // adb and debug shell user
2001: "CACHE", // cache access
2002: "DIAG", // access to diagnostic resources
// 2900-2999 is reserved for OEM
// The 3000 series are intended for use as supplemental group id's only.
// They indicate special Android capabilities that the kernel is aware of.
3001: "NET_BT_ADMIN", // bluetooth: create any socket
3002: "NET_BT", // bluetooth: create sco, rfcomm or l2cap sockets
3003: "INET", // can create AF_INET and AF_INET6 sockets
3004: "NET_RAW", // can create raw INET sockets
3005: "NET_ADMIN", // can configure interfaces and routing tables
3006: "NET_BW_STATS", // read bandwidth statistics
3007: "NET_BW_ACCT", // change bandwidth statistics accounting
3008: "NET_BT_STACK", // bluetooth: access config files
3009: "READPROC", // allow /proc read access
3010: "WAKELOCK", // allow system wakelock read/write access
// 5000-5999 is reserved for OEM
9997: "EVERYBODY", // shared between all apps in the same profile
9998: "MISC", // access to misc storage
9999: "NOBODY",
}
// BatteryStatsIDMap contains a list of all the fields in BatteryStats_* messages that are the IDs for the message.
BatteryStatsIDMap = map[reflect.Type]map[int]bool{
// App fields
reflect.TypeOf(&bspb.BatteryStats_App_Apk_Service{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_App_Process{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_App_ScheduledJob{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_App_Sensor{}): {
0: true, // number
},
reflect.TypeOf(&bspb.BatteryStats_App_Sync{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_App_UserActivity{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_App_Wakelock{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_App_WakeupAlarm{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_ControllerActivity_TxLevel{}): {
0: true, // level
},
// System fields
reflect.TypeOf(&bspb.BatteryStats_System_Battery{}): {
5: true, // start_clock_time_msec
},
reflect.TypeOf(&bspb.BatteryStats_System_BluetoothState{}): {
0: true, // name
},
// It doesn't make sense to diff ChargeStep fields.
reflect.TypeOf(&bspb.BatteryStats_System_DataConnection{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_System_KernelWakelock{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_System_PowerUseItem{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_System_PowerUseSummary{}): {
0: true, // battery_capacity_mah
},
reflect.TypeOf(&bspb.BatteryStats_System_ScreenBrightness{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_System_SignalStrength{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_System_WakeupReason{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_System_WifiSignalStrength{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_System_WifiSupplicantState{}): {
0: true, // name
},
reflect.TypeOf(&bspb.BatteryStats_System_WifiState{}): {
0: true, // name
},
}
)
// PackageUIDGroupName returns the predefined group name for the given package name.
// It will return an empty string if there is no predefined group name.
func PackageUIDGroupName(pkg string) string {
return packageNameToSharedUIDMap[pkg]
}
type stepData struct {
timeMsec float32
level float32
displayState *bspb.BatteryStats_System_DisplayState_State
powerSaveMode *bspb.BatteryStats_System_PowerSaveMode_Mode
idleMode *bspb.BatteryStats_System_IdleMode_Mode
}
// WakelockInfo is a data structure used to sort wakelocks by time or count.
type WakelockInfo struct {
Name string
UID int32
Duration time.Duration
MaxDuration time.Duration
TotalDuration time.Duration
Count float32
}
// byAbsTime sorts wakelock by absolute value of the time held.
type byAbsTime []*WakelockInfo
func (a byAbsTime) Len() int { return len(a) }
func (a byAbsTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// sort by decreasing absolute value of time
func (a byAbsTime) Less(i, j int) bool {
x, y := a[i].Duration, a[j].Duration
return math.Abs(float64(x)) >= math.Abs(float64(y))
}
// SortByAbsTime ranks a slice of wakelocks by the absolute value of duration in desc order.
func SortByAbsTime(items []*WakelockInfo) {
sort.Sort(byAbsTime(items))
}
// byTime sorts wakelock by the time held.
type byTime []*WakelockInfo
func (a byTime) Len() int { return len(a) }
func (a byTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// sort by decreasing time order then increasing alphabetic order to break the tie.
func (a byTime) Less(i, j int) bool {
if x, y := a[i].TotalDuration, a[j].TotalDuration; x != y {
return x > y
}
if x, y := a[i].Duration, a[j].Duration; x != y {
return x > y
}
return a[i].Name < a[j].Name
}
// byCount sorts wakelock by count.
type byCount []*WakelockInfo
func (a byCount) Len() int { return len(a) }
func (a byCount) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// sort by decreasing time order then increasing alphabetic order to break the tie
func (a byCount) Less(i, j int) bool {
if x, y := a[i].Count, a[j].Count; x != y {
return x > y
}
return a[i].Name < a[j].Name
}
// SortByTime ranks a slice of wakelocks by duration.
func SortByTime(items []*WakelockInfo) {
sort.Sort(byTime(items))
}
// SortByCount ranks a slice of wakelocks by count.
func SortByCount(items []*WakelockInfo) {
sort.Sort(byCount(items))
}
// ParseBatteryStats parses the aggregated battery stats in checkin report
// according to frameworks/base/core/java/android/os/BatteryStats.java.
func ParseBatteryStats(pc checkinutil.Counter, cr *checkinutil.BatteryReport, pkgs []*usagepb.PackageInfo) (*bspb.BatteryStats, []string, []error) {
// Support a single version and single aggregation type in a checkin report.
var aggregationType bspb.BatteryStats_AggregationType
var allAppComputedPowerMah float32
apkSeen := make(map[apkID]bool)
p := &bspb.BatteryStats{}
p.System = &bspb.BatteryStats_System{}
reportVersion := int32(-1) // Default to -1 so we can tell if the report version was parsed from the report.
var warnings []string
uids, errs := parsePackageManager(pc, cr.RawBatteryStats, pkgs)
if len(errs) > 0 {
return nil, warnings, errs
}
for _, r := range cr.RawBatteryStats {
var rawUID int32
var rawAggregationType, section string
// The first element in r is '9', which used to be the report version but is now just there as a legacy field.
remaining, err := parseSlice(pc, "All", r[1:], &rawUID, &rawAggregationType, §ion)
if err != nil {
errs = append(errs, fmt.Errorf("error parsing entire line: %v", err))
continue
}
if section == uidData {
// uidData is parsed in the PackageManager function
continue
}
if section == versionData { // first line may contain version information in new format
if reportVersion != -1 {
errs = append(errs, fmt.Errorf("multiple %s lines encountered", versionData))
}
// e.g., 9,0,i,vers,15,135,MMB08I,MMB08K
if _, err := parseSlice(pc, versionData, remaining, &reportVersion); err != nil {
errs = append(errs, fmt.Errorf("error parsing version data: %v", err))
}
continue
}
switch rawAggregationType {
case sinceCharged:
aggregationType = bspb.BatteryStats_SINCE_CHARGED
case current:
aggregationType = bspb.BatteryStats_CURRENT
case unplugged:
aggregationType = bspb.BatteryStats_SINCE_UNPLUGGED
case info: // Not an aggregation type so nothing to do.
default:
errs = append(errs, fmt.Errorf("unsupported aggregation type %s", rawAggregationType))
return nil, warnings, errs
}
uid := packageutils.AppID(rawUID)
if uid == 0 {
// Some lines that are parsed will provide a uid of 0, even though 0 is not the
// correct uid for the relevant package.
// See if we can find an application to claim this.
pkg, err := packageutils.GuessPackage(strings.Join(remaining, ","), "", pkgs)
if err != nil {
errs = append(errs, err)
}
// Many applications will match with android, but we should already have the android
// UID in the map, so ignore if a package matches with android.
if pkg.GetPkgName() != "" && pkg.GetPkgName() != "android" {
uid = packageutils.AppID(pkg.GetUid())
}
}
stats, ok := uids[uid]
if !ok {
// Unexpected UID. Some packages are uploaded with a uid of 0 and so won't be found
// until we come across a case like this. Try to determine package from list.
// Passing an empty uid here because if we reach this case, then the uploaded package
// in the list has a uid of 0.
pkg, err := packageutils.GuessPackage(strings.Join(remaining, ","), "", pkgs)
if err != nil {
errs = append(errs, err)
}
if pkg.GetPkgName() != "" && pkg.GetPkgName() != "android" {
stats = &bspb.BatteryStats_App{
Name: pkg.PkgName,
Uid: proto.Int32(uid),
Child: []*bspb.BatteryStats_App_Child{
{
Name: pkg.PkgName,
VersionCode: pkg.VersionCode,
VersionName: pkg.VersionName,
},
},
}
uids[uid] = stats
} else {
if _, ok := KnownUIDs[uid]; !ok {
// We've already gone through the entire package list, and it's not a UID
// that we already know about, so log a warning.
if packageutils.IsSandboxedProcess(uid) {
warnings = append(warnings, fmt.Sprintf("found sandboxed uid for section %q", section))
} else {
warnings = append(warnings, fmt.Sprintf("found unexpected uid %d for section %q", uid, section))
}
}
stats = &bspb.BatteryStats_App{Uid: proto.Int32(uid)}
uids[uid] = stats
}
}
system := p.GetSystem()
// Parse csv lines according to
// frameworks/base/core/java/android/os/BatteryStats.java.
parsed, warn, csErrs := parseSection(pc, reportVersion, rawUID, section, remaining, stats, system, apkSeen, &allAppComputedPowerMah)
e := false
if e, warnings, errs = saveWarningsAndErrors(warnings, warn, errs, csErrs...); e {
return nil, warnings, errs
}
if !parsed {
warnings = append(warnings, fmt.Sprintf("unknown data category %s", section))
}
}
if reportVersion == -1 {
errs = append(errs, errors.New("no report version found"))
} else if reportVersion < minParseReportVersion {
errs = append(errs, fmt.Errorf("old report version %d", reportVersion))
} else if reportVersion > maxParseReportVersion {
warnings = append(warnings, fmt.Sprintf("newer report version %d found", reportVersion))
}
suidMap := make(map[int32]string)
for _, pkg := range pkgs {
if suid := pkg.GetSharedUserId(); suid != "" {
if s, ok := suidMap[pkg.GetUid()]; ok && s != suid {
errs = append(errs, fmt.Errorf("got UID %d with two different shared UID labels: %s and %s", pkg.GetUid(), s, suid))
continue
}
suidMap[pkg.GetUid()] = suid
}
}
processAppInfo(uids, suidMap)
// Copy uids to p.App.
for _, app := range uids {
aggregateAppApk(app)
p.App = append(p.App, app)
}
// Copy to p.System.
p.System.PowerUseItem = append(p.System.PowerUseItem,
&bspb.BatteryStats_System_PowerUseItem{
Name: bspb.BatteryStats_System_PowerUseItem_APP.Enum(),
ComputedPowerMah: proto.Float32(allAppComputedPowerMah),
})
if m := p.System.GetMisc(); m != nil {
// Screen off time is calculated by subtracting screen on time from total battery real time.
diff := p.System.GetBattery().GetBatteryRealtimeMsec() - m.GetScreenOnTimeMsec()
m.ScreenOffTimeMsec = proto.Float32(diff)
if diff < 0 {
errs = append(errs, fmt.Errorf("negative screen off time"))
}
}
p.ReportVersion = proto.Int32(reportVersion)
p.AggregationType = aggregationType.Enum()
p.StartTimeUsec = proto.Int64(p.System.GetBattery().GetStartClockTimeMsec() * 1000)
p.EndTimeUsec = proto.Int64(cr.TimeUsec)
gmsPkg, err := packageutils.GuessPackage("com.google.android.gms", "", pkgs)
if err != nil {
errs = append(errs, err)
}
if gmsPkg != nil {
p.GmsVersion = gmsPkg.VersionCode
}
p.Build = build.Build(cr.BuildID)
if p.GetBuild().GetType() == "user" {
for _, tag := range p.GetBuild().GetTags() {
if tag == "release-keys" {
p.IsUserRelease = proto.Bool(true)
break
}
}
}
p.DeviceGroup = cr.DeviceGroup
p.CheckinRule = cr.CheckinRule
p.Radio = proto.String(cr.Radio)
p.SdkVersion = proto.Int32(cr.SDKVersion)
p.Bootloader = proto.String(cr.Bootloader)
if cr.CellOperator != "" {
p.Carrier = proto.String(cr.CellOperator + "/" + cr.CountryCode)
}
p.CountryCode = proto.String(cr.CountryCode)
p.TimeZone = proto.String(cr.TimeZone)
postProcessBatteryStats(p)
return p, warnings, errs
}
// CreateBatteryReport creates a checkinutil.BatteryReport from the given
// sessionpb.Checkin.
func CreateBatteryReport(cp *sessionpb.Checkin) *checkinutil.BatteryReport {
return &checkinutil.BatteryReport{
TimeUsec: cp.GetBucketSnapshotMsec() * 1000,
TimeZone: cp.GetSystemInfo().GetTimeZone(),
AndroidID: cp.GetAndroidId(),
DeviceGroup: cp.Groups,
BuildID: cp.GetBuildFingerprint(),
Radio: cp.GetSystemInfo().GetBasebandRadio(),
Bootloader: cp.GetSystemInfo().GetBootloader(),
SDKVersion: cp.GetSystemInfo().GetSdkVersion(),
CellOperator: cp.GetSystemInfo().GetNetworkOperator(),
CountryCode: cp.GetSystemInfo().GetCountryCode(),
RawBatteryStats: extractCSV(cp.GetCheckin()),
}
}
// saveWarningsAndErrors appends new errors (ne) and new warnings (nw) to existing slices
// and returns true if new errors were added
func saveWarningsAndErrors(warnings []string, nw string, errors []error, ne ...error) (bool, []string, []error) {
newErr := false
for _, e := range ne {
if e != nil {
errors = append(errors, e)
newErr = true
}
}
if len(nw) > 0 {
warnings = append(warnings, nw)
}
return newErr, warnings, errors
}
// extractCSV extracts the checkin package information and last charged stats from the given input.
func extractCSV(input string) [][]string {
// bs contains since last charged stats, separated by line and comma
var bs [][]string
// we only use since charged data (ignore unplugged data)
for _, arr := range checkinutil.ParseCSV(input) {
if len(arr) < minNumFields {
continue
}
switch arr[2] {
case info, sinceCharged:
bs = append(bs, arr)
}
}
return bs
}
// parseSection parses known checkin sections and returns true if the section was parsed.
// The app and system protos are directly modified.
func parseSection(c checkinutil.Counter, reportVersion, rawUID int32, section string, record []string, app *bspb.BatteryStats_App, system *bspb.BatteryStats_System, apkSeen map[apkID]bool, allAppComputedPowerMah *float32) (bool, string, []error) {
switch section {
case apkData:
warn, errs := parseChildApk(c, record, app, apkSeen, rawUID)
return true, warn, errs
case audioData:
if app.GetAudio() == nil {
app.Audio = &bspb.BatteryStats_App_Audio{}
}
warn, errs := parseAndAccumulate(audioData, record, app.GetAudio())
return true, warn, errs
case batteryData:
warn, errs := SystemBattery(c, record, system)
return true, warn, errs
case batteryDischargeData:
warn, errs := parseSystemBatteryDischarge(c, record, system)
return true, warn, errs
case batteryLevelData:
warn, errs := parseSystemBatteryLevel(c, record, system)
return true, warn, errs
case bluetoothControllerData:
if app.GetBluetoothController() == nil {
d, err := parseControllerData(c, bluetoothControllerData, record)
if err != nil {
return true, "", []error{err}
}
app.BluetoothController = d
return true, "", nil
}
if err := parseAndAccumulateControllerData(c, bluetoothControllerData, record, app.BluetoothController); err != nil {
return true, "", []error{err}
}
return true, "", nil
case bluetoothMiscData:
if app.GetBluetoothMisc() == nil {
app.BluetoothMisc = &bspb.BatteryStats_App_BluetoothMisc{}
}
warn, errs := parseAndAccumulate(bluetoothMiscData, record, app.GetBluetoothMisc())
return true, warn, errs
case cameraData:
if app.GetCamera() == nil {
app.Camera = &bspb.BatteryStats_App_Camera{}
}
warn, errs := parseAndAccumulate(cameraData, record, app.GetCamera())
return true, warn, errs
case chargeStepData:
data, warn, err := parseStepData(record)
if err != nil {
return true, warn, []error{err}
}
system.ChargeStep = append(system.ChargeStep, &bspb.BatteryStats_System_ChargeStep{
TimeMsec: proto.Float32(data.timeMsec),
Level: proto.Float32(data.level),
DisplayState: data.displayState,
PowerSaveMode: data.powerSaveMode,
IdleMode: data.idleMode,
})
return true, warn, nil
case chargeTimeRemainData: // Current format: 9,0,i,ctr,18147528000
if system.ChargeTimeRemaining != nil {
c.Count("error-charge-time-remaining-exist", 1)
return true, "", []error{errors.New("charge time remaining field already exists")}
}
ctr := &bspb.BatteryStats_System_ChargeTimeRemaining{}
warn, errs := parseLine(chargeTimeRemainData, record, ctr)
if len(errs) == 0 {
system.ChargeTimeRemaining = ctr
}
return true, warn, errs
case cpuData:
if app.GetCpu() == nil {
app.Cpu = &bspb.BatteryStats_App_Cpu{}
}
warn, errs := parseAndAccumulate(cpuData, record, app.GetCpu())
return true, warn, errs
case dischargeStepData:
data, warn, err := parseStepData(record)
if err != nil {
return true, warn, []error{err}
}
system.DischargeStep = append(system.DischargeStep, &bspb.BatteryStats_System_DischargeStep{
TimeMsec: proto.Float32(data.timeMsec),
Level: proto.Float32(data.level),
DisplayState: data.displayState,
PowerSaveMode: data.powerSaveMode,
IdleMode: data.idleMode,
})
return true, warn, nil
case dischargeTimeRemainData: // Current format: 9,0,i,dtr,18147528000
if system.DischargeTimeRemaining != nil {
c.Count("error-discharge-time-remaining-exist", 1)
return true, "", []error{errors.New("discharge time remaining field already exists")}
}
dtr := &bspb.BatteryStats_System_DischargeTimeRemaining{}
warn, errs := parseLine(dischargeTimeRemainData, record, dtr)
if len(errs) == 0 {
system.DischargeTimeRemaining = dtr
}
return true, warn, errs
case flashlightData:
if app.GetFlashlight() == nil {
app.Flashlight = &bspb.BatteryStats_App_Flashlight{}
}
warn, errs := parseAndAccumulate(flashlightData, record, app.GetFlashlight())
return true, warn, errs
case foregroundData:
if app.GetForeground() == nil {
app.Foreground = &bspb.BatteryStats_App_Foreground{}
}
warn, errs := parseAndAccumulate(foregroundData, record, app.GetForeground())
return true, warn, errs
case globalBluetoothControllerData:
if reportVersion < 17 {
warn, errs := parseGlobalBluetooth(record, system)
return true, warn, errs
}
d, err := parseControllerData(c, globalBluetoothControllerData, record)
if err != nil {
return true, "", []error{err}
}
system.GlobalBluetoothController = d
return true, "", nil
case globalModemControllerData:
d, err := parseControllerData(c, globalModemControllerData, record)
if err != nil {
return true, "", []error{err}
}
system.GlobalModemController = d
return true, "", nil
case globalNetworkData:
warn, errs := parseGlobalNetwork(c, record, system)
return true, warn, errs
case globalWifiControllerData:
d, err := parseControllerData(c, globalWifiControllerData, record)
if err != nil {
return true, "", []error{err}
}
system.GlobalWifiController = d
return true, "", nil
case globalWifiData:
warn, errs := parseGlobalWifi(record, system)
return true, warn, errs
case jobData:
warn, errs := parseAppScheduledJob(record, app)
return true, warn, errs
case kernelWakelockData:
warn, errs := parseSystemKernelWakelock(record, system)
return true, warn, errs
case miscData:
warn, errs := parseSystemMisc(c, reportVersion, record, system)
return true, warn, errs
case modemControllerData:
if app.GetModemController() == nil {
d, err := parseControllerData(c, modemControllerData, record)
if err != nil {
return true, "", []error{err}
}
app.ModemController = d
return true, "", nil
}
if err := parseAndAccumulateControllerData(c, modemControllerData, record, app.ModemController); err != nil {
return true, "", []error{err}
}
return true, "", nil
case networkData:
warn, errs := parseAppNetwork(record, app)
return true, warn, errs
case powerUseItemData:
warn, err := parseAppSystemPowerUseItem(c, record, app, system, allAppComputedPowerMah)
if err != nil {
return true, warn, []error{err}
}
return true, warn, nil
case powerUseSummaryData:
warn, errs := parseSystemPowerUseSummary(c, record, system)
return true, warn, errs
case processData:
warn, errs := parseAppProcess(record, app)
return true, warn, errs
case screenBrightnessData:
err := parseSystemScreenBrightness(c, record, system)
if err != nil {
return true, "", []error{err}
}
return true, "", nil
case sensorData:
warn, errs := parseAppSensor(record, app)
return true, warn, errs
case signalScanningTimeData:
warn, errs := parseSystemSignalScanningTime(c, record, system)
return true, warn, errs
case stateTimeData:
warn, errs := parseAppStateTime(c, record, reportVersion, app)
return true, warn, errs
case syncData:
warn, errs := parseAppSync(record, app)
return true, warn, errs
case userActivityData:
if packageutils.AppID(rawUID) != 0 {
warn, err := parseAppUserActivity(record, app)
if err != nil {
return true, warn, []error{err}
}
return true, warn, nil
}
return true, "", nil
case vibratorData:
if app.GetVibrator() == nil {
app.Vibrator = &bspb.BatteryStats_App_Vibrator{}
}
warn, errs := parseAndAccumulate(vibratorData, record, app.GetVibrator())
return true, warn, errs
case videoData:
if app.GetVideo() == nil {
app.Video = &bspb.BatteryStats_App_Video{}
}
warn, errs := parseAndAccumulate(videoData, record, app.GetVideo())
return true, warn, errs
case wakelockData:
warn, err := parseAppWakelock(c, reportVersion, record, app)
if err != nil {
return true, warn, []error{err}
}
return true, warn, nil
case wakeupAlarmData:
warn, errs := parseAppWakeupAlarm(record, app)
return true, warn, errs
case wakeupReasonData:
warn, errs := parseSystemWakeupReason(record, system)
return true, warn, errs
case wifiControllerData:
if app.GetWifiController() == nil {
d, err := parseControllerData(c, wifiControllerData, record)
if err != nil {
return true, "", []error{err}
}
app.WifiController = d
return true, "", nil
}
err := parseAndAccumulateControllerData(c, wifiControllerData, record, app.WifiController)
if err != nil {
return true, "", []error{err}
}
return true, "", nil
case wifiData:
warn, errs := parseAppWifi(record, app)
return true, warn, errs
case signalStrengthTimeData, signalStrengthCountData, dataConnectionTimeData, dataConnectionCountData, wifiStateTimeData, wifiStateCountData, bluetoothStateTimeData, bluetoothStateCountData, wifiSupplStateTimeData, wifiSupplStateCountData, wifiSignalStrengthTimeData, wifiSignalStrengthCountData:
warn, err := parseSystemTimeCountPair(c, section, record, system)
if err != nil {
return true, warn, []error{err}
}
return true, warn, nil
default:
return false, "", nil
}
}
// postProcessBatteryStats handles processing and data population of special fields.
func postProcessBatteryStats(bs *bspb.BatteryStats) {