1 /* 2 * Copyright (C) 2014 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.tradefed.targetprep; 18 19 import com.android.tradefed.build.IBuildInfo; 20 import com.android.tradefed.config.Option; 21 import com.android.tradefed.config.OptionClass; 22 import com.android.tradefed.device.DeviceNotAvailableException; 23 import com.android.tradefed.device.ITestDevice; 24 import com.android.tradefed.log.LogUtil.CLog; 25 import com.android.tradefed.util.CommandResult; 26 import com.android.tradefed.util.CommandStatus; 27 28 /** A {@link ITargetPreparer} that wipes userdata */ 29 @OptionClass(alias = "device-wiper") 30 public class DeviceWiper extends BaseTargetPreparer { 31 32 @Option(name = "use-erase", description = 33 "instruct wiper to use fastboot erase instead of format") 34 protected boolean mUseErase = false; 35 36 @Override 37 public void setUp(ITestDevice device, IBuildInfo buildInfo) throws TargetSetupError, 38 DeviceNotAvailableException { 39 if (isDisabled()) { 40 return; 41 } 42 CLog.i("Wiping device"); 43 device.rebootIntoBootloader(); 44 if (mUseErase) { 45 doErase(device); 46 } else { 47 doFormat(device); 48 } 49 device.executeFastbootCommand("reboot"); 50 device.waitForDeviceAvailable(); 51 } 52 53 private void doFormat(ITestDevice device) throws DeviceNotAvailableException, TargetSetupError { 54 CLog.d("Attempting fastboot wiping"); 55 CommandResult r = device.executeLongFastbootCommand("-w"); 56 if (r.getStatus() != CommandStatus.SUCCESS) { 57 throw new TargetSetupError(String.format("fastboot wiping failed: %s", r.getStderr()), 58 device.getDeviceDescriptor()); 59 } 60 } 61 62 private void doErase(ITestDevice device) throws DeviceNotAvailableException, TargetSetupError { 63 performFastbootOp(device, "erase", "cache"); 64 performFastbootOp(device, "erase", "userdata"); 65 } 66 67 private void performFastbootOp(ITestDevice device, String op, String partition) 68 throws DeviceNotAvailableException, TargetSetupError { 69 CLog.d("Attempting fastboot %s %s", op, partition); 70 CommandResult r = device.executeLongFastbootCommand(op, partition); 71 if (r.getStatus() != CommandStatus.SUCCESS) { 72 throw new TargetSetupError(String.format("%s %s failed: %s", op, partition, 73 r.getStderr()), device.getDeviceDescriptor()); 74 } 75 } 76 } 77