-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
289 lines (242 loc) · 8.77 KB
/
main.go
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
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
"sync"
"time"
"github.com/bitrise-io/go-steputils/stepconf"
"github.com/bitrise-io/go-steputils/tools"
"github.com/bitrise-io/go-utils/command"
"github.com/bitrise-io/go-utils/log"
)
// Define Genymotion constants
const (
GMCloudSaaSInstanceUUID = "GMCLOUD_SAAS_INSTANCE_UUID"
GMCloudSaaSInstanceADBSerialPort = "GMCLOUD_SAAS_INSTANCE_ADB_SERIAL_PORT"
)
// Define variable
var isError bool = false
// Config ...
type Config struct {
GMCloudSaaSEmail string `env:"email"`
GMCloudSaaSPassword stepconf.Secret `env:"password"`
GMCloudSaaSAPIToken stepconf.Secret `env:"api_token"`
GMCloudSaaSRecipeUUID string `env:"recipe_uuid,required"`
GMCloudSaaSAdbSerialPort string `env:"adb_serial_port"`
GMCloudSaaSGmsaasVersion string `env:"gmsaas_version"`
}
type Instance struct {
UUID string `json:"uuid"`
ADB_SERIAL string `json:"adb_serial"`
NAME string `json:"name"`
}
type Output struct {
Instance Instance `json:"instance"`
Instances []Instance `json:"instances"`
}
// install gmsaas if not installed.
func ensureGMSAASisInstalled(version string) error {
path, err := exec.LookPath("gmsaas")
if err != nil {
log.Infof("Installing gmsaas...")
var installCmd *exec.Cmd
if version != "" {
installCmd = exec.Command("pip3", "install", "gmsaas=="+version, "--break-system-packages")
} else {
installCmd = exec.Command("pip3", "install", "gmsaas", "--break-system-packages")
}
if out, err := installCmd.CombinedOutput(); err != nil {
return fmt.Errorf("%s failed, error: %s | output: %s", installCmd.Args, err, out)
}
// Execute asdf reshim to update PATH
exec.Command("asdf", "reshim", "python").CombinedOutput()
if version != "" {
log.Infof("gmsaas %s has been installed.", version)
} else {
log.Infof("gmsaas has been installed.")
}
} else {
log.Infof("gmsaas is already installed: %s", path)
}
// Set Custom user agent to improve customer support
os.Setenv("GMSAAS_USER_AGENT_EXTRA_DATA", "bitrise.io")
return nil
}
// printError prints an error.
func printError(format string, args ...interface{}) {
log.Errorf(format, args...)
}
// abortf prints an error and terminates step
func abortf(format string, args ...interface{}) {
printError(format, args...)
os.Exit(1)
}
// setOperationFailed marked step as failed
func setOperationFailed(format string, args ...interface{}) {
printError(format, args...)
isError = true
}
func getADBSerialFromJSON(jsonData string) string {
var output Output
if err := json.Unmarshal([]byte(jsonData), &output); err != nil {
setOperationFailed("Issue with JSON parsing : %w", err)
}
return output.Instance.ADB_SERIAL
}
func getInstanceDetails(name string) (string, string) {
cmd := command.New("gmsaas", "--format", "json", "instances", "list")
out, err := cmd.RunAndReturnTrimmedCombinedOutput()
if err != nil {
setOperationFailed("Failed to get instances list, error: error: %s | output: %s", cmd.PrintableCommandArgs(), err, out)
return "", ""
}
var output Output
if err := json.Unmarshal([]byte(out), &output); err != nil {
setOperationFailed("Issue with JSON parsing : %w", err)
}
for _, instance := range output.Instances {
if instance.NAME == name {
return instance.UUID, instance.ADB_SERIAL
}
}
return "", ""
}
func configureAndroidSDKPath() {
log.Infof("Configure Android SDK configuration")
value, exists := os.LookupEnv("ANDROID_HOME")
if exists {
cmd := command.New("gmsaas", "config", "set", "android-sdk-path", value)
out, err := cmd.RunAndReturnTrimmedCombinedOutput()
if err != nil {
setOperationFailed("Failed to set android-sdk-path, error: error: %s | output: %s", cmd.PrintableCommandArgs(), err, out)
return
}
log.Infof("Android SDK is configured")
} else {
setOperationFailed("Please set ANDROID_HOME environment variable")
return
}
}
func login(api_token, username, password string) {
log.Infof("Login Genymotion Account")
var cmd *exec.Cmd
if api_token != "" {
cmd = exec.Command("gmsaas", "auth", "token", api_token)
} else if username != "" && password != "" {
cmd = exec.Command("gmsaas", "auth", "login", username, password)
} else {
abortf("Invalid arguments. Must provide either a token or both email and password.")
return
}
if out, err := cmd.CombinedOutput(); err != nil {
abortf("Failed to login with gmsaas, error: error: %s | output: %s", cmd.Args, err, out)
return
}
log.Infof("Logged to Genymotion Cloud SaaS platform")
}
func startInstanceAndConnect(wg *sync.WaitGroup, recipeUUID, instanceName, adbSerialPort string) {
var output Output
defer wg.Done()
cmd := command.New("gmsaas", "--format", "json", "instances", "start", recipeUUID, instanceName)
jsonData, err := cmd.RunAndReturnTrimmedCombinedOutput()
if err != nil {
setOperationFailed("Failed to start a device, error: %s | output: %s\n", err, jsonData)
return
}
if err := json.Unmarshal([]byte(jsonData), &output); err != nil {
setOperationFailed("Issue with JSON parsing : %s", err)
}
// Connect to adb with adb-serial-port
if adbSerialPort != "" {
cmd := command.New("gmsaas", "--format", "json", "instances", "adbconnect", output.Instance.UUID, "--adb-serial-port", adbSerialPort)
ADBjsonData, err := cmd.RunAndReturnTrimmedCombinedOutput()
if err != nil {
setOperationFailed("Failed to connect a device, error: error: %s | output: %s", cmd.PrintableCommandArgs(), err, ADBjsonData)
return
}
if err := json.Unmarshal([]byte(ADBjsonData), &output); err != nil {
setOperationFailed("Issue with JSON parsing : %s", err)
}
} else {
cmd := command.New("gmsaas", "--format", "json", "instances", "adbconnect", output.Instance.UUID)
ADBjsonData, err := cmd.RunAndReturnTrimmedCombinedOutput()
if err != nil {
setOperationFailed("Failed to connect a device, error: error: %s | output: %s", cmd.PrintableCommandArgs(), err, ADBjsonData)
return
}
if err := json.Unmarshal([]byte(ADBjsonData), &output); err != nil {
setOperationFailed("Issue with JSON parsing : %s", err)
}
}
log.Infof("Genymotion instance UUID : %s has been started and connected with ADB Serial Port : %s", output.Instance.UUID, output.Instance.ADB_SERIAL)
}
func main() {
var c Config
if err := stepconf.Parse(&c); err != nil {
abortf("Issue with input: %s", err)
}
stepconf.Print(c)
if err := ensureGMSAASisInstalled(c.GMCloudSaaSGmsaasVersion); err != nil {
abortf("%s", err)
}
configureAndroidSDKPath()
if err := tools.ExportEnvironmentWithEnvman("GMSAAS_USER_AGENT_EXTRA_DATA", "bitrise.io"); err != nil {
printError("Failed to export %s, error: %v", "GMSAAS_USER_AGENT_EXTRA_DATA", err)
}
if c.GMCloudSaaSAPIToken != "" {
login(string(c.GMCloudSaaSAPIToken), "", "")
} else {
login("", c.GMCloudSaaSEmail, string(c.GMCloudSaaSPassword))
}
instancesList := []string{}
adbSerialList := []string{}
adbSerialPortList := []string{}
recipesList := strings.Split(c.GMCloudSaaSRecipeUUID, ",")
if len(c.GMCloudSaaSAdbSerialPort) >= 1 {
adbSerialPortList = strings.Split(c.GMCloudSaaSAdbSerialPort, ",")
}
workflowID := os.Getenv("BITRISE_TRIGGERED_WORKFLOW_ID")
log.Infof("Use workflow : %s ", workflowID)
log.Infof("Start %d Android instances on Genymotion Cloud SaaS", len(recipesList))
var wg sync.WaitGroup
t := time.Now().UnixNano()
for cptInstance := 0; cptInstance < len(recipesList); cptInstance++ {
instanceName := fmt.Sprint("bitrise_", workflowID, "_", t, "_", cptInstance)
log.Infof("Start instance : %s on Genymotion Cloud SaaS", instanceName)
wg.Add(1)
if len(adbSerialPortList) >= 1 {
go startInstanceAndConnect(&wg, recipesList[cptInstance], instanceName, adbSerialPortList[cptInstance])
} else {
go startInstanceAndConnect(&wg, recipesList[cptInstance], instanceName, "")
}
}
wg.Wait()
for cptInstance := 0; cptInstance < len(recipesList); cptInstance++ {
instanceName := fmt.Sprint("bitrise_", workflowID, "_", t, "_", cptInstance)
instanceUUID, InstanceADBSerialPort := getInstanceDetails(instanceName)
instancesList = append(instancesList, instanceUUID)
adbSerialList = append(adbSerialList, InstanceADBSerialPort)
}
// --- Step Outputs: Export Environment Variables for other Steps:
outputs := map[string]string{
GMCloudSaaSInstanceUUID: strings.Join(instancesList, ","),
GMCloudSaaSInstanceADBSerialPort: strings.Join(adbSerialList, ","),
}
for k, v := range outputs {
if err := tools.ExportEnvironmentWithEnvman(k, v); err != nil {
abortf("Failed to export %s, error: %v", k, err)
}
}
// --- Exit codes:
// The exit code of your Step is very important. If you return
// with a 0 exit code `bitrise` will register your Step as "successful".
// Any non zero exit code will be registered as "failed" by `bitrise`.
if isError {
// If at least one error happens, step will fail
os.Exit(1)
}
os.Exit(0)
}