This repository has been archived by the owner on Feb 5, 2021. It is now read-only.
/
test.go
390 lines (356 loc) · 12.9 KB
/
test.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
/*
* Copyright (c) 2019 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 image
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"cellery.io/cellery/components/cli/cli"
"cellery.io/cellery/components/cli/pkg/ballerina"
"cellery.io/cellery/components/cli/pkg/constants"
"cellery.io/cellery/components/cli/pkg/kubernetes"
"cellery.io/cellery/components/cli/pkg/util"
)
const CelleryTestVerboseMode = "CELLERY_DEBUG_MODE"
const Logs = "logs"
// RunTest starts Cell instance (along with dependency instances if specified by the user)\
func RunTest(cli cli.Cli, cellImageTag string, instanceName string, startDependencies bool, shareDependencies bool,
dependencyLinks []string, envVars []string, assumeYes bool, debug bool, verbose bool, disableTelepresence bool, incell bool, projLocation string) error {
extractedImage, err := extractImage(cli, cellImageTag, instanceName, dependencyLinks, envVars)
if err != nil {
return err
}
err = startTestCellInstance(cli, extractedImage, instanceName, startDependencies,
shareDependencies, verbose, debug, disableTelepresence, incell, assumeYes, projLocation)
//Cleanup telepresence deployment started for tests
if !disableTelepresence {
DeleteTelepresenceResouces(extractedImage.ImageDir)
}
if err != nil {
return fmt.Errorf("failed to test Cell instance "+instanceName+", %v", err)
}
util.PrintSuccessMessage(fmt.Sprintf("Successfully tested image %s", util.Bold(cellImageTag)))
return nil
}
func startTestCellInstance(cli cli.Cli, extractedImage *ExtractedImage, instanceName string, startDependencies bool, shareDependencies bool,
verbose bool, debug bool, disableTelepresence bool, incell bool, assumeYes bool, projLocation string) error {
currentDir := cli.FileSystem().CurrentDir()
imageDir := extractedImage.ImageDir
runningNode := extractedImage.MainNode
envVars := extractedImage.InstanceEnvVars
imageTag := fmt.Sprintf("%s/%s:%s", runningNode.MetaData.Organization, runningNode.MetaData.Name,
runningNode.MetaData.Version)
verboseMode := strconv.FormatBool(verbose)
var projectDir, balModulePath string
var balEnvVars []*ballerina.EnvironmentVariable
// Set celleryImageDirEnvVar environment variable.
balEnvVars = append(balEnvVars, &ballerina.EnvironmentVariable{
Key: celleryImageDirEnvVar,
Value: imageDir})
// Set verbose
// mode to print debug logs
balEnvVars = append(balEnvVars, &ballerina.EnvironmentVariable{
Key: CelleryTestVerboseMode,
Value: verboseMode})
// Setting user defined environment variables.
for _, envVar := range envVars {
// Export environment variables defined by user for root instance
if envVar.InstanceName == "" || envVar.InstanceName == instanceName {
balEnvVars = append(balEnvVars, &ballerina.EnvironmentVariable{
Key: envVar.Key,
Value: envVar.Value,
})
}
// Export environment variables defined by user for dependent instances
if !(envVar.InstanceName == "" || envVar.InstanceName == instanceName) {
balEnvVars = append(balEnvVars, &ballerina.EnvironmentVariable{
Key: celleryEnvVarPrefix + envVar.InstanceName + "." + envVar.Key,
Value: envVar.Value,
})
}
}
// Get Ballerina Installation if exists
exePath, err := cli.BalExecutor().ExecutablePath()
if err != nil {
return err
}
if debug && exePath == "" {
return fmt.Errorf("Ballerina should be installed to debug tests.")
}
// If --debug flag is passed, start a Telepresence shell
// Else create a ballerina project, copy files from image and execute ballerina test command via Telepresence
if debug {
projectDir, err = filepath.Abs(projLocation)
if err != nil {
return err
}
if !assumeYes {
isConfirmed, err := PromtConfirmation(projectDir, debug)
if err != nil {
return err
}
if !isConfirmed {
return fmt.Errorf("cell testing aborted")
}
}
balEnvVars = append(balEnvVars, &ballerina.EnvironmentVariable{
Key: "DEBUG",
Value: "true",
})
} else {
testDir, err := util.FindRecursiveInDirectory(extractedImage.ImageDir, "tests")
if err != nil {
return err
}
if testDir == nil {
return fmt.Errorf("no tests found in Image %s", imageTag)
}
balSourceName, err := util.GetSourceName(filepath.Join(imageDir, src))
if err != nil {
return fmt.Errorf("failed to find source file in Image %s due to %v", imageTag, err)
}
projectDir = filepath.Join(imageDir, src, balSourceName)
var modules []os.FileInfo
if modules, err = ioutil.ReadDir(filepath.Join(projectDir, src)); err != nil {
return err
}
balModulePath = filepath.Join(projectDir, src, modules[0].Name())
// Check if @test:BeforeSuite and @test:AfterSuite functions are defined in any bal file
// Print a warning if at least one of the functions are missing and prompt for confirmation to continue
var isTestsContainBeforeSuite bool
var isTestsContainAfterSuite bool
balFilesList, err := util.FindRecursiveInDirectory(filepath.Join(balModulePath, "tests"), "*.bal")
if err != nil {
return err
}
for _, balFile := range balFilesList {
isTestsContainBeforeSuite, err = util.FindPatternInFile("@test:BeforeSuite", balFile)
if err != nil {
return err
}
if isTestsContainBeforeSuite {
break
}
}
for _, balFile := range balFilesList {
isTestsContainAfterSuite, err = util.FindPatternInFile("@test:AfterSuite", balFile)
if err != nil {
return err
}
if isTestsContainAfterSuite {
break
}
}
// Print a warning message if atleast one of the functions are missing
// Prompt for confirmation to continue if -y flag is not passed
if !isTestsContainBeforeSuite || !isTestsContainAfterSuite {
var missingFunctions []string
if !isTestsContainBeforeSuite {
missingFunctions = append(missingFunctions, "@BeforeSuite")
}
if !isTestsContainAfterSuite {
missingFunctions = append(missingFunctions, "@AfterSuite")
}
util.PrintWarningMessage(fmt.Sprintf(
"Missing function(s) %s in test files. "+
"Please make sure the instances are already available in the cluster or abort to write the missing functions.",
util.CyanBold(strings.Join(missingFunctions, ", "))))
if !assumeYes {
// passing an empty string for bal project path since it is used only for the message for debugging
isConfirmed, err := PromtConfirmation("", debug)
if err != nil {
return err
}
if !isConfirmed {
return fmt.Errorf("cell testing aborted")
}
}
if err != nil {
return err
}
}
}
//Create ballerina.conf to pass info given in CLI flags to the Ballerina process
err = CreateBallerinaConf(instanceName, extractedImage, startDependencies, shareDependencies, verboseMode, projectDir)
if err != nil {
return err
}
//Create logs directory for test execution logs
err = util.CleanAndCreateDir(filepath.Join(projectDir, "logs"))
if err != nil {
return err
}
target := filepath.Join(currentDir, constants.TargetDirName)
if err = util.CleanOrCreateDir(target); err != nil {
return err
}
var testCmdArgs []string
// if --disable-telepresence flag is passed, pass an empty array to Bal executor since telepresence is not required
if !disableTelepresence {
if testCmdArgs, err = testCommandArgs(cli, incell, imageDir, instanceName); err != nil {
return err
}
}
if err = cli.BalExecutor().Test(testCmdArgs, balEnvVars, projectDir); err != nil {
if err = util.CopyDir(filepath.Join(projectDir, Logs), filepath.Join(target, Logs)); err != nil {
return err
}
return err
}
if err = util.CopyDir(filepath.Join(projectDir, Logs), filepath.Join(target, Logs)); err != nil {
return err
}
return nil
}
func PromtConfirmation(balProj string, debug bool) (bool, error) {
if !debug {
fmt.Printf("%s "+util.Bold("Do you wish to continue running tests (Y/n)? "), util.YellowBold("?"))
} else {
debugMsg := "The following will be created/overwritten in your project location %s:\n" +
" 1) %s\n" +
" 2) %s\n"
fmt.Printf(util.CyanBold(fmt.Sprintf(debugMsg, balProj, constants.BallerinaConf, "logs/")))
fmt.Printf("%s"+util.Bold(" Do you wish to continue debugging tests (Y/n)? "), util.YellowBold("?"))
}
reader := bufio.NewReader(os.Stdin)
confirmation, err := reader.ReadString('\n')
if err != nil {
return false, err
}
if strings.ToLower(strings.TrimSpace(confirmation)) == "n" {
return false, nil
}
return true, nil
}
func CreateBallerinaConf(instanceName string, extractedImage *ExtractedImage, startDependencies bool, shareDependencies bool,
verboseMode string, balProj string) error {
imageDir := extractedImage.ImageDir
envVars := extractedImage.InstanceEnvVars
var imageNameStruct = &dependencyInfo{
Organization: extractedImage.MainNode.MetaData.Organization,
Name: extractedImage.MainNode.MetaData.Name,
Version: extractedImage.MainNode.MetaData.Version,
InstanceName: instanceName,
IsRoot: true,
}
iName, err := json.Marshal(imageNameStruct)
if err != nil {
return err
}
iNameStr := string(iName)
dependencyLinks := extractedImage.RootNodeDependencies
dependencyLinksJson, err := json.Marshal(dependencyLinks)
if err != nil {
return err
}
dependencyLinksStr := string(dependencyLinksJson)
content := []string{fmt.Sprintf(CelleryTestVerboseMode+"=\"%s\"\n", verboseMode)}
content = append(content, fmt.Sprintf(constants.CelleryImageDirEnvVar+"=\"%s\"\n", imageDir))
for _, envVar := range envVars {
content = append(content, fmt.Sprintf(envVar.Key+"=\"%s\"\n", envVar.Value))
}
content = append(content, "[test.config]\n")
content = append(content, fmt.Sprintf("IMAGE_NAME=\"%s\"\n", strings.Replace(iNameStr, "\"", "\\\"", -1)))
content = append(content, fmt.Sprintf("DEPENDENCY_LINKS=\"%s\"\n",
strings.Replace(dependencyLinksStr, "\"", "\\\"", -1)))
content = append(content, fmt.Sprintf("START_DEPENDENCIES=%s\n", strconv.FormatBool(startDependencies)))
content = append(content, fmt.Sprintf("SHARE_DEPENDENCIES=%s\n", strconv.FormatBool(shareDependencies)))
ballerinaConfPath := filepath.Join(balProj, constants.BallerinaConf)
isExistsBalConf, err := util.FileExists(ballerinaConfPath)
if err != nil {
return err
}
if isExistsBalConf {
err := os.Remove(ballerinaConfPath)
if err != nil {
return err
}
}
f, err := os.OpenFile(ballerinaConfPath, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer f.Close()
for _, element := range content {
if _, err = f.WriteString(element); err != nil {
return err
}
}
return nil
}
func CreateTelepresenceResources(incell bool, imageDir string, instanceName string) (*string, error) {
var srcYamlFile string
dstYamlFile := filepath.Join(imageDir, "telepresence.yaml")
var deploymentName string
if incell {
srcYamlFile = filepath.Join(util.CelleryInstallationDir(), constants.K8sArtifacts, constants.TELEPRESENCE, "telepresence-deployment.yaml")
err := util.CopyFile(srcYamlFile, dstYamlFile)
if err != nil {
return nil, err
}
util.ReplaceInFile(dstYamlFile, "{{cell}}", instanceName, -1)
deploymentName = instanceName + "--telepresence"
} else {
srcYamlFile = filepath.Join(util.CelleryInstallationDir(), constants.K8sArtifacts, constants.TELEPRESENCE, "telepresence-cell.yaml")
err := util.CopyFile(srcYamlFile, dstYamlFile)
if err != nil {
return nil, err
}
deploymentName = "telepresence--telepresence-deployment"
}
kubernetes.ApplyFile(dstYamlFile)
time.Sleep(5 * time.Second)
err := kubernetes.WaitForDeployment("available", 900, deploymentName)
if err != nil {
return nil, err
}
if !incell {
err = kubernetes.WaitForCell("Ready", 30*60, "telepresence")
if err != nil {
return nil, err
}
}
return &deploymentName, nil
}
func DeleteTelepresenceResouces(imageDir string) {
out, err := kubernetes.DeleteResource("cells.mesh.cellery.io", "telepresence")
if err != nil {
util.PrintWarningMessage(
fmt.Sprintf("Failed to delete telepresence resources in the Kubernetes cluster, %v ", fmt.Errorf(out)))
}
}
func testCommandArgs(cli cli.Cli, incell bool, imageDir string, instanceName string) ([]string, error) {
var err error
var deploymentName *string
if err = cli.ExecuteTask("Creating telepresence k8s resources",
"Failed to create telepresence k8s resources",
"", func() error {
deploymentName, err = CreateTelepresenceResources(incell, imageDir, instanceName)
return err
}); err != nil {
return nil, err
}
var telArgs = []string{"--deployment", *deploymentName}
return telArgs, nil
}