aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/internal/vespa/target_test.go
blob: 68b60774c945979c3eae74d140f049a8e1fa5240 (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
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package vespa

import (
	"bytes"
	"io"
	"net/http"
	"strings"
	"testing"
	"time"

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

func TestLocalTarget(t *testing.T) {
	// Local target uses discovery
	client := &mock.HTTPClient{}
	lt := LocalTarget(client, TLSOptions{}, 0)
	assertServiceURL(t, "http://127.0.0.1:19071", lt, "deploy")
	for i := 0; i < 2; i++ {
		response := `
{
  "services": [
    {
      "host": "foo",
      "port": 8080,
      "type": "container",
      "url": "http://localhost:19071/application/v2/tenant/default/application/default/environment/prod/region/default/instance/default/serviceconverge/localhost:8080",
      "currentGeneration": 1
    },
    {
      "host": "bar",
      "port": 8080,
      "type": "container",
      "url": "http://localhost:19071/application/v2/tenant/default/application/default/environment/prod/region/default/instance/default/serviceconverge/localhost:8080",
      "currentGeneration": 1
    },
    {
      "clusterName": "feed",
      "host": "localhost",
      "port": 8081,
      "type": "container",
      "url": "http://localhost:19071/application/v2/tenant/default/application/default/environment/prod/region/default/instance/default/serviceconverge/localhost:8081",
      "currentGeneration": 1
    },
    {
      "host": "localhost",
      "port": 19112,
      "type": "searchnode",
      "url": "http://localhost:19071/application/v2/tenant/default/application/default/environment/prod/region/default/instance/default/serviceconverge/localhost:19112",
      "currentGeneration": 1
    }
  ],
  "currentGeneration": 1
}`
		client.NextResponse(mock.HTTPResponse{
			URI:    "/application/v2/tenant/default/application/default/environment/prod/region/default/instance/default/serviceconverge",
			Status: 200,
			Body:   []byte(response),
		})
	}
	assertServiceURL(t, "http://127.0.0.1:8080", lt, "container8080")
	assertServiceURL(t, "http://127.0.0.1:8081", lt, "feed")
}

func TestCustomTarget(t *testing.T) {
	// Custom target always uses URL directly, without discovery
	ct := CustomTarget(&mock.HTTPClient{}, "http://192.0.2.42", TLSOptions{}, 0)
	assertServiceURL(t, "http://192.0.2.42", ct, "deploy")
	assertServiceURL(t, "http://192.0.2.42", ct, "")
	ct2 := CustomTarget(&mock.HTTPClient{}, "http://192.0.2.42:60000", TLSOptions{}, 0)
	assertServiceURL(t, "http://192.0.2.42:60000", ct2, "deploy")
	assertServiceURL(t, "http://192.0.2.42:60000", ct2, "")
}

func TestCustomTargetWait(t *testing.T) {
	client := &mock.HTTPClient{}
	target := CustomTarget(client, "http://192.0.2.42", TLSOptions{}, 0)
	// Fails once
	client.NextStatus(500)
	assertService(t, true, target, "", 0)
	// Fails multiple times
	for i := 0; i < 3; i++ {
		client.NextStatus(500)
		client.NextResponseError(io.EOF)
	}
	// Then succeeds
	client.NextResponse(mock.HTTPResponse{URI: "/ApplicationStatus", Status: 200})
	assertService(t, false, target, "", time.Second)
}

func TestCustomTargetAwaitDeployment(t *testing.T) {
	client := &mock.HTTPClient{}
	target := CustomTarget(client, "http://192.0.2.42", TLSOptions{}, 0)

	// Not converged initially
	_, err := target.AwaitDeployment(42, 0)
	assert.NotNil(t, err)

	// Not converged on this generation
	response := mock.HTTPResponse{
		URI:    "/application/v2/tenant/default/application/default/environment/prod/region/default/instance/default/serviceconverge",
		Status: 200,
		Body:   []byte(`{"currentGeneration": 42}`),
	}
	client.NextResponse(response)
	_, err = target.AwaitDeployment(41, 0)
	assert.NotNil(t, err)

	// Converged
	client.NextResponse(response)
	convergedID, err := target.AwaitDeployment(42, 0)
	assert.Nil(t, err)
	assert.Equal(t, int64(42), convergedID)
}

func TestCloudTargetWait(t *testing.T) {
	var logWriter bytes.Buffer
	target, client := createCloudTarget(t, &logWriter)
	client.NextStatus(401)
	assertService(t, true, target, "deploy", time.Second) // No retrying on 4xx
	client.NextStatus(500)
	client.NextStatus(500)
	client.NextResponse(mock.HTTPResponse{URI: "/status.html", Status: 200})
	assertService(t, false, target, "deploy", time.Second)

	client.NextResponse(mock.HTTPResponse{
		URI:    "/application/v4/tenant/t1/application/a1/instance/i1/environment/dev/region/us-north-1",
		Status: 200,
		Body:   []byte(`{"endpoints":[]}`),
	})
	_, err := target.ContainerServices(time.Millisecond)
	assert.NotNil(t, err)

	response := mock.HTTPResponse{
		URI:    "/application/v4/tenant/t1/application/a1/instance/i1/environment/dev/region/us-north-1",
		Status: 200,
		Body: []byte(`{
  "endpoints": [
    {"url": "http://a.example.com","scope": "zone", "cluster": "default"},
    {"url": "http://b.example.com","scope": "zone", "cluster": "feed"}
  ]
}`),
	}
	client.NextResponse(response)
	services, err := target.ContainerServices(time.Millisecond)
	assert.Nil(t, err)
	assert.Equal(t, 2, len(services))

	client.NextResponse(response)
	client.NextResponse(mock.HTTPResponse{URI: "/ApplicationStatus", Status: 500})
	assertService(t, true, target, "default", 0)
	client.NextResponse(response)
	client.NextResponse(mock.HTTPResponse{URI: "/ApplicationStatus", Status: 200})
	assertService(t, false, target, "feed", 0)
}

func TestCloudTargetAwaitDeployment(t *testing.T) {
	var logWriter bytes.Buffer
	target, client := createCloudTarget(t, &logWriter)

	runningResponse := mock.HTTPResponse{
		URI:    "/application/v4/tenant/t1/application/a1/instance/i1/job/dev-us-north-1/run/42?after=-1",
		Status: 200,
		Body: []byte(`{"active": true, "status": "running",
                       "lastId": 42,
                       "log": {"deployReal": [{"at": 1631707708431,
                                               "type": "info",
                                                "message": "Deploying platform version 7.465.17 and application version 1.0.2 ..."}]}}`),
	}
	client.NextResponse(runningResponse)
	runningResponse.URI = "/application/v4/tenant/t1/application/a1/instance/i1/job/dev-us-north-1/run/42?after=42"
	client.NextResponse(runningResponse)
	// Deployment has not succeeded yet
	_, err := target.AwaitDeployment(int64(42), time.Second)
	assert.NotNil(t, err)

	// Log timestamp is converted to local time, do the same here in case the local time where tests are run varies
	tm := time.Unix(1631707708, 431000)
	expectedTime := tm.Format("[15:04:05]")
	assert.Equal(t, strings.Repeat(expectedTime+" info    Deploying platform version 7.465.17 and application version 1.0.2 ...\n", 2), logWriter.String())

	// Wanted deployment run eventually succeeds
	runningResponse.URI = "/application/v4/tenant/t1/application/a1/instance/i1/job/dev-us-north-1/run/42?after=-1"
	client.NextResponse(runningResponse)
	client.NextResponse(mock.HTTPResponse{
		URI:    "/application/v4/tenant/t1/application/a1/instance/i1/job/dev-us-north-1/run/42?after=42",
		Status: 200,
		Body:   []byte(`{"active": false, "status": "success"}`),
	})
	convergedID, err := target.AwaitDeployment(int64(42), time.Second)
	assert.Nil(t, err)
	assert.Equal(t, int64(42), convergedID)

	// Await latest deployment
	client.NextResponse(mock.HTTPResponse{
		URI:    "/application/v4/tenant/t1/application/a1/instance/i1/job/dev-us-north-1?limit=1",
		Status: 200,
		Body:   []byte(`{"runs": [{"id": 1337}]}`),
	})
	client.NextResponse(mock.HTTPResponse{
		URI:    "/application/v4/tenant/t1/application/a1/instance/i1/job/dev-us-north-1/run/1337?after=-1",
		Status: 200,
		Body:   []byte(`{"active": false, "status": "success"}`),
	})
	convergedID, err = target.AwaitDeployment(LatestDeployment, time.Second)
	assert.Nil(t, err)
	assert.Equal(t, int64(1337), convergedID)
}

func TestLog(t *testing.T) {
	target, client := createCloudTarget(t, io.Discard)
	client.NextResponse(mock.HTTPResponse{
		URI:    "/application/v4/tenant/t1/application/a1/instance/i1/environment/dev/region/us-north-1/logs?from=-62135596800000",
		Status: 200,
		Body: []byte(`1632738690.905535	host1a.dev.aws-us-east-1c	806/53	logserver-container	Container.com.yahoo.container.jdisc.ConfiguredApplication	info	Switching to the latest deployed set of configurations and components. Application config generation: 52532
1632738698.600189	host1a.dev.aws-us-east-1c	1723/33590	config-sentinel	sentinel.sentinel.config-owner	config	Sentinel got 3 service elements [tenant(vespa-team), application(music), instance(mpolden)] for config generation 52532
`),
	})
	var buf bytes.Buffer
	if err := target.PrintLog(LogOptions{Writer: &buf, Level: 3}); err != nil {
		t.Fatal(err)
	}
	expected := "[2021-09-27 10:31:30.905535] host1a.dev.aws-us-east-1c info    logserver-container Container.com.yahoo.container.jdisc.ConfiguredApplication\tSwitching to the latest deployed set of configurations and components. Application config generation: 52532\n" +
		"[2021-09-27 10:31:38.600189] host1a.dev.aws-us-east-1c config  config-sentinel  sentinel.sentinel.config-owner\tSentinel got 3 service elements [tenant(vespa-team), application(music), instance(mpolden)] for config generation 52532\n"
	assert.Equal(t, expected, buf.String())
}

func TestCheckVersion(t *testing.T) {
	target, client := createCloudTarget(t, io.Discard)
	for i := 0; i < 3; i++ {
		client.NextResponse(mock.HTTPResponse{URI: "/cli/v1/", Status: 200, Body: []byte(`{"minVersion":"8.0.0"}`)})
	}
	assert.Nil(t, target.CheckVersion(version.MustParse("8.0.0")))
	assert.Nil(t, target.CheckVersion(version.MustParse("8.1.0")))
	assert.NotNil(t, target.CheckVersion(version.MustParse("7.0.0")))
}

func createCloudTarget(t *testing.T, logWriter io.Writer) (Target, *mock.HTTPClient) {
	apiKey, err := CreateAPIKey()
	require.Nil(t, err)
	auth := &mockAuthenticator{}
	client := &mock.HTTPClient{}
	target, err := CloudTarget(
		client,
		auth,
		auth,
		APIOptions{APIKey: apiKey, System: PublicSystem},
		CloudDeploymentOptions{
			Deployment: Deployment{
				Application: ApplicationID{Tenant: "t1", Application: "a1", Instance: "i1"},
				Zone:        ZoneID{Environment: "dev", Region: "us-north-1"},
				System:      PublicSystem,
			},
		},
		LogOptions{Writer: logWriter},
		0,
	)
	require.Nil(t, err)
	return target, client
}

func getService(t *testing.T, target Target, name string) (*Service, error) {
	t.Helper()
	if name == "deploy" {
		return target.DeployService()
	}
	services, err := target.ContainerServices(0)
	require.Nil(t, err)
	return FindService(name, services)
}

func assertServiceURL(t *testing.T, url string, target Target, serviceName string) {
	t.Helper()
	service, err := getService(t, target, serviceName)
	require.Nil(t, err)
	assert.Equal(t, url, service.BaseURL)
}

func assertService(t *testing.T, fail bool, target Target, serviceName string, timeout time.Duration) {
	t.Helper()
	service, err := getService(t, target, serviceName)
	require.Nil(t, err)
	err = service.Wait(timeout)
	if fail {
		assert.NotNil(t, err)
	} else {
		assert.Nil(t, err)
	}
}

type mockAuthenticator struct{}

func (a *mockAuthenticator) Authenticate(request *http.Request) error { return nil }