1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.power.stats;
18 
19 import static org.mockito.Mockito.mock;
20 
21 import android.annotation.NonNull;
22 import android.app.usage.NetworkStatsManager;
23 import android.net.NetworkStats;
24 import android.os.Handler;
25 import android.os.Looper;
26 import android.util.SparseArray;
27 
28 import com.android.internal.annotations.GuardedBy;
29 import com.android.internal.os.BatteryStatsHistory;
30 import com.android.internal.os.Clock;
31 import com.android.internal.os.CpuScalingPolicies;
32 import com.android.internal.os.KernelCpuSpeedReader;
33 import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidActiveTimeReader;
34 import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidClusterTimeReader;
35 import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidFreqTimeReader;
36 import com.android.internal.os.KernelCpuUidTimeReader.KernelCpuUidUserSysTimeReader;
37 import com.android.internal.os.KernelSingleUidTimeReader;
38 import com.android.internal.os.MonotonicClock;
39 import com.android.internal.os.PowerProfile;
40 import com.android.internal.power.EnergyConsumerStats;
41 
42 import java.io.File;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Queue;
46 import java.util.concurrent.Future;
47 
48 /**
49  * Mocks a BatteryStatsImpl object.
50  */
51 public class MockBatteryStatsImpl extends BatteryStatsImpl {
52     public boolean mForceOnBattery;
53     // The mNetworkStats will be used for both wifi and mobile categories
54     private NetworkStats mNetworkStats;
55     private DummyExternalStatsSync mExternalStatsSync = new DummyExternalStatsSync();
56     public static final BatteryStatsConfig DEFAULT_CONFIG =
57             new BatteryStatsConfig.Builder().build();
58 
MockBatteryStatsImpl()59     MockBatteryStatsImpl() {
60         this(new MockClock());
61     }
62 
MockBatteryStatsImpl(Clock clock)63     MockBatteryStatsImpl(Clock clock) {
64         this(clock, null);
65     }
66 
MockBatteryStatsImpl(Clock clock, File historyDirectory)67     MockBatteryStatsImpl(Clock clock, File historyDirectory) {
68         this(clock, historyDirectory, new Handler(Looper.getMainLooper()));
69     }
70 
MockBatteryStatsImpl(Clock clock, File historyDirectory, Handler handler)71     MockBatteryStatsImpl(Clock clock, File historyDirectory, Handler handler) {
72         this(DEFAULT_CONFIG, clock, historyDirectory, handler, new PowerStatsUidResolver());
73     }
74 
MockBatteryStatsImpl(BatteryStatsConfig config, Clock clock, File historyDirectory)75     MockBatteryStatsImpl(BatteryStatsConfig config, Clock clock, File historyDirectory) {
76         this(config, clock, historyDirectory, new Handler(Looper.getMainLooper()),
77                 new PowerStatsUidResolver());
78     }
79 
MockBatteryStatsImpl(BatteryStatsConfig config, Clock clock, File historyDirectory, Handler handler, PowerStatsUidResolver powerStatsUidResolver)80     MockBatteryStatsImpl(BatteryStatsConfig config, Clock clock, File historyDirectory,
81             Handler handler, PowerStatsUidResolver powerStatsUidResolver) {
82         super(config, clock, new MonotonicClock(0, clock), historyDirectory, handler,
83                 mock(PlatformIdleStateCallback.class), mock(EnergyStatsRetriever.class),
84                 mock(UserInfoProvider.class), mock(PowerProfile.class),
85                 new CpuScalingPolicies(new SparseArray<>(), new SparseArray<>()),
86                 powerStatsUidResolver, mock(FrameworkStatsLogger.class),
87                 mock(BatteryStatsHistory.TraceDelegate.class),
88                 mock(BatteryStatsHistory.EventLogger.class));
89         setMaxHistoryBuffer(128 * 1024);
90 
91         setExternalStatsSyncLocked(mExternalStatsSync);
92         informThatAllExternalStatsAreFlushed();
93 
94         mHandler = handler;
95 
96         mCpuUidFreqTimeReader = mock(KernelCpuUidFreqTimeReader.class);
97         mKernelWakelockReader = null;
98     }
99 
initMeasuredEnergyStats(String[] customBucketNames)100     public void initMeasuredEnergyStats(String[] customBucketNames) {
101         final boolean[] supportedStandardBuckets =
102                 new boolean[EnergyConsumerStats.NUMBER_STANDARD_POWER_BUCKETS];
103         Arrays.fill(supportedStandardBuckets, true);
104         synchronized (this) {
105             mEnergyConsumerStatsConfig = new EnergyConsumerStats.Config(supportedStandardBuckets,
106                     customBucketNames, new int[0], new String[]{""});
107             mGlobalEnergyConsumerStats = new EnergyConsumerStats(mEnergyConsumerStatsConfig);
108         }
109     }
110 
getOnBatteryTimeBase()111     public TimeBase getOnBatteryTimeBase() {
112         return mOnBatteryTimeBase;
113     }
114 
getOnBatteryScreenOffTimeBase()115     public TimeBase getOnBatteryScreenOffTimeBase() {
116         return mOnBatteryScreenOffTimeBase;
117     }
118 
getScreenState()119     public int getScreenState() {
120         return mScreenState;
121     }
122 
getPendingRemovedUids()123     public Queue<UidToRemove> getPendingRemovedUids() {
124         synchronized (this) {
125             return mPendingRemovedUids;
126         }
127     }
128 
isOnBattery()129     public boolean isOnBattery() {
130         return mForceOnBattery ? true : super.isOnBattery();
131     }
132 
getOnBatteryBackgroundTimeBase(int uid)133     public TimeBase getOnBatteryBackgroundTimeBase(int uid) {
134         return getUidStatsLocked(uid).mOnBatteryBackgroundTimeBase;
135     }
136 
getOnBatteryScreenOffBackgroundTimeBase(int uid)137     public TimeBase getOnBatteryScreenOffBackgroundTimeBase(int uid) {
138         return getUidStatsLocked(uid).mOnBatteryScreenOffBackgroundTimeBase;
139     }
140 
getMobileRadioPowerStateUpdateRateLimit()141     public long getMobileRadioPowerStateUpdateRateLimit() {
142         return MOBILE_RADIO_POWER_STATE_UPDATE_FREQ_MS;
143     }
144 
setNetworkStats(NetworkStats networkStats)145     public MockBatteryStatsImpl setNetworkStats(NetworkStats networkStats) {
146         mNetworkStats = networkStats;
147         return this;
148     }
149 
150     @Override
readMobileNetworkStatsLocked( @onNull NetworkStatsManager networkStatsManager)151     protected NetworkStats readMobileNetworkStatsLocked(
152             @NonNull NetworkStatsManager networkStatsManager) {
153         return mNetworkStats;
154     }
155 
156     @Override
readWifiNetworkStatsLocked( @onNull NetworkStatsManager networkStatsManager)157     protected NetworkStats readWifiNetworkStatsLocked(
158             @NonNull NetworkStatsManager networkStatsManager) {
159         return mNetworkStats;
160     }
161 
setPowerProfile(PowerProfile powerProfile)162     public MockBatteryStatsImpl setPowerProfile(PowerProfile powerProfile) {
163         mPowerProfile = powerProfile;
164         setTestCpuScalingPolicies();
165         return this;
166     }
167 
setTestCpuScalingPolicies()168     public MockBatteryStatsImpl setTestCpuScalingPolicies() {
169         SparseArray<int[]> cpusByPolicy = new SparseArray<>();
170         cpusByPolicy.put(0, new int[]{0});
171         SparseArray<int[]> freqsByPolicy = new SparseArray<>();
172         freqsByPolicy.put(0, new int[]{100, 200, 300});
173 
174         setCpuScalingPolicies(new CpuScalingPolicies(freqsByPolicy, freqsByPolicy));
175         return this;
176     }
177 
setCpuScalingPolicies(CpuScalingPolicies cpuScalingPolicies)178     public MockBatteryStatsImpl setCpuScalingPolicies(CpuScalingPolicies cpuScalingPolicies) {
179         mCpuScalingPolicies = cpuScalingPolicies;
180         return this;
181     }
182 
setKernelCpuUidFreqTimeReader(KernelCpuUidFreqTimeReader reader)183     public MockBatteryStatsImpl setKernelCpuUidFreqTimeReader(KernelCpuUidFreqTimeReader reader) {
184         mCpuUidFreqTimeReader = reader;
185         return this;
186     }
187 
setKernelCpuUidActiveTimeReader( KernelCpuUidActiveTimeReader reader)188     public MockBatteryStatsImpl setKernelCpuUidActiveTimeReader(
189             KernelCpuUidActiveTimeReader reader) {
190         mCpuUidActiveTimeReader = reader;
191         return this;
192     }
193 
setKernelCpuUidClusterTimeReader( KernelCpuUidClusterTimeReader reader)194     public MockBatteryStatsImpl setKernelCpuUidClusterTimeReader(
195             KernelCpuUidClusterTimeReader reader) {
196         mCpuUidClusterTimeReader = reader;
197         return this;
198     }
199 
setKernelCpuUidUserSysTimeReader( KernelCpuUidUserSysTimeReader reader)200     public MockBatteryStatsImpl setKernelCpuUidUserSysTimeReader(
201             KernelCpuUidUserSysTimeReader reader) {
202         mCpuUidUserSysTimeReader = reader;
203         return this;
204     }
205 
setKernelSingleUidTimeReader(KernelSingleUidTimeReader reader)206     public MockBatteryStatsImpl setKernelSingleUidTimeReader(KernelSingleUidTimeReader reader) {
207         mKernelSingleUidTimeReader = reader;
208         return this;
209     }
210 
setKernelCpuSpeedReaders(KernelCpuSpeedReader[] readers)211     public MockBatteryStatsImpl setKernelCpuSpeedReaders(KernelCpuSpeedReader[] readers) {
212         mKernelCpuSpeedReaders = readers;
213         return this;
214     }
215 
setKernelWakelockReader(KernelWakelockReader reader)216     public MockBatteryStatsImpl setKernelWakelockReader(KernelWakelockReader reader) {
217         mKernelWakelockReader = reader;
218         return this;
219     }
220 
setSystemServerCpuThreadReader( SystemServerCpuThreadReader systemServerCpuThreadReader)221     public MockBatteryStatsImpl setSystemServerCpuThreadReader(
222             SystemServerCpuThreadReader systemServerCpuThreadReader) {
223         mSystemServerCpuThreadReader = systemServerCpuThreadReader;
224         return this;
225     }
226 
setUserInfoProvider(UserInfoProvider provider)227     public MockBatteryStatsImpl setUserInfoProvider(UserInfoProvider provider) {
228         mUserInfoProvider = provider;
229         return this;
230     }
231 
setPartialTimers(ArrayList<StopwatchTimer> partialTimers)232     public MockBatteryStatsImpl setPartialTimers(ArrayList<StopwatchTimer> partialTimers) {
233         mPartialTimers = partialTimers;
234         return this;
235     }
236 
setLastPartialTimers(ArrayList<StopwatchTimer> lastPartialTimers)237     public MockBatteryStatsImpl setLastPartialTimers(ArrayList<StopwatchTimer> lastPartialTimers) {
238         mLastPartialTimers = lastPartialTimers;
239         return this;
240     }
241 
setOnBatteryInternal(boolean onBatteryInternal)242     public MockBatteryStatsImpl setOnBatteryInternal(boolean onBatteryInternal) {
243         mOnBatteryInternal = onBatteryInternal;
244         return this;
245     }
246 
247     @GuardedBy("this")
setMaxHistoryFiles(int maxHistoryFiles)248     public MockBatteryStatsImpl setMaxHistoryFiles(int maxHistoryFiles) {
249         mConstants.MAX_HISTORY_FILES = maxHistoryFiles;
250         mConstants.onChange();
251         return this;
252     }
253 
254     @GuardedBy("this")
setMaxHistoryBuffer(int maxHistoryBuffer)255     public MockBatteryStatsImpl setMaxHistoryBuffer(int maxHistoryBuffer) {
256         mConstants.MAX_HISTORY_BUFFER = maxHistoryBuffer;
257         mConstants.onChange();
258         return this;
259     }
260 
261     @GuardedBy("this")
setPerUidModemModel(int perUidModemModel)262     public MockBatteryStatsImpl setPerUidModemModel(int perUidModemModel) {
263         mConstants.PER_UID_MODEM_MODEL = perUidModemModel;
264         mConstants.onChange();
265         return this;
266     }
267 
getAndClearExternalStatsSyncFlags()268     public int getAndClearExternalStatsSyncFlags() {
269         final int flags = mExternalStatsSync.flags;
270         mExternalStatsSync.flags = 0;
271         return flags;
272     }
273 
setDummyExternalStatsSync(DummyExternalStatsSync externalStatsSync)274     public void setDummyExternalStatsSync(DummyExternalStatsSync externalStatsSync) {
275         mExternalStatsSync = externalStatsSync;
276         setExternalStatsSyncLocked(mExternalStatsSync);
277     }
278 
279     @Override
writeSyncLocked()280     public void writeSyncLocked() {
281     }
282 
283     @Override
updateBatteryPropertiesLocked()284     protected void updateBatteryPropertiesLocked() {
285     }
286 
287     public static class DummyExternalStatsSync implements ExternalStatsSync {
288         public int flags = 0;
289 
290         @Override
scheduleSync(String reason, int flags)291         public Future<?> scheduleSync(String reason, int flags) {
292             return null;
293         }
294 
295         @Override
scheduleCleanupDueToRemovedUser(int userId)296         public Future<?> scheduleCleanupDueToRemovedUser(int userId) {
297             return null;
298         }
299 
300         @Override
scheduleCpuSyncDueToRemovedUid(int uid)301         public Future<?> scheduleCpuSyncDueToRemovedUid(int uid) {
302             return null;
303         }
304 
305         @Override
scheduleSyncDueToScreenStateChange(int flag, boolean onBattery, boolean onBatteryScreenOff, int screenState, int[] perDisplayScreenStates)306         public Future<?> scheduleSyncDueToScreenStateChange(int flag, boolean onBattery,
307                 boolean onBatteryScreenOff, int screenState, int[] perDisplayScreenStates) {
308             flags |= flag;
309             return null;
310         }
311 
312         @Override
scheduleCpuSyncDueToWakelockChange(long delayMillis)313         public Future<?> scheduleCpuSyncDueToWakelockChange(long delayMillis) {
314             return null;
315         }
316 
317         @Override
cancelCpuSyncDueToWakelockChange()318         public void cancelCpuSyncDueToWakelockChange() {
319         }
320 
321         @Override
scheduleSyncDueToBatteryLevelChange(long delayMillis)322         public Future<?> scheduleSyncDueToBatteryLevelChange(long delayMillis) {
323             return null;
324         }
325 
326         @Override
scheduleSyncDueToProcessStateChange(int flags, long delayMillis)327         public void scheduleSyncDueToProcessStateChange(int flags, long delayMillis) {
328         }
329     }
330 }
331