├── settings.gradle ├── CHANGELOG.md ├── swarmer ├── swarmer.gif ├── src │ ├── main │ │ └── kotlin │ │ │ └── com │ │ │ └── gojuno │ │ │ └── swarmer │ │ │ ├── Main.kt │ │ │ ├── Args.kt │ │ │ └── Emulators.kt │ └── test │ │ └── kotlin │ │ └── com │ │ └── gojuno │ │ └── swarmer │ │ ├── ArgsSpec.kt │ │ └── EmulatorsSpec.kt └── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── .travis.yml ├── ci └── build.sh ├── dependencies.gradle ├── gradlew.bat ├── gradlew ├── README.md └── LICENSE.txt /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':swarmer' 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # See [Releases](https://github.com/gojuno/swarmer/releases) 2 | -------------------------------------------------------------------------------- /swarmer/swarmer.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gojuno/swarmer/HEAD/swarmer/swarmer.gif -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gojuno/swarmer/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/ 4 | *.iml 5 | .DS_Store 6 | build/ 7 | artifacts/ 8 | /captures 9 | gradle/local.properties 10 | /docs 11 | 12 | # Share code style. 13 | !.idea/codeStyleSettings.xml 14 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Apr 05 19:47:52 MSK 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.7-all.zip 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: shell 2 | 3 | # We use Docker → we need sudo. 4 | sudo: required 5 | 6 | services: 7 | - docker 8 | 9 | script: 10 | - ci/build.sh 11 | 12 | deploy: 13 | - provider: script 14 | script: PUBLISH=true ci/build.sh 15 | skip_cleanup: true 16 | on: 17 | tags: true 18 | 19 | notifications: 20 | email: false 21 | -------------------------------------------------------------------------------- /swarmer/src/main/kotlin/com/gojuno/swarmer/Main.kt: -------------------------------------------------------------------------------- 1 | package com.gojuno.swarmer 2 | 3 | fun main(vararg rawArgs: String) { 4 | rawArgs.toList().apply { 5 | when (parseCommand(this)) { 6 | is Commands.Start -> { 7 | startEmulators(parseStartArguments(this)) 8 | } 9 | is Commands.Stop -> { 10 | stopAllEmulators(parseStopArguments(this)) 11 | } 12 | Commands.Help -> { 13 | printUsage() 14 | } 15 | else -> { 16 | println("Invalid command!") 17 | printUsage() 18 | } 19 | } 20 | } 21 | 22 | System.exit(0) // Force exit, emulator and logcat redirect will keep running as detached processes. 23 | } 24 | -------------------------------------------------------------------------------- /ci/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | # You can run it from any directory. 5 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 6 | PROJECT_DIR="$DIR/.." 7 | 8 | pushd "$PROJECT_DIR" 9 | 10 | # Files created in mounted volume by container should have same owner as host machine user to prevent chmod problems. 11 | USER_ID=`id -u $USER` 12 | 13 | BUILD_COMMAND="set -xe && " 14 | BUILD_COMMAND+="apt-get update && apt-get --assume-yes install git && " 15 | 16 | if [ "$USER_ID" == "0" ]; then 17 | echo "Warning: running as r00t." 18 | else 19 | BUILD_COMMAND+="apt-get --assume-yes install sudo && " 20 | BUILD_COMMAND+="groupadd --gid $USER_ID build_user && " 21 | BUILD_COMMAND+="useradd --shell /bin/bash --uid $USER_ID --gid $USER_ID --create-home build_user && " 22 | BUILD_COMMAND+="sudo --set-home --preserve-env -u build_user " 23 | fi 24 | 25 | BUILD_COMMAND+="/opt/project/gradlew " 26 | BUILD_COMMAND+="--no-daemon --info --stacktrace " 27 | BUILD_COMMAND+="clean build " 28 | 29 | if [ "$PUBLISH" == "true" ]; then 30 | BUILD_COMMAND+="bintrayUpload " 31 | fi 32 | 33 | BUILD_COMMAND+="--project-dir /opt/project" 34 | 35 | docker run \ 36 | --env BINTRAY_USER="$BINTRAY_USER" \ 37 | --env BINTRAY_API_KEY="$BINTRAY_API_KEY" \ 38 | --env BINTRAY_GPG_PASSPHRASE="$BINTRAY_GPG_PASSPHRASE" \ 39 | --env ANDROID_HOME="" \ 40 | --volume `"pwd"`:/opt/project \ 41 | --rm \ 42 | openjdk:8u171-jdk \ 43 | bash -c "$BUILD_COMMAND" 44 | 45 | popd 46 | -------------------------------------------------------------------------------- /dependencies.gradle: -------------------------------------------------------------------------------- 1 | ext.versions = [ 2 | kotlin : '1.2.41', 3 | 4 | rxJava : '1.3.8', 5 | jCommander : '1.71', 6 | commander : '0.1.8', 7 | 8 | junit : '4.12', 9 | junitPlatform: '1.0.1', 10 | spek : '1.1.5', 11 | assertJ : '3.9.1', 12 | mockito : '2.8.1', 13 | mockitoKotlin: '1.5.0', 14 | ] 15 | 16 | ext.libraries = [ 17 | kotlinStd : "org.jetbrains.kotlin:kotlin-stdlib:$versions.kotlin", 18 | kotlinRuntime : "org.jetbrains.kotlin:kotlin-runtime:$versions.kotlin", 19 | kotlinReflect : "org.jetbrains.kotlin:kotlin-reflect:$versions.kotlin", 20 | 21 | rxJava : "io.reactivex:rxjava:$versions.rxJava", 22 | jCommander : "com.beust:jcommander:$versions.jCommander", 23 | commanderOs : "com.gojuno.commander:os:$versions.commander", 24 | commanderAndroid : "com.gojuno.commander:android:$versions.commander", 25 | 26 | junit : "junit:junit:$versions.junit", 27 | spek : "org.jetbrains.spek:spek-api:$versions.spek", 28 | spekJunitPlatformEngine: "org.jetbrains.spek:spek-junit-platform-engine:$versions.spek", 29 | assertJ : "org.assertj:assertj-core:$versions.assertJ", 30 | mockito : "org.mockito:mockito-core:$versions.mockito", 31 | mockitoKotlin : "com.nhaarman:mockito-kotlin:$versions.mockitoKotlin" 32 | ] 33 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /swarmer/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'kotlin' 2 | apply plugin: 'application' 3 | apply plugin: 'org.junit.platform.gradle.plugin' 4 | apply plugin: 'maven' 5 | apply plugin: 'maven-publish' 6 | apply plugin: 'com.jfrog.bintray' 7 | 8 | mainClassName = 'com.gojuno.swarmer.MainKt' 9 | 10 | dependencies { 11 | compile libraries.kotlinStd 12 | compile libraries.jCommander 13 | compile libraries.commanderOs 14 | compile libraries.commanderAndroid 15 | compile libraries.rxJava 16 | } 17 | 18 | dependencies { 19 | testCompile libraries.spek 20 | testRuntime libraries.spekJunitPlatformEngine 21 | testCompile libraries.assertJ 22 | testCompile libraries.mockito 23 | testCompile libraries.mockitoKotlin 24 | } 25 | 26 | jar { 27 | // Build jar with dependencies. 28 | from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) { 29 | exclude 'META-INF/*.SF' 30 | exclude 'META-INF/*.DSA' 31 | exclude 'META-INF/*.RSA' 32 | } 33 | 34 | manifest { 35 | attributes('Main-Class': mainClassName) 36 | } 37 | } 38 | 39 | junitPlatform { 40 | platformVersion = versions.junitPlatform 41 | 42 | filters { 43 | engines { 44 | include 'spek' 45 | } 46 | } 47 | } 48 | 49 | task sourcesJar(type: Jar, dependsOn: classes) { 50 | classifier = 'sources' 51 | from sourceSets.main.allSource 52 | } 53 | 54 | task javadocJar(type: Jar, dependsOn: javadoc) { 55 | classifier = 'javadoc' 56 | from javadoc.destinationDir 57 | } 58 | 59 | task validatePublishing { 60 | doLast { 61 | validateTagAndVersion() 62 | } 63 | } 64 | 65 | bintrayUpload.dependsOn validatePublishing 66 | 67 | def pomConfig = { 68 | licenses { 69 | license { 70 | name 'The Apache Software License, Version 2.0' 71 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 72 | distribution 'repo' 73 | } 74 | } 75 | developers { 76 | developer { 77 | id 'gojuno' 78 | name 'Juno Inc.' 79 | email 'opensource@gojuno.com' 80 | } 81 | } 82 | } 83 | 84 | publishing { 85 | publications { 86 | SwarmerPublication(MavenPublication) { 87 | from components.java 88 | 89 | artifact sourcesJar 90 | artifact javadocJar 91 | 92 | groupId 'com.gojuno.swarmer' 93 | artifactId 'swarmer' 94 | version projectVersion() 95 | 96 | pom.withXml { 97 | def root = asNode() 98 | root.appendNode('description', 'Tool to create and start multiple Android Emulators in parallel.') 99 | root.appendNode('name', 'Swarmer') 100 | root.appendNode('url', 'https://github.com/gojuno/swarmer') 101 | root.children().last() + pomConfig 102 | } 103 | } 104 | } 105 | } 106 | 107 | bintray { 108 | user = System.getenv('BINTRAY_USER') 109 | key = System.getenv('BINTRAY_API_KEY') 110 | publish = true 111 | 112 | pkg { 113 | repo = 'maven' 114 | name = 'swarmer' 115 | licenses = ['Apache-2.0'] 116 | vcsUrl = 'https://github.com/gojuno/swarmer.git' 117 | issueTrackerUrl = 'https://github.com/gojuno/swarmer/issues' 118 | publications = ['SwarmerPublication'] 119 | 120 | version { 121 | name = projectVersion() 122 | vcsTag = gitTag() 123 | 124 | gpg { 125 | sign = true 126 | passphrase = System.getenv('BINTRAY_GPG_PASSPHRASE') 127 | } 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /swarmer/src/test/kotlin/com/gojuno/swarmer/ArgsSpec.kt: -------------------------------------------------------------------------------- 1 | package com.gojuno.swarmer 2 | 3 | import org.assertj.core.api.Assertions.assertThat 4 | import org.jetbrains.spek.api.Spek 5 | import org.jetbrains.spek.api.dsl.it 6 | import org.jetbrains.spek.api.dsl.on 7 | 8 | class ArgsSpec : Spek({ 9 | 10 | val REQUIRED_ARGS = listOf( 11 | "--emulator-name", "test_emulator_name", 12 | "--package", "test_android_package", 13 | "--android-abi", "test_android_abi", 14 | "--path-to-config-ini", "test_path_to_config_ini" 15 | ) 16 | 17 | val OPTIONAL_ARGS = listOf( 18 | "--emulator-start-options", "-prop option=value", 19 | "--emulator-start-timeout-seconds", "180", 20 | "--redirect-logcat-to", "logcat.txt", 21 | "--verbose-emulator", "--keep-output-on-exit", 22 | "--keep-existing-avds" 23 | ) 24 | 25 | on("parse args with only required fields") { 26 | 27 | val result by memoized { 28 | parseStartArguments(listOf("start") + REQUIRED_ARGS) 29 | } 30 | 31 | it("parses passed args and uses default values for non-required fields") { 32 | assertThat(result).isEqualTo(listOf(Commands.Start( 33 | emulatorName = "test_emulator_name", 34 | pakage = "test_android_package", 35 | androidAbi = "test_android_abi", 36 | pathToConfigIni = "test_path_to_config_ini" 37 | ))) 38 | } 39 | } 40 | 41 | on("parse args with all fields") { 42 | 43 | val result by memoized { 44 | parseStartArguments(listOf("start") + REQUIRED_ARGS + OPTIONAL_ARGS) 45 | } 46 | 47 | it("parses passed args and uses default values for non-required fields") { 48 | assertThat(result).isEqualTo(listOf(Commands.Start( 49 | emulatorName = "test_emulator_name", 50 | pakage = "test_android_package", 51 | androidAbi = "test_android_abi", 52 | pathToConfigIni = "test_path_to_config_ini", 53 | emulatorStartOptions = listOf("-prop option=value"), 54 | emulatorStartTimeoutSeconds = 180L, 55 | redirectLogcatTo = "logcat.txt", 56 | verbose = true, 57 | keepOutputOnExit = true, 58 | keepExistingAvds = true 59 | ))) 60 | } 61 | } 62 | 63 | on("parse multiple args") { 64 | 65 | val result by memoized { 66 | parseStartArguments(listOf( 67 | "start", 68 | "--emulator-name", "test_emulator_name_1", 69 | "--package", "test_android_package_1", 70 | "--android-abi", "test_android_abi_1", 71 | "--path-to-config-ini", "test_path_to_config_ini_1", 72 | "--emulator-name", "test_emulator_name_2", 73 | "--package", "test_android_package_2", 74 | "--android-abi", "test_android_abi_2", 75 | "--path-to-config-ini", "test_path_to_config_ini_2" 76 | )) 77 | } 78 | 79 | it("parses two arguments") { 80 | assertThat(result).isEqualTo(listOf( 81 | Commands.Start( 82 | emulatorName = "test_emulator_name_1", 83 | pakage = "test_android_package_1", 84 | androidAbi = "test_android_abi_1", 85 | pathToConfigIni = "test_path_to_config_ini_1" 86 | ), 87 | Commands.Start( 88 | emulatorName = "test_emulator_name_2", 89 | pakage = "test_android_package_2", 90 | androidAbi = "test_android_abi_2", 91 | pathToConfigIni = "test_path_to_config_ini_2" 92 | ) 93 | )) 94 | } 95 | } 96 | 97 | arrayOf( 98 | "--help", "-help", "help", "-h" 99 | ).forEach { alias -> 100 | on("parses help command for alias : $alias") { 101 | 102 | val result by memoized { 103 | parseCommand(listOf(alias)) 104 | } 105 | 106 | it("parses correct command") { 107 | assertThat(result).isEqualTo(Commands.Help) 108 | } 109 | } 110 | } 111 | 112 | on("parses start command") { 113 | 114 | val result by memoized { 115 | parseCommand(listOf("start") + REQUIRED_ARGS) 116 | } 117 | 118 | it("parses correct command") { 119 | assertThat(result).isEqualTo(Commands.Start()) 120 | } 121 | } 122 | 123 | on("stop command passed") { 124 | 125 | val result by memoized { 126 | parseCommand(listOf("stop")) 127 | } 128 | 129 | it("parses correct command") { 130 | assertThat(result).isEqualTo(Commands.Stop()) 131 | } 132 | } 133 | }) 134 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Swarmer — create, start and wait for Android emulators to boot in parallel. 2 | 3 | `Swarmer` is a replacement for [such bash scripts](https://github.com/travis-ci/travis-cookbooks/blob/master/community-cookbooks/android-sdk/files/default/android-wait-for-emulator) but with features like: 4 | 5 | * Start **multiple** Android Emulators and wait for each to boot in parallel. 6 | * Pass `config.ini` that'll be applied to created emulator. 7 | * Redirect Logcat output of an emulator to a file. 8 | 9 | ![Demo](swarmer/swarmer.gif) 10 | 11 | ## How to use 12 | 13 | `Swarmer` shipped as `jar`, so just run it `java -jar swarmer.jar options`. 14 | 15 | Dependencies: 16 | 17 | * JVM 1.8+ 18 | * [Android SDK Tools 26.0.0+](https://developer.android.com/studio/releases/sdk-tools.html) 19 | 20 | ### Commands 21 | 22 | #### Start 23 | 24 | ```console 25 | java -jar swarmer.jar start … 26 | ``` 27 | 28 | ##### Options 29 | 30 | ###### Required 31 | 32 | * `--emulator-name` 33 | * Name of the emulator, i.e. `test_emulator_1`. 34 | * `--package` 35 | * Package of the system image for this AVD (e.g.'system-images;android-25;google_apis;x86') to pass to `avdmanager create avd --package`. 36 | * `--android-abi` 37 | * Android system image abi, i.e. `google_apis/x86_64`. 38 | * `--path-to-config-ini` 39 | * Path either relative or absolute to the file that will be used as `config.ini` for created emulator. 40 | * Easiest way to get `config.ini` is to create AVD on your machine using Android Studio and then copy config from `~/.android/avd/device_name.avd/config.ini`. 41 | * We recommend to keep `config.ini` in version control so your team members could review it and builds will be reproducible. 42 | 43 | ###### Optional 44 | 45 | * `--help, -help, help, -h` 46 | * Print help and exit. 47 | * `--emulator-start-options` 48 | * Options to pass to `emulator -avd \$emulatorName` command, i.e. `--no-window -prop persist.sys.language=en -prop persist.sys.country=US`. 49 | * `--emulator-start-timeout-seconds` 50 | * Timeout to wait for emulator to finish boot. Default value is 180 seconds. 51 | * `--redirect-logcat-to` 52 | * Path either relative or absolute to the file that will be used to redirect logcat of started emulator to. No redirection will happen if parameter is not presented. 53 | * `--keep-existing-avds` 54 | * Avoid recreating avds and reuse existing ones whenever possible. 55 | 56 | ##### Examples 57 | 58 | ###### Start one emulator 59 | 60 | ```console 61 | java -jar swarmer.jar start \ 62 | --emulator-name test_emulator_1 \ 63 | --package "system-images;android-25;google_apis;x86" \ 64 | --android-abi google_apis/x86_64 \ 65 | --path-to-config-ini emulator_config.ini \ 66 | --emulator-start-options -prop persist.sys.language=en -prop persist.sys.country=US \ 67 | --redirect-logcat-to test_emulator_1_logcat.txt 68 | ``` 69 | 70 | ###### Start two emulators in parallel 71 | 72 | ```console 73 | java -jar swarmer.jar start \ 74 | --emulator-name test_emulator_1 \ 75 | --package "system-images;android-25;google_apis;x86" \ 76 | --android-abi google_apis/x86_64 \ 77 | --path-to-config-ini emulator_config1.ini \ 78 | --emulator-start-options -prop persist.sys.language=en -prop persist.sys.country=US \ 79 | --redirect-logcat-to test_emulator_1_logcat.txt \ 80 | --emulator-name test_emulator_2 \ 81 | --package "system-images;android-23;google_apis;x86" \ 82 | --android-abi google_apis/x86_64 \ 83 | --path-to-config-ini emulator_config2.ini \ 84 | --emulator-start-options -prop persist.sys.language=en -prop persist.sys.country=US \ 85 | --redirect-logcat-to test_emulator_2_logcat.txt 86 | ``` 87 | 88 | ###### Start two emulators sequentially 89 | 90 | ```console 91 | java -jar swarmer.jar start \ 92 | --emulator-name test_emulator_1 \ 93 | --android-target android-25 \ 94 | --android-abi google_apis/x86_64 \ 95 | --path-to-config-ini emulator_config.ini \ 96 | --emulator-start-options -prop persist.sys.language=en -prop persist.sys.country=US \ 97 | --redirect-logcat-to test_emulator_1_logcat.txt 98 | 99 | java -jar swarmer.jar start \ 100 | --emulator-name test_emulator_2 \ 101 | --package "system-images;android-23;google_apis;x86" \ 102 | --android-abi google_apis/x86_64 \ 103 | --path-to-config-ini emulator_config2.ini \ 104 | --emulator-start-options -prop persist.sys.language=en -prop persist.sys.country=US \ 105 | --redirect-logcat-to test_emulator_2_logcat.txt 106 | ``` 107 | 108 | #### Stop 109 | 110 | ```console 111 | java -jar swarmer.jar stop … 112 | ``` 113 | 114 | ##### Options 115 | 116 | ###### Optional 117 | 118 | * `--timeout` 119 | * Timeout for emulators to stop in seconds, default is 15 seconds. 120 | 121 | ###### Stop all running emulators 122 | 123 | ```console 124 | java -jar swarmer.jar stop --timeout 10 125 | ``` 126 | 127 | ### Download 128 | 129 | Swarmer is [available on jcenter](https://jcenter.bintray.com/com/gojuno/swarmer). 130 | 131 | >You can download it in your CI scripts or store it in your version control system (not recommended). 132 | 133 | ```console 134 | SWARMER_VERSION=some-version 135 | curl --fail --location https://jcenter.bintray.com/com/gojuno/swarmer/swarmer/${SWARMER_VERSION}/swarmer-${SWARMER_VERSION}.jar --output /tmp/swarmer.jar 136 | ``` 137 | 138 | All the releases and changelogs can be found on [Releases Page](https://github.com/gojuno/swarmer/releases). 139 | 140 | ### Composer 141 | 142 | Swarmer works great in combination with [Composer][composer] — another tool we've built at Juno. 143 | 144 | [Composer][composer] can run Android Instrumentation tests in parallel on multiple connected devices/emulators. In our [CI Pipeline][ci pipeline] we start emulators with Swarmer and then Composer runs tests on them. 145 | 146 | ### How to build 147 | 148 | Dependencies: you only need `docker` and `bash` installed on your machine. 149 | 150 | ```console 151 | bash ci/build.sh 152 | ``` 153 | 154 | ## License 155 | 156 | ``` 157 | Copyright 2017 Juno, Inc. 158 | 159 | Licensed under the Apache License, Version 2.0 (the "License"); 160 | you may not use this file except in compliance with the License. 161 | You may obtain a copy of the License at 162 | 163 | http://www.apache.org/licenses/LICENSE-2.0 164 | 165 | Unless required by applicable law or agreed to in writing, software 166 | distributed under the License is distributed on an "AS IS" BASIS, 167 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 168 | See the License for the specific language governing permissions and 169 | limitations under the License. 170 | ``` 171 | 172 | [composer]: https://github.com/gojuno/composer 173 | [ci pipeline]: https://github.com/gojuno/engineering/tree/master/articles/ci_pipeline_and_custom_tools_of_android_projects 174 | -------------------------------------------------------------------------------- /swarmer/src/test/kotlin/com/gojuno/swarmer/EmulatorsSpec.kt: -------------------------------------------------------------------------------- 1 | package com.gojuno.swarmer 2 | 3 | import com.gojuno.commander.android.AdbDevice 4 | import com.gojuno.commander.android.adb 5 | import com.gojuno.commander.os.Notification 6 | import com.nhaarman.mockito_kotlin.any 7 | import com.nhaarman.mockito_kotlin.argumentCaptor 8 | import com.nhaarman.mockito_kotlin.mock 9 | import com.nhaarman.mockito_kotlin.verify 10 | import com.nhaarman.mockito_kotlin.whenever 11 | import org.jetbrains.spek.api.Spek 12 | import org.jetbrains.spek.api.dsl.describe 13 | import org.jetbrains.spek.api.dsl.it 14 | import rx.Completable 15 | import rx.Observable 16 | import rx.Single 17 | import java.io.File 18 | import java.util.concurrent.TimeUnit 19 | 20 | class EmulatorsSpec : Spek({ 21 | 22 | val ADB_DEVICES = setOf( 23 | AdbDevice("id1", online = true), 24 | AdbDevice("id2", online = true), 25 | AdbDevice("id3", online = true) 26 | ) 27 | 28 | arrayOf( 29 | Commands.Stop(), 30 | Commands.Stop(timeoutSeconds = 10), 31 | Commands.Stop(timeoutSeconds = 0) 32 | ).forEach { command -> 33 | describe("emulator stop called with timeout ${command.timeoutSeconds}") { 34 | val connectedEmulators by memoized { 35 | { Single.just(ADB_DEVICES) } 36 | } 37 | val startProcess by memoized { 38 | mock<(List, Pair?) -> Completable>().apply { 39 | whenever(invoke(any(), any())).thenReturn(Completable.complete()) 40 | } 41 | } 42 | 43 | beforeEachTest { 44 | stopAllEmulators( 45 | command, 46 | connectedEmulators = connectedEmulators, 47 | completableProcess = startProcess 48 | ) 49 | } 50 | 51 | ADB_DEVICES.forEach { device -> 52 | it("should call stop command for emulator ${device.id}") { 53 | verify(startProcess).invoke( 54 | listOf(adb, "-s", device.id, "emu", "kill"), 55 | command.timeoutSeconds to TimeUnit.SECONDS 56 | ) 57 | } 58 | } 59 | } 60 | } 61 | 62 | val START_COMMANDS = listOf( 63 | Commands.Start( 64 | emulatorName = "emulator_1", 65 | pakage = "system-images;android-25;google_apis;x86", 66 | androidAbi = "google_apis/x86_64", 67 | pathToConfigIni = "config.ini", 68 | emulatorStartOptions = listOf("--no-window"), 69 | emulatorStartTimeoutSeconds = 45L, 70 | redirectOutputTo = "output-dir", 71 | verbose = true, 72 | keepOutputOnExit = true 73 | ), 74 | Commands.Start( 75 | emulatorName = "emulator_2", 76 | pakage = "system-images;android-25;google_apis;x86", 77 | androidAbi = "google_apis/x86_64", 78 | pathToConfigIni = "config2.ini", 79 | emulatorStartOptions = listOf("--no-window"), 80 | emulatorStartTimeoutSeconds = 45L, 81 | redirectOutputTo = "output-dir", 82 | verbose = true 83 | ), 84 | Commands.Start( 85 | emulatorName = "emulator_3", 86 | pakage = "system-images;android-25;google_apis;x86", 87 | androidAbi = "google_apis/x86", 88 | pathToConfigIni = "config3.ini", 89 | emulatorStartOptions = listOf("--no-window --some option"), 90 | emulatorStartTimeoutSeconds = 60L, 91 | verbose = false, 92 | keepOutputOnExit = true 93 | ) 94 | ) 95 | 96 | val EMULATOR_PORTS = Pair(12, 34) 97 | 98 | describe("start emulators command called") { 99 | val connectedAdbDevices by memoized { 100 | { Observable.just(emptySet()) } 101 | } 102 | 103 | val outputFile by memoized { 104 | File("") 105 | } 106 | 107 | val process by memoized { 108 | mock() 109 | } 110 | 111 | val createAvd by memoized { 112 | mock<(Commands.Start) -> Observable>().apply { 113 | whenever(invoke(any())).thenReturn(Observable.just(Unit)) 114 | } 115 | } 116 | 117 | val applyConfig by memoized { 118 | mock<(Commands.Start) -> Observable>().apply { 119 | whenever(invoke(any())).thenReturn(Observable.just(Unit)) 120 | } 121 | } 122 | 123 | val emulator by memoized { 124 | mock<(Commands.Start) -> String>().apply { whenever(invoke(any())).thenReturn("/path/to/emulator/binary") } 125 | } 126 | 127 | val startEmulatorsProcess by memoized { 128 | mock<(List, Commands.Start) -> Observable>().apply { 129 | whenever(invoke(any(), any())).thenReturn(Observable.just( 130 | Notification.Start(process, outputFile), 131 | Notification.Exit(outputFile) 132 | )) 133 | } 134 | } 135 | 136 | val waitForEmulatorToStart by memoized { 137 | val commandCaptor = argumentCaptor() 138 | 139 | mock<(Commands.Start, () -> Observable>, Observable, Pair) -> Observable>().apply { 140 | whenever(invoke(commandCaptor.capture(), any(), any(), any())).thenAnswer { 141 | Observable.just( 142 | Emulator("emulator-${EMULATOR_PORTS.first}", commandCaptor.firstValue.emulatorName) 143 | ) 144 | } 145 | } 146 | } 147 | 148 | val waitForEmulatorToFinishBoot by memoized { 149 | val emulatorCaptor = argumentCaptor() 150 | 151 | mock<(Emulator, Commands.Start) -> Observable>().apply { 152 | whenever(invoke(emulatorCaptor.capture(), any())).thenAnswer { 153 | Observable.just(emulatorCaptor.firstValue) 154 | } 155 | } 156 | } 157 | 158 | val findAvailablePortsForNewEmulator by memoized { 159 | mock<() -> Observable>>().apply { 160 | whenever(invoke()).thenReturn(Observable.just(EMULATOR_PORTS)) 161 | } 162 | } 163 | 164 | beforeEachTest { 165 | startEmulators( 166 | args = START_COMMANDS, 167 | connectedAdbDevices = connectedAdbDevices, 168 | createAvd = createAvd, 169 | applyConfig = applyConfig, 170 | emulator = emulator, 171 | startEmulatorProcess = startEmulatorsProcess, 172 | waitForEmulatorToStart = waitForEmulatorToStart, 173 | findAvailablePortsForNewEmulator = findAvailablePortsForNewEmulator, 174 | waitForEmulatorToFinishBoot = waitForEmulatorToFinishBoot 175 | ) 176 | } 177 | 178 | START_COMMANDS.forEach { command -> 179 | it("should start emulators") { 180 | verify(startEmulatorsProcess).invoke( 181 | listOf( 182 | "/bin/sh", "-c", 183 | "${emulator(command)} ${if (command.verbose) "-verbose" else ""} -avd ${command.emulatorName} -ports ${EMULATOR_PORTS.first},${EMULATOR_PORTS.second} ${command.emulatorStartOptions.joinToString(" ")} &" 184 | ), 185 | command 186 | ) 187 | } 188 | } 189 | } 190 | }) -------------------------------------------------------------------------------- /swarmer/src/main/kotlin/com/gojuno/swarmer/Args.kt: -------------------------------------------------------------------------------- 1 | package com.gojuno.swarmer 2 | 3 | import com.beust.jcommander.JCommander 4 | import com.beust.jcommander.Parameter 5 | import com.beust.jcommander.Parameters 6 | import java.util.* 7 | import java.util.Collections.emptyList 8 | 9 | // No way to share array both for runtime and annotation without reflection. 10 | private const val PARAMETER_EMULATOR_NAME = "--emulator-name" 11 | 12 | sealed class Commands { 13 | companion object { 14 | val ALIASES_HELP = listOf("--help", "-help", "help", "-h") 15 | val ALIASES_START = listOf("start") 16 | val ALIASES_STOP = listOf("stop") 17 | 18 | fun fromStringAlias(alias: String): Commands? = when { 19 | ALIASES_HELP.contains(alias) -> Help 20 | ALIASES_STOP.contains(alias) -> Stop() 21 | ALIASES_START.contains(alias) -> Start() 22 | else -> null 23 | } 24 | } 25 | 26 | @Parameters( 27 | commandDescription = "Print help and exit.", 28 | commandNames = ["--help", "-help", "help", "-h"] 29 | ) 30 | object Help : Commands() 31 | 32 | @Parameters( 33 | commandDescription = "Start emulators listed", 34 | commandNames = ["start"] 35 | ) 36 | data class Start( 37 | @Parameter( 38 | names = [PARAMETER_EMULATOR_NAME], 39 | required = true, 40 | description = "Name for the emulator, i.e. `test_emulator_1` to pass to `avdmanager create avd --name`.", 41 | order = 1 42 | ) 43 | var emulatorName: String = "", 44 | 45 | @Parameter( 46 | names = ["--package"], 47 | required = true, 48 | description = "Package of the system image for this AVD (e.g.'system-images;android-25;google_apis;x86') to pass to `avdmanager create avd --package`.", 49 | order = 2 50 | ) 51 | var pakage: String = "", 52 | 53 | @Parameter( 54 | names = ["--android-abi"], 55 | required = true, 56 | description = "Android system image abi, i.e. `google_apis/x86_64` to pass to `avdmanager create avd --abi`.", 57 | order = 3 58 | ) 59 | var androidAbi: String = "", 60 | 61 | @Parameter( 62 | names = ["--path-to-config-ini"], 63 | required = true, 64 | description = "Path either relative or absolute to the file that will be used as `config.ini` for created emulator.", 65 | order = 4 66 | ) 67 | var pathToConfigIni: String = "", 68 | 69 | @Parameter( 70 | names = ["--emulator-start-options"], 71 | required = false, 72 | variableArity = true, 73 | description = "Options to pass to `emulator -avd \$emulatorName` command, i.e. `--no-window -prop persist.sys.language=en -prop persist.sys.country=US`.", 74 | order = 5 75 | ) 76 | var emulatorStartOptions: List = emptyList(), 77 | 78 | @Parameter( 79 | names = ["--emulator-start-timeout-seconds"], 80 | required = false, 81 | description = "Timeout to wait for emulator to finish boot. Default value is 180 seconds.", 82 | order = 6 83 | ) 84 | var emulatorStartTimeoutSeconds: Long = 180, 85 | 86 | @Parameter( 87 | names = ["--redirect-logcat-to"], 88 | required = false, 89 | description = "Path either relative or absolute to the file that will be used to redirect logcat of started emulator to. No redirection will happen if parameter is not presented.", 90 | order = 7 91 | ) 92 | var redirectLogcatTo: String? = null, 93 | 94 | @Parameter( 95 | names = ["--redirect-output-to"], 96 | required = false, 97 | description = "Path either relative or absolute to the directory that will be used to redirect emulator command output. No redirection will happen if parameter is not presented.", 98 | order = 8 99 | ) 100 | var redirectOutputTo: String? = null, 101 | 102 | @Parameter( 103 | names = ["--verbose-emulator"], 104 | required = false, 105 | description = "Print verbose emulator initialization messages.", 106 | order = 9 107 | ) 108 | var verbose: Boolean = false, 109 | 110 | @Parameter( 111 | names = ["--keep-output-on-exit"], 112 | required = false, 113 | description = "Keep output of emulator command on exit. False by default.", 114 | order = 10 115 | ) 116 | var keepOutputOnExit: Boolean = false, 117 | 118 | @Parameter( 119 | names = ["--use-compat-emulator"], 120 | required = false, 121 | description = "Use old compat emulator tool. Look https://issuetracker.google.com/issues/66886035 for details. False by default.", 122 | order = 11 123 | ) 124 | var useCompatEmulator: Boolean = false, 125 | 126 | @Parameter( 127 | names = ["--keep-existing-avds"], 128 | required = false, 129 | description = "Don't recreate avds if one with the same name already exists.", 130 | order = 12 131 | ) 132 | var keepExistingAvds: Boolean = false 133 | 134 | ) : Commands() 135 | 136 | @Parameters( 137 | commandDescription = "Stop all emulators", 138 | commandNames = ["stop"] 139 | ) 140 | data class Stop( 141 | @Parameter( 142 | names = ["--timeout"], 143 | required = false, 144 | description = "Timeout for emulators to stop in seconds, default is 15 seconds.", 145 | order = 1 146 | ) 147 | var timeoutSeconds: Int = 15 148 | ) : Commands() 149 | } 150 | 151 | fun parseCommand(rawArgs: List) = Commands.fromStringAlias(rawArgs[0]) 152 | 153 | fun parseStartArguments(rawArgs: List): List = 154 | rawArgs 155 | .subList(1, rawArgs.size) // skip command 156 | .fold(ArrayList>()) { accumulator, value -> 157 | accumulator.apply { 158 | if (value == PARAMETER_EMULATOR_NAME) { 159 | add(arrayListOf(value)) 160 | } else { 161 | last().add(value) 162 | } 163 | } 164 | } 165 | .map { args -> 166 | Commands.Start().also { command -> 167 | JCommander(command).parse(*args.toTypedArray()) 168 | } 169 | } 170 | 171 | fun parseStopArguments(rawArgs: List): Commands.Stop = 172 | rawArgs 173 | .subList(1, rawArgs.size) // skip command 174 | .let { stopArguments -> 175 | Commands.Stop().also { command -> 176 | JCommander(command).parse(*stopArguments.toTypedArray()) 177 | } 178 | } 179 | 180 | fun printUsage() = 181 | JCommander.newBuilder() 182 | .addCommand(Commands.ALIASES_HELP.first(), Commands.Help, *Commands.ALIASES_HELP.toTypedArray()) 183 | .addCommand(Commands.Stop()) 184 | .addCommand(Commands.Start()) 185 | .build() 186 | .usage() 187 | 188 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Juno Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /swarmer/src/main/kotlin/com/gojuno/swarmer/Emulators.kt: -------------------------------------------------------------------------------- 1 | package com.gojuno.swarmer 2 | 3 | import com.gojuno.commander.android.* 4 | import com.gojuno.commander.os.Notification 5 | import com.gojuno.commander.os.home 6 | import com.gojuno.commander.os.log 7 | import com.gojuno.commander.os.process 8 | import rx.Completable 9 | import rx.Observable 10 | import rx.Single 11 | import rx.schedulers.Schedulers 12 | import rx.schedulers.Schedulers.io 13 | import java.io.File 14 | import java.lang.System.nanoTime 15 | import java.util.concurrent.Semaphore 16 | import java.util.concurrent.TimeUnit 17 | import java.util.concurrent.TimeUnit.* 18 | import java.util.concurrent.TimeoutException 19 | import java.util.concurrent.atomic.AtomicLong 20 | 21 | val sh: String = "/bin/sh" 22 | val avdManager: String = "$androidHome/tools/bin/avdmanager" 23 | val emulator = "$androidHome/emulator/emulator" 24 | val emulatorCompat = "$androidHome/tools/emulator" 25 | 26 | data class Emulator( 27 | val id: String, 28 | val name: String 29 | ) 30 | 31 | fun startEmulators( 32 | args: List, 33 | connectedAdbDevices: () -> Observable> = ::connectedAdbDevices, 34 | createAvd: (args: Commands.Start) -> Observable = ::createAvd, 35 | applyConfig: (args: Commands.Start) -> Observable = ::applyConfig, 36 | emulator: (args: Commands.Start) -> String = ::emulatorBinary, 37 | findAvailablePortsForNewEmulator: () -> Observable> = ::findAvailablePortsForNewEmulator, 38 | startEmulatorProcess: (List, Commands.Start) -> Observable = ::startEmulatorProcess, 39 | waitForEmulatorToStart: (Commands.Start, () -> Observable>, Observable, Pair) -> Observable = ::waitForEmulatorToStart, 40 | waitForEmulatorToFinishBoot: (Emulator, Commands.Start) -> Observable = ::waitForEmulatorToFinishBoot 41 | ) { 42 | val startTime = System.nanoTime() 43 | 44 | // Sometimes on Linux "emulator -verbose -avd" does not print serial id of started emulator, 45 | // so by allocating ports manually we know which serial id emulator will have. 46 | val availablePortsSemaphore = Semaphore(1) 47 | 48 | val startedEmulators = connectedAdbDevices() 49 | .doOnNext { log("Already running emulators: $it") } 50 | .flatMap { 51 | val startEmulators: List> = args 52 | .map { command -> 53 | startEmulator( 54 | args = command, 55 | createAvd = createAvd, 56 | applyConfig = applyConfig, 57 | availablePortsSemaphore = availablePortsSemaphore, 58 | findAvailablePortsForNewEmulator = findAvailablePortsForNewEmulator, 59 | startEmulatorProcess = startEmulatorProcess, 60 | waitForEmulatorToStart = waitForEmulatorToStart, 61 | connectedAdbDevices = connectedAdbDevices, 62 | emulator = emulator, 63 | waitForEmulatorToFinishBoot = waitForEmulatorToFinishBoot 64 | ) 65 | } 66 | .map { it.subscribeOn(Schedulers.io()) } // So each emulator will start in parallel. 67 | .map { it.doOnNext { log("Emulator $it is ready.") } } 68 | 69 | Observable.zip(startEmulators, { startedEmulator -> startedEmulator }) 70 | } 71 | .map { it.map { it as Emulator }.toSet() } 72 | .toBlocking() 73 | .firstOrDefault(emptySet()) 74 | 75 | log("Swarmer: - \"My job is done here, took ${(System.nanoTime() - startTime).nanosAsSeconds()} seconds, startedEmulators: $startedEmulators, bye bye.\"") 76 | } 77 | 78 | private fun startEmulatorProcess(args: List, command: Commands.Start) = 79 | process( 80 | commandAndArgs = args, 81 | timeout = null, 82 | redirectOutputTo = outputFileForEmulator(command), 83 | keepOutputOnExit = command.keepOutputOnExit 84 | ) 85 | 86 | private fun startEmulator( 87 | args: Commands.Start, 88 | createAvd: (args: Commands.Start) -> Observable, 89 | applyConfig: (args: Commands.Start) -> Observable, 90 | availablePortsSemaphore: Semaphore, 91 | findAvailablePortsForNewEmulator: () -> Observable>, 92 | startEmulatorProcess: (List, Commands.Start) -> Observable, 93 | waitForEmulatorToStart: (Commands.Start, () -> Observable>, Observable, Pair) -> Observable, 94 | connectedAdbDevices: () -> Observable> = ::connectedAdbDevices, 95 | emulator: (Commands.Start) -> String, 96 | waitForEmulatorToFinishBoot: (Emulator, Commands.Start) -> Observable 97 | ): Observable = 98 | createAvd(args) 99 | .flatMap { applyConfig(args) } 100 | .map { availablePortsSemaphore.acquire() } 101 | .flatMap { findAvailablePortsForNewEmulator() } 102 | .doOnNext { log("Ports for emulator ${args.emulatorName}: ${it.first}, ${it.second}.") } 103 | .flatMap { ports -> 104 | startEmulatorProcess( 105 | // Unix only, PR welcome. 106 | listOf(sh, "-c", "${emulator(args)} ${if (args.verbose) "-verbose" else ""} -avd ${args.emulatorName} -ports ${ports.first},${ports.second} ${args.emulatorStartOptions.joinToString(" ")} &"), 107 | args 108 | ).let { process -> 109 | waitForEmulatorToStart(args, connectedAdbDevices, process, ports) 110 | } 111 | } 112 | .map { emulator -> availablePortsSemaphore.release().let { emulator } } 113 | .flatMap { emulator -> 114 | when (args.redirectLogcatTo) { 115 | null -> Observable.just(emulator) 116 | else -> { 117 | val adbDevice = AdbDevice(id = emulator.id, online = true) 118 | val logcatFile = File(args.redirectLogcatTo) 119 | 120 | adbDevice 121 | .redirectLogcatToFile(logcatFile) 122 | .doOnSubscribe { adbDevice.log("Redirecting logcat output to file $logcatFile") } 123 | .toObservable() 124 | .subscribeOn(Schedulers.io()) 125 | .map { emulator } 126 | } 127 | } 128 | } 129 | .flatMap { emulator -> 130 | waitForEmulatorToFinishBoot(emulator, args) 131 | } 132 | .timeout(args.emulatorStartTimeoutSeconds, SECONDS) 133 | .doOnError { 134 | when (it) { 135 | is TimeoutException -> println("Timeout ${args.emulatorStartTimeoutSeconds} seconds, failed to start emulator ${args.emulatorName}.") 136 | else -> Unit 137 | } 138 | } 139 | 140 | fun stopAllEmulators( 141 | args: Commands.Stop, 142 | connectedEmulators: () -> Single> = ::connectedEmulators, 143 | completableProcess: (List, Pair?) -> Completable = ::completableProcess 144 | ) { 145 | val startTime = System.nanoTime() 146 | 147 | connectedEmulators() 148 | .map { emulators -> 149 | log("Stopping running emulators: $emulators.") 150 | emulators.map { emulator -> 151 | completableProcess( 152 | listOf(adb, "-s", emulator.id, "emu", "kill"), 153 | args.timeoutSeconds to SECONDS 154 | ) 155 | .doOnCompleted { log("Stopped emulator $emulator.") } 156 | } 157 | } 158 | .flatMapCompletable(Completable::merge) 159 | .doOnError { log("Error during stopping emulators, error = $it.") } 160 | .doOnCompleted { log("All emulators stopped.") } 161 | .await() 162 | 163 | log("Swarmer: - \"My job is done here, took ${(System.nanoTime() - startTime).nanosAsSeconds()} seconds, bye bye.\"") 164 | } 165 | 166 | private fun completableProcess(args: List, timeout: Pair?) = 167 | process(args, timeout) 168 | .filter { it is Notification.Exit } 169 | .toCompletable() 170 | 171 | private fun createAvd(args: Commands.Start): Observable { 172 | val createAvdProcess = process( 173 | listOf( 174 | avdManager, "create", 175 | "avd", "--force", 176 | "--name", args.emulatorName, 177 | "--package", args.pakage, 178 | "--abi", args.androidAbi 179 | ), 180 | timeout = 60 to SECONDS, 181 | redirectOutputTo = outputDirectory(args), 182 | keepOutputOnExit = args.keepOutputOnExit 183 | ).share() 184 | 185 | val iDontWishToCreateCustomHardwareProfile = Observable 186 | .combineLatest( 187 | createAvdProcess.filter { it is Notification.Start }.cast(Notification.Start::class.java), 188 | Observable.interval(500, MILLISECONDS), 189 | { notification, _ -> notification } 190 | ) 191 | .first { it.output.readText().contains("Do you wish to create a custom hardware profile") } 192 | .observeOn(io()) 193 | .map { it.process.outputStream.writer().use { it.write("no") } } 194 | 195 | val startTime = AtomicLong() 196 | 197 | val createAvd = Observable 198 | .merge(iDontWishToCreateCustomHardwareProfile, createAvdProcess) 199 | .first { it is Notification.Exit } 200 | .doOnError { log("Error during creation of avd ${args.emulatorName}, error = $it") } 201 | .retry(3) // https://code.google.com/p/android/issues/detail?id=262719 202 | .map { Unit } 203 | .doOnSubscribe { log("Creating avd ${args.emulatorName}."); startTime.set(nanoTime()) } 204 | .doOnNext { log("Avd ${args.emulatorName} created in ${(nanoTime() - startTime.get()).nanosAsSeconds()} seconds.") } 205 | .doOnError { log("Could not create avd ${args.emulatorName}, error = $it") } 206 | 207 | return if (args.keepExistingAvds) { 208 | createdEmulators(args).flatMapObservable { 209 | if (it.contains(args.emulatorName)) { 210 | Observable 211 | .just(Unit) 212 | .doOnSubscribe { log("Avd ${args.emulatorName} already exists, will not be overridden.") } 213 | } else { 214 | createAvd 215 | } 216 | } 217 | } else { 218 | createAvd 219 | } 220 | } 221 | 222 | private fun applyConfig(args: Commands.Start): Observable = Observable 223 | .fromCallable { 224 | File(args.pathToConfigIni) 225 | .copyTo(File("$home/.android/avd/${args.emulatorName}.avd/config.ini"), overwrite = true) 226 | } 227 | .map { Unit } 228 | 229 | private fun emulatorBinary(args: Commands.Start): String = 230 | if (args.useCompatEmulator) { 231 | emulatorCompat 232 | } else { 233 | emulator 234 | } 235 | 236 | private fun findAvailablePortsForNewEmulator(): Observable> = connectedAdbDevices() 237 | .map { it.filter { it.isEmulator } } 238 | .map { 239 | if (it.isEmpty()) { 240 | 5554 241 | } else { 242 | it 243 | .map { it.id } 244 | .map { it.substringAfter("emulator-") } 245 | .map { it.toInt() } 246 | .max()!! + 2 247 | } 248 | } 249 | .map { it to it + 1 } 250 | 251 | private fun waitForEmulatorToStart( 252 | args: Commands.Start, 253 | connectedAdbDevices: () -> Observable>, 254 | emulatorProcess: Observable, 255 | ports: Pair 256 | ): Observable { 257 | val startTime = AtomicLong() 258 | 259 | return emulatorProcess 260 | .filter { it is Notification.Start } 261 | .cast(Notification.Start::class.java) 262 | .flatMap { 263 | // Wait for emulator serial number to show up in emulator -avd output. 264 | Observable 265 | .interval(1000, MILLISECONDS) 266 | .flatMap { connectedAdbDevices() } 267 | .map { 268 | if (it.map { it.id }.contains("emulator-${ports.first}")) { 269 | Emulator(id = "emulator-${ports.first}", name = args.emulatorName) 270 | } else { 271 | null 272 | } 273 | } 274 | .filter { it != null } 275 | .first() 276 | } 277 | .cast(Emulator::class.java) // Lost Kotlin nullability after flatMap. 278 | .flatMap { emulator -> 279 | // Wait for emulator to show up in adb devices. 280 | Observable 281 | .interval(1000, MILLISECONDS) 282 | .flatMap { connectedAdbDevices() } 283 | .map { it.firstOrNull { it.id == emulator.id } } 284 | .filter { it != null } 285 | .first() 286 | .map { emulator } 287 | } 288 | .doOnSubscribe { log("Starting emulator ${args.emulatorName}."); startTime.set(nanoTime()) } 289 | .doOnNext { log("Emulator $it started in ${(nanoTime() - startTime.get()).nanosAsSeconds()} seconds.") } 290 | .doOnError { log("Error during start of the emulator ${args.emulatorName}, error = $it") } 291 | } 292 | 293 | private fun waitForEmulatorToFinishBoot( 294 | targetEmulator: Emulator, 295 | args: Commands.Start 296 | ): Observable { 297 | val startTime = AtomicLong() 298 | 299 | return Observable 300 | .interval(1500, MILLISECONDS) 301 | .switchMap { connectedEmulators().toObservable() } 302 | .switchMap { runningEmulators -> 303 | val emulator = runningEmulators.firstOrNull { it.id == targetEmulator.id } 304 | 305 | if (emulator == null || !emulator.online) { 306 | Observable.never() 307 | } else { 308 | process( 309 | listOf( 310 | adb, 311 | "-s", emulator.id, 312 | "shell", 313 | "getprop", "init.svc.bootanim" 314 | ), 315 | timeout = 10 to SECONDS, 316 | redirectOutputTo = outputDirectory(args), 317 | keepOutputOnExit = args.keepOutputOnExit 318 | ) 319 | .filter { it is Notification.Exit } 320 | .cast(Notification.Exit::class.java) 321 | .map { it.output.readText().contains("stopped", ignoreCase = true) } 322 | .switchMap { bootAnimationStopped -> 323 | if (bootAnimationStopped) { 324 | Observable.just(targetEmulator) 325 | } else { 326 | Observable.never() 327 | } 328 | } 329 | } 330 | } 331 | .first() 332 | .doOnSubscribe { log("Waiting boot process to finish for emulator $targetEmulator."); startTime.set(nanoTime()) } 333 | .doOnNext { log("Emulator $targetEmulator finished boot process in ${(nanoTime() - startTime.get()).nanosAsSeconds()} seconds.") } 334 | .doOnError { log("Error during start of the emulator $targetEmulator, error = $it.") } 335 | } 336 | 337 | private fun Long.nanosAsSeconds(): Float = NANOSECONDS.toMillis(this) / 1000f 338 | 339 | private fun outputFileForEmulator(args: Commands.Start) = 340 | File(outputDirectory(args), "${args.emulatorName}.output").apply { 341 | if (!args.keepOutputOnExit) deleteOnExit() 342 | } 343 | 344 | private fun outputDirectory(args: Commands.Start) = 345 | args.redirectOutputTo?.run { 346 | File(this).apply { mkdirs() } 347 | } 348 | 349 | private fun connectedEmulators(): Single> = 350 | connectedAdbDevices().take(1).toSingle().map { it.filter { it.isEmulator }.toSet() } 351 | 352 | private fun createdEmulators(args: Commands.Start, timeout: Pair = 60 to SECONDS): Single> = 353 | process( 354 | commandAndArgs = listOf(emulatorBinary(args), "-list-avds"), 355 | timeout = timeout, 356 | unbufferedOutput = true 357 | ).ofType(Notification.Exit::class.java) 358 | .toSingle() 359 | .map { 360 | it.output.readText() 361 | .split(System.lineSeparator()) 362 | .filter { !it.isBlank() } 363 | .map { it.trim() } 364 | .toSet() 365 | } 366 | --------------------------------------------------------------------------------