forked from Azure/acs-engine
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
408 lines (368 loc) · 11.8 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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
package main
import (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"math/rand"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/Azure/acs-engine/test/acs-engine-test/config"
"github.com/Azure/acs-engine/test/acs-engine-test/metrics"
"github.com/Azure/acs-engine/test/acs-engine-test/report"
)
const (
script = "test/step.sh"
testReport = "TestReport.json"
combinedReport = "CombinedReport.json"
metricsEndpoint = ":8125"
metricsNS = "ACSEngine"
metricName = "Error"
)
const usage = `Usage:
acs-engine-test -c <configuration.json> -d <acs-engine root directory>
Options:
-c <configuration.json> : JSON file containing a list of deployment configurations.
Refer to acs-engine/test/acs-engine-test/acs-engine-test.json for examples
-d <acs-engine root directory>
`
var logDir string
var orchestratorRe *regexp.Regexp
func init() {
orchestratorRe = regexp.MustCompile(`"orchestratorType": "(\S+)"`)
}
type ErrorStat struct {
errorInfo *report.ErrorInfo
testCategory string
count int64
}
type TestManager struct {
config *config.TestConfig
reportMgr *report.ReportMgr
lock sync.Mutex
wg sync.WaitGroup
rootDir string
}
func (m *TestManager) Run() error {
n := len(m.config.Deployments)
if n == 0 {
return nil
}
// determine timeout
timeoutMin, err := strconv.Atoi(os.Getenv("STAGE_TIMEOUT_MIN"))
if err != nil {
return fmt.Errorf("Error [Atoi STAGE_TIMEOUT_MIN]: %v", err)
}
timeout := time.Duration(time.Minute * time.Duration(timeoutMin))
// determine number of retries
retries, err := strconv.Atoi(os.Getenv("NUM_OF_RETRIES"))
if err != nil {
fmt.Println("Warning: NUM_OF_RETRIES is not set or invalid. Assuming 1")
retries = 1
}
// login to Azure
if _, err := m.runStep("init", "set_azure_account", os.Environ(), timeout); err != nil {
return err
}
// return values for tests
success := make([]bool, n)
rand.Seed(time.Now().UnixNano())
m.wg.Add(n)
for index, dep := range m.config.Deployments {
go func(index int, dep config.Deployment) {
defer m.wg.Done()
resMap := make(map[string]*ErrorStat)
for attempt := 0; attempt < retries; attempt++ {
errorInfo := m.testRun(dep, index, attempt, timeout)
// do not retry if successful
if errorInfo == nil {
success[index] = true
break
}
if errorStat, ok := resMap[errorInfo.ErrName]; !ok {
resMap[errorInfo.ErrName] = &ErrorStat{errorInfo: errorInfo, testCategory: dep.TestCategory, count: 1}
} else {
errorStat.count++
}
}
sendMetrics(resMap)
}(index, dep)
}
m.wg.Wait()
//create reports
if err = m.reportMgr.CreateTestReport(fmt.Sprintf("%s/%s", logDir, testReport)); err != nil {
fmt.Printf("Failed to create %s: %v\n", testReport, err)
}
if err = m.reportMgr.CreateCombinedReport(fmt.Sprintf("%s/%s", logDir, combinedReport), testReport); err != nil {
fmt.Printf("Failed to create %s: %v\n", combinedReport, err)
}
// fail the test on error
for _, ok := range success {
if !ok {
return errors.New("Test failed")
}
}
return nil
}
func (m *TestManager) testRun(d config.Deployment, index, attempt int, timeout time.Duration) *report.ErrorInfo {
rgPrefix := os.Getenv("RESOURCE_GROUP_PREFIX")
if rgPrefix == "" {
rgPrefix = "x"
fmt.Printf("RESOURCE_GROUP_PREFIX is not set. Using default '%s'\n", rgPrefix)
}
testName := strings.TrimSuffix(d.ClusterDefinition, filepath.Ext(d.ClusterDefinition))
instanceName := fmt.Sprintf("acse-%d-%s-%s-%d-%d", rand.Intn(0x0ffffff), d.Location, os.Getenv("BUILD_NUMBER"), index, attempt)
resourceGroup := fmt.Sprintf("%s-%s-%s-%s-%d-%d", rgPrefix, strings.Replace(testName, "/", "-", -1), d.Location, os.Getenv("BUILD_NUMBER"), index, attempt)
logFile := fmt.Sprintf("%s/%s.log", logDir, resourceGroup)
validateLogFile := fmt.Sprintf("%s/validate-%s.log", logDir, resourceGroup)
// determine orchestrator
env := os.Environ()
env = append(env, fmt.Sprintf("CLUSTER_DEFINITION=examples/%s", d.ClusterDefinition))
cmd := exec.Command("test/step.sh", "get_orchestrator_type")
cmd.Env = env
out, err := cmd.Output()
if err != nil {
wrileLog(logFile, "Error [getOrchestrator %s] : %v", d.ClusterDefinition, err)
return report.NewErrorInfo(testName, "OrchestratorTypeParsingError", "PreRun", d.Location)
}
orchestrator := strings.TrimSpace(string(out))
// update environment
env = append(env, fmt.Sprintf("LOCATION=%s", d.Location))
env = append(env, fmt.Sprintf("ORCHESTRATOR=%s", orchestrator))
env = append(env, fmt.Sprintf("INSTANCE_NAME=%s", instanceName))
env = append(env, fmt.Sprintf("DEPLOYMENT_NAME=%s", instanceName))
env = append(env, fmt.Sprintf("RESOURCE_GROUP=%s", resourceGroup))
// add scenario-specific environment variables
envFile := fmt.Sprintf("examples/%s.env", d.ClusterDefinition)
if _, err = os.Stat(envFile); err == nil {
envHandle, err := os.Open(envFile)
if err != nil {
wrileLog(logFile, "Error [open %s] : %v", envFile, err)
return report.NewErrorInfo(testName, "FileAccessError", "PreRun", d.Location)
}
defer envHandle.Close()
fileScanner := bufio.NewScanner(envHandle)
for fileScanner.Scan() {
str := strings.TrimSpace(fileScanner.Text())
if match, _ := regexp.MatchString(`^\S+=\S+$`, str); match {
env = append(env, str)
}
}
}
var errorInfo *report.ErrorInfo
steps := []string{"create_resource_group", "predeploy", "generate_template", "deploy_template", "postdeploy"}
// determine validation script
if !d.SkipValidation {
validate := fmt.Sprintf("test/cluster-tests/%s/test.sh", orchestrator)
if _, err = os.Stat(fmt.Sprintf("%s/%s", m.rootDir, validate)); err == nil {
env = append(env, fmt.Sprintf("VALIDATE=%s", validate))
steps = append(steps, "validate")
}
}
for _, step := range steps {
txt, err := m.runStep(resourceGroup, step, env, timeout)
if err != nil {
errorInfo = m.reportMgr.Process(txt, testName, d.Location)
wrileLog(logFile, "Error [%s:%s] %v\nOutput: %s", step, resourceGroup, err, txt)
// check AUTOCLEAN flag: if set to 'n', don't remove deployment
if os.Getenv("AUTOCLEAN") == "n" {
env = append(env, "CLEANUP=n")
}
break
}
wrileLog(logFile, txt)
if step == "generate_template" {
// set up extra environment variables available after template generation
validateLogFile = fmt.Sprintf("%s/validate-%s.log", logDir, resourceGroup)
env = append(env, fmt.Sprintf("LOGFILE=%s", validateLogFile))
cmd := exec.Command("test/step.sh", "get_orchestrator_version")
cmd.Env = env
out, err := cmd.Output()
if err != nil {
wrileLog(logFile, "Error [%s:%s] %v", "get_orchestrator_version", resourceGroup, err)
errorInfo = report.NewErrorInfo(testName, "OrchestratorVersionParsingError", "PreRun", d.Location)
break
}
env = append(env, fmt.Sprintf("EXPECTED_ORCHESTRATOR_VERSION=%s", strings.TrimSpace(string(out))))
cmd = exec.Command("test/step.sh", "get_node_count")
cmd.Env = env
out, err = cmd.Output()
if err != nil {
wrileLog(logFile, "Error [%s:%s] %v", "get_node_count", resourceGroup, err)
errorInfo = report.NewErrorInfo(testName, "NodeCountParsingError", "PreRun", d.Location)
break
}
nodesCount := strings.Split(strings.TrimSpace(string(out)), ":")
if len(nodesCount) != 2 {
wrileLog(logFile, "get_node_count: unexpected output '%s'", string(out))
errorInfo = report.NewErrorInfo(testName, "NodeCountParsingError", "PreRun", d.Location)
break
}
env = append(env, fmt.Sprintf("EXPECTED_NODE_COUNT=%s", nodesCount[0]))
env = append(env, fmt.Sprintf("EXPECTED_LINUX_NODE_COUNT=%s", nodesCount[1]))
}
}
// clean up
if txt, err := m.runStep(resourceGroup, "cleanup", env, timeout); err != nil {
wrileLog(logFile, "Error: %v\nOutput: %s", err, txt)
}
if errorInfo == nil {
// do not keep logs for successful test
for _, fname := range []string{logFile, validateLogFile} {
if _, err := os.Stat(fname); !os.IsNotExist(err) {
if err = os.Remove(fname); err != nil {
fmt.Printf("Failed to remove %s : %v\n", fname, err)
}
}
}
}
return errorInfo
}
func isValidEnv() bool {
valid := true
envVars := []string{
"SERVICE_PRINCIPAL_CLIENT_ID",
"SERVICE_PRINCIPAL_CLIENT_SECRET",
"TENANT_ID",
"SUBSCRIPTION_ID",
"CLUSTER_SERVICE_PRINCIPAL_CLIENT_ID",
"CLUSTER_SERVICE_PRINCIPAL_CLIENT_SECRET",
"STAGE_TIMEOUT_MIN"}
for _, envVar := range envVars {
if os.Getenv(envVar) == "" {
fmt.Printf("Must specify environment variable %s\n", envVar)
valid = false
}
}
return valid
}
func (m *TestManager) runStep(name, step string, env []string, timeout time.Duration) (string, error) {
// prevent ARM throttling
m.lock.Lock()
go func() {
time.Sleep(2 * time.Second)
m.lock.Unlock()
}()
cmd := exec.Command("/bin/bash", "-c", fmt.Sprintf("%s %s", script, step))
cmd.Dir = m.rootDir
cmd.Env = env
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &out
if err := cmd.Start(); err != nil {
return "", err
}
timer := time.AfterFunc(timeout, func() {
cmd.Process.Kill()
})
err := cmd.Wait()
timer.Stop()
now := time.Now().Format("15:04:05")
if err != nil {
fmt.Printf("ERROR [%s] [%s %s]\n", now, step, name)
return out.String(), err
}
fmt.Printf("SUCCESS [%s] [%s %s]\n", now, step, name)
return out.String(), nil
}
func wrileLog(fname string, format string, args ...interface{}) {
str := fmt.Sprintf(format, args...)
f, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
fmt.Printf("Error [OpenFile %s] : %v\n", fname, err)
return
}
defer f.Close()
if _, err = f.Write([]byte(str)); err != nil {
fmt.Printf("Error [Write %s] : %v\n", fname, err)
}
}
func sendMetrics(resMap map[string]*ErrorStat) {
for _, errorStat := range resMap {
var severity string
if errorStat.count > 1 {
severity = "Critical"
} else {
severity = "Intermittent"
}
category := errorStat.testCategory
if len(category) == 0 {
category = "generic"
}
// add metrics
dims := map[string]string{
"TestName": errorStat.errorInfo.TestName,
"TestCategory": category,
"Location": errorStat.errorInfo.Location,
"Error": errorStat.errorInfo.ErrName,
"Class": errorStat.errorInfo.ErrClass,
"Severity": severity,
}
err := metrics.AddMetric(metricsEndpoint, metricsNS, metricName, errorStat.count, dims)
if err != nil {
fmt.Printf("Failed to send metric: %v\n", err)
}
}
}
func mainInternal() error {
var configFile string
var rootDir string
var err error
flag.StringVar(&configFile, "c", "", "deployment configurations")
flag.StringVar(&rootDir, "d", "", "acs-engine root directory")
flag.Usage = func() {
fmt.Println(usage)
}
flag.Parse()
testManager := TestManager{}
// validate environment
if !isValidEnv() {
return fmt.Errorf("environment is not set")
}
// get test configuration
if configFile == "" {
return fmt.Errorf("test configuration is not provided")
}
testManager.config, err = config.GetTestConfig(configFile)
if err != nil {
return err
}
// get Jenkins build number
buildNum, err := strconv.Atoi(os.Getenv("BUILD_NUMBER"))
if err != nil {
fmt.Println("Warning: BUILD_NUMBER is not set or invalid. Assuming 0")
buildNum = 0
}
// initialize report manager
testManager.reportMgr = report.New(os.Getenv("JOB_BASE_NAME"), buildNum, len(testManager.config.Deployments))
// check root directory
if rootDir == "" {
return fmt.Errorf("acs-engine root directory is not provided")
}
testManager.rootDir = rootDir
if _, err = os.Stat(fmt.Sprintf("%s/%s", rootDir, script)); err != nil {
return err
}
// make logs directory
logDir = fmt.Sprintf("%s/_logs", rootDir)
os.RemoveAll(logDir)
if err = os.Mkdir(logDir, os.FileMode(0755)); err != nil {
return err
}
// run tests
return testManager.Run()
}
func main() {
if err := mainInternal(); err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
os.Exit(0)
}