1 /* 2 * Copyright (C) 2020 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.util; 18 19 import com.android.tradefed.invoker.TestInformation; 20 import com.android.tradefed.invoker.ExecutionFiles.FilesKey; 21 import com.android.tradefed.log.LogUtil.CLog; 22 23 import java.io.File; 24 25 /** A utility class for adb operations. */ 26 public class AdbUtils { 27 28 private static final String PATH_VAR = "PATH"; 29 private static final long PATH_TIMEOUT_MS = 60000L; 30 31 /** 32 * Updates $PATH if a special adb version is used. 33 * 34 * @param testInfo A {@link TestInformation} object. 35 * @param runUtil An {@link IRunUtil} object used to run system command. 36 * @param adbPath The path to the adb binary. 37 */ updateAdb(TestInformation testInfo, IRunUtil runUtil, String adbPath)38 public static void updateAdb(TestInformation testInfo, IRunUtil runUtil, String adbPath) { 39 File updatedAdb = testInfo.executionFiles().get(FilesKey.ADB_BINARY); 40 if (updatedAdb == null) { 41 // Don't check if it's the adb on the $PATH 42 if (!adbPath.equals("adb")) { 43 updatedAdb = new File(adbPath); 44 if (!updatedAdb.exists()) { 45 CLog.w( 46 String.format( 47 "adb path %s doesn't exist. Fall back on the abd in $PATH", 48 adbPath)); 49 updatedAdb = null; 50 } 51 } else { 52 CLog.d("Use the adb in the $PATH."); 53 } 54 } 55 if (updatedAdb == null) { 56 return; 57 } 58 CLog.d("Testing with adb binary at: %s", updatedAdb); 59 // If a special adb version is used, pass it to the PATH 60 CommandResult pathResult = 61 runUtil.runTimedCmd(PATH_TIMEOUT_MS, "/bin/bash", "-c", "echo $" + PATH_VAR); 62 if (!CommandStatus.SUCCESS.equals(pathResult.getStatus())) { 63 throw new RuntimeException( 64 String.format( 65 "Failed to get the $PATH. status: %s, stdout: %s, stderr: %s", 66 pathResult.getStatus(), 67 pathResult.getStdout(), 68 pathResult.getStderr())); 69 } 70 // Include the directory of the adb on the PATH to be used. 71 String path = 72 String.format( 73 "%s:%s", 74 updatedAdb.getParentFile().getAbsolutePath(), 75 pathResult.getStdout().trim()); 76 CLog.d("Using $PATH with updated adb: %s", path); 77 runUtil.setEnvVariable(PATH_VAR, path); 78 // Log the version of adb seen 79 CommandResult versionRes = runUtil.runTimedCmd(PATH_TIMEOUT_MS, "adb", "version"); 80 CLog.d("%s", versionRes.getStdout()); 81 CLog.d("%s", versionRes.getStderr()); 82 } 83 } 84