aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/internal/cli/cmd/prod_test.go
blob: 5594c846cc8336085e7f679ad08092c2c93a251e (plain) (blame)
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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package cmd

import (
	"bytes"
	"io"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/vespa-engine/vespa/client/go/internal/mock"
	"github.com/vespa-engine/vespa/client/go/internal/util"
	"github.com/vespa-engine/vespa/client/go/internal/vespa"
)

func TestProdInit(t *testing.T) {
	pkgDir := filepath.Join(t.TempDir(), "app")
	createApplication(t, pkgDir, false, false)

	answers := []string{
		// Regions
		"invalid input",
		"aws-us-west-2a,aws-eu-west-1a",

		// Node count: qrs
		"invalid input",
		"4",

		// Node resources: qrs
		"invalid input",
		"auto",

		// Node count: music
		"invalid input",
		"6",

		// Node resources: music
		"invalid input",
		"vcpu=16,memory=64Gb,disk=100Gb",
	}
	var buf bytes.Buffer
	buf.WriteString(strings.Join(answers, "\n") + "\n")

	cli, _, _ := newTestCLI(t)
	cli.Stdin = &buf
	assert.Nil(t, cli.Run("config", "set", "target", "cloud"))
	assert.Nil(t, cli.Run("config", "set", "application", "foo.bar"))
	assert.Nil(t, cli.Run("auth", "api-key"))
	assert.Nil(t, cli.Run("prod", "init", pkgDir))

	// Verify contents
	deploymentPath := filepath.Join(pkgDir, "deployment.xml")
	deploymentXML := readFileString(t, deploymentPath)
	assert.Contains(t, deploymentXML, `<region>aws-us-west-2a</region>`)
	assert.Contains(t, deploymentXML, `<region>aws-eu-west-1a</region>`)

	servicesPath := filepath.Join(pkgDir, "services.xml")
	servicesXML := readFileString(t, servicesPath)
	containerFragment := `<container id="qrs" version="1.0">
    <document-api></document-api>
    <search></search>
    <nodes count="4"></nodes>
  </container>`
	assert.Contains(t, servicesXML, containerFragment)
	contentFragment := `<content id="music" version="1.0">
    <redundancy>2</redundancy>
    <documents>
      <document type="music" mode="index"></document>
    </documents>
    <nodes count="6">
      <resources vcpu="16" memory="64Gb" disk="100Gb"></resources>
    </nodes>
  </content>`
	assert.Contains(t, servicesXML, contentFragment)

	// Backups are created
	assert.True(t, util.PathExists(deploymentPath+".1.bak"))
	assert.True(t, util.PathExists(servicesPath+".1.bak"))
}

func readFileString(t *testing.T, filename string) string {
	t.Helper()
	content, err := os.ReadFile(filename)
	if err != nil {
		t.Fatal(err)
	}
	return string(content)
}

func createApplication(t *testing.T, pkgDir string, java bool, skipTests bool) {
	appDir := pkgDir
	testsDir := pkgDir
	if java {
		appDir = filepath.Join(pkgDir, "target", "application")
		testsDir = filepath.Join(pkgDir, "target", "application-test")
	}
	if err := os.MkdirAll(appDir, 0755); err != nil {
		t.Fatal(err)
	}
	deploymentXML := `<deployment version="1.0">
  <prod>
    <region>aws-us-east-1c</region>
  </prod>
</deployment>`
	if err := os.WriteFile(filepath.Join(appDir, "deployment.xml"), []byte(deploymentXML), 0644); err != nil {
		t.Fatal(err)
	}
	servicesXML := `<services version="1.0" xmlns:deploy="vespa" xmlns:preprocess="properties">
  <container id="qrs" version="1.0">
    <document-api/>
    <search/>
    <nodes count="2">
      <resources vcpu="4" memory="8Gb" disk="100Gb"/>
    </nodes>
  </container>
  <content id="music" version="1.0">
    <redundancy>2</redundancy>
    <documents>
      <document type="music" mode="index"></document>
    </documents>
    <nodes count="4"></nodes>
  </content>
</services>`

	if err := os.WriteFile(filepath.Join(appDir, "services.xml"), []byte(servicesXML), 0644); err != nil {
		t.Fatal(err)
	}
	if java {
		if err := os.WriteFile(filepath.Join(pkgDir, "pom.xml"), []byte(""), 0644); err != nil {
			t.Fatal(err)
		}
	}
	if !skipTests {
		if err := os.MkdirAll(testsDir, 0755); err != nil {
			t.Fatal(err)
		}
		testBytes := []byte("{\"steps\":[{}]}")
		writeTest(filepath.Join(testsDir, "system-test", "test.json"), testBytes, t)
		writeTest(filepath.Join(testsDir, "staging-setup", "test.json"), testBytes, t)
		writeTest(filepath.Join(testsDir, "staging-test", "test.json"), testBytes, t)
	}
}

func writeTest(path string, content []byte, t *testing.T) {
	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(path, content, 0644); err != nil {
		t.Fatal(err)
	}
}

func TestProdDeploy(t *testing.T) {
	pkgDir := filepath.Join(t.TempDir(), "app")
	createApplication(t, pkgDir, false, false)
	prodDeploy(pkgDir, t)
}

func TestProdDeployWithoutTests(t *testing.T) {
	pkgDir := filepath.Join(t.TempDir(), "app")
	createApplication(t, pkgDir, false, true)
	prodDeploy(pkgDir, t)
}

func prodDeploy(pkgDir string, t *testing.T) {
	t.Helper()
	httpClient := &mock.HTTPClient{}
	httpClient.NextResponseString(200, `ok`)

	cli, stdout, _ := newTestCLI(t, "CI=true")
	cli.httpClient = httpClient
	app := vespa.ApplicationID{Tenant: "t1", Application: "a1", Instance: "i1"}
	assert.Nil(t, cli.Run("config", "set", "application", app.String()))
	assert.Nil(t, cli.Run("config", "set", "target", "cloud"))
	assert.Nil(t, cli.Run("auth", "api-key"))
	assert.Nil(t, cli.Run("auth", "cert", "--no-add"))

	// Zipping requires relative paths, so must let command run from pkgDir, then reset cwd for subsequent tests.
	if cwd, err := os.Getwd(); err != nil {
		t.Fatal(err)
	} else {
		defer os.Chdir(cwd)
	}
	if err := os.Chdir(pkgDir); err != nil {
		t.Fatal(err)
	}

	stdout.Reset()
	cli.Environment["VESPA_CLI_API_KEY_FILE"] = filepath.Join(cli.config.homeDir, "t1.api-key.pem")
	assert.Nil(t, cli.Run("prod", "deploy", "--add-cert"))
	assert.Contains(t, stdout.String(), "Success: Deployed")
	assert.Contains(t, stdout.String(), "See https://console.vespa-cloud.com/tenant/t1/application/a1/prod/deployment for deployment progress")
	stdout.Reset()
	assert.Nil(t, cli.Run("prod", "submit", "--add-cert")) // old variant also works
	assert.Contains(t, stdout.String(), "Success: Deployed")
	assert.Contains(t, stdout.String(), "See https://console.vespa-cloud.com/tenant/t1/application/a1/prod/deployment for deployment progress")
}

func TestProdDeployWithJava(t *testing.T) {
	pkgDir := filepath.Join(t.TempDir(), "app")
	createApplication(t, pkgDir, true, false)

	httpClient := &mock.HTTPClient{}
	httpClient.NextResponseString(200, `ok`)
	cli, stdout, stderr := newTestCLI(t, "CI=true")
	cli.httpClient = httpClient
	assert.Nil(t, cli.Run("config", "set", "application", "t1.a1.i1"))
	assert.Nil(t, cli.Run("config", "set", "target", "cloud"))
	assert.Nil(t, cli.Run("auth", "api-key"))
	assert.Nil(t, cli.Run("auth", "cert", "--no-add"))

	stdout.Reset()
	cli.Environment["VESPA_CLI_API_KEY_FILE"] = filepath.Join(cli.config.homeDir, "t1.api-key.pem")
	assert.Nil(t, cli.Run("prod", "deploy", "--add-cert", pkgDir))
	assert.Equal(t, "", stderr.String())
	assert.Contains(t, stdout.String(), "Success: Deployed")
	assert.Contains(t, stdout.String(), "See https://console.vespa-cloud.com/tenant/t1/application/a1/prod/deployment for deployment progress")
}

func TestProdDeployInvalidZip(t *testing.T) {
	pkgDir := filepath.Join(t.TempDir(), "app")
	createApplication(t, pkgDir, true, false)

	httpClient := &mock.HTTPClient{}
	httpClient.NextResponseString(200, `ok`)
	cli, _, stderr := newTestCLI(t, "CI=true")
	cli.httpClient = httpClient
	assert.Nil(t, cli.Run("config", "set", "application", "t1.a1.i1"))
	assert.Nil(t, cli.Run("config", "set", "target", "cloud"))
	assert.Nil(t, cli.Run("auth", "api-key"))
	assert.Nil(t, cli.Run("auth", "cert", "--no-add"))

	// Copy an invalid application package containing relative file names
	testAppDir := filepath.Join("testdata", "applications", "withInvalidEntries", "target")
	zipFile := filepath.Join(testAppDir, "application.zip")

	assert.NotNil(t, cli.Run("prod", "deploy", zipFile))
	assert.Equal(t, "Error: found invalid path inside zip: ../../../../../../../tmp/foo\n", stderr.String())
}

func copyFile(t *testing.T, dstFilename, srcFilename string) {
	dst, err := os.Create(dstFilename)
	if err != nil {
		t.Fatal(err)
	}
	defer dst.Close()
	src, err := os.Open(srcFilename)
	if err != nil {
		t.Fatal(err)
	}
	defer src.Close()
	if _, err := io.Copy(dst, src); err != nil {
		t.Fatal(err)
	}
}