summaryrefslogtreecommitdiffstats
path: root/jack-tests/src/com/android/jack/test/runner/DeviceRunner.java
blob: dbb9203486ebb6ec6d2553fffa8852a2999cbf2f (plain)
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
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * 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 com.android.jack.test.runner;

import com.google.common.base.Joiner;

import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.IShellOutputReceiver;
import com.android.ddmlib.ShellCommandUnresponsiveException;
import com.android.ddmlib.SyncException;
import com.android.ddmlib.TimeoutException;
import com.android.jack.test.toolchain.AbstractTestTools;
import com.android.jack.test.toolchain.TestConfigurationException;
import com.android.jack.test.util.ExecFileException;
import com.android.jack.test.util.ExecuteFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Nonnull;

/**
 * This runner is used to execute tests on a device.
 */
public abstract class DeviceRunner extends AbstractRuntimeRunner {

  @Nonnull
  public static final File ROOT_DIR = new File("/system");
  @Nonnull
  public static final File ANDROID_DATA_DIR = new File("/data");

  private static final long ADB_CONNECTION_TIMEOUT = 5000;
  private static final long ADB_WAIT_STEP = ADB_CONNECTION_TIMEOUT / 10;

  @Nonnull
  private MyShellOuputReceiver shellOutput = new MyShellOuputReceiver();

  private class MyShellOuputReceiver implements IShellOutputReceiver {

    @Override
    public void addOutput(@Nonnull byte[] data, int offset, int length) {
      outRedirectStream.println(new String(Arrays.copyOfRange(data, offset, offset + length)));
    }

    @Override
    public void flush() {
    }

    @Override
    public boolean isCancelled() {
      return false;
    }
  }

  public DeviceRunner() {
    super(ROOT_DIR);
    try {
      AndroidDebugBridge.init(/* clientSupport */ false);
    } catch (IllegalStateException ex) {
      // ADB was already initialized, we're fine, so just ignore.
    }
  }

  private class ShellOutputToStringReceiver implements IShellOutputReceiver {

    @Nonnull
    StringBuffer out = new StringBuffer();

    @Override
    public void addOutput(@Nonnull byte[] data, int offset, int length) {
      out.append(new String(Arrays.copyOfRange(data, offset, offset + length)));
    }

    @Override
    public void flush() {
    }

    @Override
    public boolean isCancelled() {
      return false;
    }

    @Nonnull
    public String getOutput() {
      return out.toString();
    }
  }

  protected int runOnDevice(@Nonnull String[] options, @Nonnull String[] mainClasses,
      @Nonnull File... classpathFiles)
      throws RuntimeRunnerException {

    // Assumes adb is in PATH
    AndroidDebugBridge adb = AndroidDebugBridge.createBridge("adb", false);

    long start = System.currentTimeMillis();

    if (isVerbose) {
      outRedirectStream.println("Initializing adb...");
    }

    while (!isAdbInitialized(adb)) {
      long timeLeft = start + ADB_CONNECTION_TIMEOUT - System.currentTimeMillis();
      if (timeLeft <= 0) {
        break;
      }
      try {
        Thread.sleep(ADB_WAIT_STEP);
      } catch (InterruptedException e) {
        throw new RuntimeRunnerException(e);
      }
    }
    if (!isAdbInitialized(adb)) {
      throw new RuntimeRunnerException("adb is not initialized");
    }

    if (isVerbose) {
      outRedirectStream.println("Done");
    }

    IDevice[] connectedDevices = adb.getDevices();

    if (connectedDevices.length == 0) {
      throw new RuntimeRunnerException("No device found");
    }

    int exitStatus = -1;
    for (IDevice device : connectedDevices) {

      checkDeviceRuntime(device);

      if (isVerbose) {
        outRedirectStream.println("Running on device: " + device.getName());
      }

      ensureAdbRoot(device);

      File testsRootDir = new File(device.getMountPoint(IDevice.MNT_DATA) + "/jack-tests");
      File[] desFilePaths = new File[classpathFiles.length];
      try {
        if (isVerbose) {
          outRedirectStream.println("adb shell -s " + device.getSerialNumber() + " mkdir "
              + testsRootDir.getAbsolutePath());
        }
        device.executeShellCommand("mkdir " + testsRootDir.getAbsolutePath(), shellOutput);

        if (isVerbose) {
          outRedirectStream.println("adb -s " + device.getSerialNumber() + " push  "
              + System.getProperty("user.dir") + File.separator + "test-exit-status.sh "
              + testsRootDir.getAbsolutePath() + "/test-exit-status.sh");
        }
        device.pushFile(System.getProperty("user.dir") + File.separator + "test-exit-status.sh",
            testsRootDir.getAbsolutePath() + "/test-exit-status.sh");

        if (isVerbose) {
          outRedirectStream.println("adb -s " + device.getSerialNumber() + " shell chmod 777 "
              + testsRootDir.getAbsolutePath() + "/test-exit-status.sh");
        }
        device.executeShellCommand(
            "chmod 777 " + testsRootDir.getAbsolutePath() + "/test-exit-status.sh", shellOutput);

        int i = 0;
        for (File f : classpathFiles) {
          desFilePaths[i] = new File(testsRootDir, "f" + i + "_"  + f.getName());

          if (isVerbose) {
            outRedirectStream.println("adb -s " + device.getSerialNumber() + " push "
                + f.getAbsolutePath() + " " + desFilePaths[i].getAbsolutePath());
          }
          device.pushFile(f.getAbsolutePath(), desFilePaths[i].getAbsolutePath());
          i++;
        }
      } catch (TimeoutException e) {
        throw new RuntimeRunnerException(e);
      } catch (AdbCommandRejectedException e) {
        throw new RuntimeRunnerException(e);
      } catch (ShellCommandUnresponsiveException e) {
        throw new RuntimeRunnerException(e);
      } catch (IOException e) {
        throw new RuntimeRunnerException(e);
      } catch (SyncException e) {
        throw new RuntimeRunnerException(e);
      }

      String args = Joiner.on(' ').join(buildCommandLine(options, mainClasses, desFilePaths));

      try {
        // Bug : exit code return by adb shell is wrong (always 0)
        // https://code.google.com/p/android/issues/detail?id=3254
        // Use go team hack to work this around
        // https://code.google.com/p/go/source/browse/misc/arm/a

        if (isVerbose) {
          outRedirectStream.println("adb -s " + device.getSerialNumber() + " shell "
              + testsRootDir.getAbsolutePath() + "/test-exit-status.sh " + args);
        }
        device.executeShellCommand(
            testsRootDir.getAbsolutePath() + "/test-exit-status.sh " + args,
            shellOutput);

        File exitStatusFile = AbstractTestTools.createTempFile("exitStatus", "");
        if (isVerbose) {
          outRedirectStream.println("adb -s " + device.getSerialNumber() + " pull "
              + testsRootDir.getAbsolutePath() + "/exitStatus " + exitStatusFile.getAbsolutePath());
        }
        device.pullFile(testsRootDir.getAbsolutePath() + "/exitStatus",
            exitStatusFile.getAbsolutePath());

        BufferedReader br = new BufferedReader(new FileReader(exitStatusFile));
        try {
          String readLine = br.readLine();
          if (readLine == null) {
            throw new RuntimeRunnerException("Exit status not found");
          }
          exitStatus = Integer.parseInt(readLine);
        } finally {
          br.close();
        }

        if (isVerbose) {
          outRedirectStream.println("Exit status: " + exitStatus);
        }

        for (File pushedFile : desFilePaths) {
          if (isVerbose) {
            outRedirectStream.println(
                "adb -s " + device.getSerialNumber() + "rm " + pushedFile.getAbsolutePath());
          }
          device.executeShellCommand("rm " + pushedFile.getAbsolutePath(), shellOutput);
        }

        if (exitStatus != 0) {
          errRedirectStream.println("Execution failed on device '" + device.getName() + "'");
          break;
        }

      } catch (TimeoutException e) {
        throw new RuntimeRunnerException(e);
      } catch (AdbCommandRejectedException e) {
        throw new RuntimeRunnerException(e);
      } catch (ShellCommandUnresponsiveException e) {
        throw new RuntimeRunnerException(e);
      } catch (IOException e) {
        throw new RuntimeRunnerException(e);
      } catch (SyncException e) {
        throw new RuntimeRunnerException(e);
      }
    }

    return exitStatus;
  }

  @Nonnull
  protected abstract List<String> buildCommandLine(@Nonnull String[] options,
      @Nonnull String[] mainClasses, @Nonnull File... classpathFiles);

  private boolean isAdbInitialized(@Nonnull AndroidDebugBridge adb) {
    return adb.isConnected() && adb.hasInitialDeviceList();
  }

  private void ensureAdbRoot(@Nonnull IDevice device) throws RuntimeRunnerException {
    ShellOutputToStringReceiver outputToString = new ShellOutputToStringReceiver();
    try {
      device.executeShellCommand("id", outputToString);

      if (!outputToString.getOutput().contains("uid=0(root)")) {
        ExecuteFile ef;

        ef = new ExecuteFile("adb -s " + device.getSerialNumber() + " root");
        ef.setOut(System.out);
        ef.setErr(System.err);
        ef.setVerbose(isVerbose);
        ef.run();

        try {
          Thread.sleep(1000);
        } catch (InterruptedException e1) {
          Thread.currentThread().interrupt();
        }
      }
    } catch (TimeoutException e1) {
      throw new RuntimeRunnerException(e1);
    } catch (AdbCommandRejectedException e1) {
      throw new RuntimeRunnerException(e1);
    } catch (ShellCommandUnresponsiveException e1) {
      throw new RuntimeRunnerException(e1);
    } catch (IOException e1) {
      throw new RuntimeRunnerException(e1);
    } catch (ExecFileException e) {
      throw new RuntimeRunnerException("Error while executing 'adb root'", e);
    }
  }

  @Nonnull
  protected abstract String getRuntimeName();

  private void checkDeviceRuntime(@Nonnull IDevice device) throws RuntimeRunnerException {
    ShellOutputToStringReceiver outputToString = new ShellOutputToStringReceiver();
    try {
      device.executeShellCommand("dalvikvm -showversion", outputToString);
      if (!outputToString.getOutput().contains(getRuntimeName())) {
        throw new TestConfigurationException(
            "The plugged device does not run the required runtime: '" + getRuntimeName() + "'");
      }
    } catch (TimeoutException e) {
      throw new RuntimeRunnerException(e);
    } catch (AdbCommandRejectedException e) {
      throw new RuntimeRunnerException(e);
    } catch (ShellCommandUnresponsiveException e) {
      throw new RuntimeRunnerException(e);
    } catch (IOException e) {
      throw new RuntimeRunnerException(e);
    }
  }

}