-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathrun_test.go
More file actions
547 lines (527 loc) · 15.2 KB
/
Copy pathrun_test.go
File metadata and controls
547 lines (527 loc) · 15.2 KB
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
// Copyright 2021 by Leipzig University Library, http://ub.uni-leipzig.de
// The Finc Authors, http://finc.info
// Martin Czygan, <martin.czygan@uni-leipzig.de>
//
// This file is part of some open source application.
//
// Some open source application is free software: you can redistribute
// it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// Some open source application is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Foobar. If not, see <http://www.gnu.org/licenses/>.
//
// @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>
package esbulk
import (
"context"
"fmt"
"io"
"io/ioutil"
"log"
"net/url"
"os"
"os/exec"
"os/user"
"strings"
"sync"
"testing"
"time"
"github.com/docker/docker/api/types/container"
"github.com/segmentio/encoding/json"
"github.com/sethgrid/pester"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
func TestIncompleteConfig(t *testing.T) {
skipNoDocker(t)
var cases = []struct {
help string
r Runner
err error
}{
{help: "no default index name", r: Runner{}, err: ErrNoWorkers},
{help: "no such host", r: Runner{
IndexName: "abc",
BatchSize: 10,
NumWorkers: 1,
Servers: []string{"http://broken.server:9200"},
}, err: &url.Error{Op: "Get", URL: "http://broken.server:9200/abc"}},
}
for _, c := range cases {
err := c.r.Run()
switch err.(type) {
case nil:
if c.err != nil {
t.Fatalf("got: %#v, %T, want: %v [%s]", err, err, c.err, c.help)
}
case *url.Error:
// For now, only check whether we expect an error.
if c.err == nil {
t.Fatalf("got: %#v, %T, want: %v [%s]", err, err, c.err, c.help)
}
default:
if err != c.err {
t.Fatalf("got: %#v, %T, want: %v [%s]", err, err, c.err, c.help)
}
}
}
}
// startServer starts an elasticsearch server from image, exposing the http
// port. Note that the Java heap required may be 2GB or more.
func startServer(ctx context.Context, image string, httpPort int) (testcontainers.Container, error) {
var (
hp = fmt.Sprintf("%d:9200/tcp", httpPort)
parts = strings.Split(image, ":")
tag string
)
if len(parts) == 2 {
tag = parts[1]
} else {
tag = "latest"
}
var (
name = fmt.Sprintf("esbulk-test-es-%s-%d", tag, time.Now().UnixNano())
req = testcontainers.ContainerRequest{
Image: image,
Name: name,
Env: map[string]string{
"discovery.type": "single-node",
// If you’re starting a single-node Elasticsearch cluster in a
// Docker container, security will be automatically enabled and
// configured for you. -- https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html#docker-cli-run-dev-mode
"xpack.security.enabled": "false",
"ES_JAVA_OPTS": "-Xms4g -Xmx4g",
},
ExposedPorts: []string{hp},
WaitingFor: wait.ForLog("started"),
// $ docker run --platform linux/amd64 m 8g -e ES_JAVA_OPTS="-Xms512m -Xmx512m" elasticsearch:2.3.4
// library initialization failed - unable to allocate file descriptor table - out of memory#
HostConfigModifier: func(hc *container.HostConfig) {
hc.CgroupnsMode = container.CgroupnsModeHost
hc.Resources = container.Resources{
Ulimits: []*container.Ulimit{{
Name: "nofile",
Hard: 65536,
Soft: 65536,
}},
}
},
}
)
return testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ProviderType: testcontainers.ProviderDefault,
ContainerRequest: req,
Started: true,
})
}
// logReader reads data from reader and bot logs it and returns it. Fails, if
// reading fails.
func logReader(t *testing.T, r io.Reader) []byte {
b, err := ioutil.ReadAll(r)
if err != nil {
t.Fatalf("read failed: %s", err)
return nil
}
t.Logf("%s", string(b))
return b
}
// skipNoDocker skips a test, if docker is not running. Also support podman.
func skipNoDocker(t *testing.T) {
noDocker := false
cmd := exec.Command("systemctl", "is-active", "docker")
b, err := cmd.CombinedOutput()
if err != nil {
noDocker = true
}
if strings.TrimSpace(string(b)) != "active" {
noDocker = true
}
if !noDocker {
// We found some docker.
return
}
// Otherwise, try podman.
_, err = exec.LookPath("podman")
if err == nil {
t.Logf("podman detected")
// DOCKER_HOST=unix:///run/user/$UID/podman/podman.sock
usr, err := user.Current()
if err != nil {
t.Logf("cannot get UID, set DOCKER_HOST manually")
} else {
sckt := fmt.Sprintf("unix:///run/user/%v/podman/podman.sock", usr.Uid)
os.Setenv("DOCKER_HOST", sckt)
t.Logf("set DOCKER_HOST to %v", sckt)
}
noDocker = false
}
if noDocker {
t.Skipf("docker not installed or not running")
}
}
func TestMinimalConfig(t *testing.T) {
skipNoDocker(t)
ctx := context.Background()
var imageConf = []struct {
ElasticsearchMajorVersion int
Image string
HttpPort int
}{
// $ docker pull elasticsearch:2.3.4
// 2.3.4: Pulling from library/elasticsearch
// ca69fe441e9d: Already exists
// failed to unpack image on snapshotter overlayfs: apply layer error
// for "docker.io/library/elasticsearch:2.3.4": failed to extract layer
// sha256:2f71b45e4e254ddceb187b1467f5471f0e14d7124ac2dd7fdd7ddbc76e13f0e5:
// NotFound: failed to get reader from content store: content digest
// sha256:357ea8c3d80bc25792e010facfc98aee5972ebc47e290eb0d5aea3671a901cab:
// not found
// {2, "elasticsearch:2.3.4", 39200},
{5, "elasticsearch:5.6.16", 39200},
{6, "elasticsearch:6.8.14", 39200},
{7, "elasticsearch:7.17.7", 39200}, // https://is.gd/MPwhaM, https://is.gd/RJ4LOZ, ...
{8, "elasticsearch:8.6.0", 39200},
}
log.Printf("testing %d versions: %v", len(imageConf), imageConf)
for _, conf := range imageConf {
wrapper := func() error {
c, err := startServer(ctx, conf.Image, conf.HttpPort)
if err != nil {
t.Fatalf("could not start test container for %v: %v", conf.Image, err)
}
defer func() {
if err := c.Terminate(ctx); err != nil {
t.Errorf("could not kill container: %v", err)
}
}()
base := fmt.Sprintf("http://localhost:%d", conf.HttpPort)
resp, err := pester.Get(base)
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
logReader(t, resp.Body)
t.Logf("server should be up at %s", base)
var cases = []struct {
filename string
indexName string
numDocs int64
err error
}{
{"fixtures/v10k.jsonl", "abc", 10000, nil},
}
for _, c := range cases {
f, err := os.Open(c.filename)
if err != nil {
return fmt.Errorf("could not open fixture: %s", c.filename)
}
defer f.Close()
r := Runner{
Servers: []string{"http://localhost:39200"},
BatchSize: 5000,
NumWorkers: 1,
RefreshInterval: "1s",
IndexName: "abc",
File: f,
Verbose: true,
}
if conf.ElasticsearchMajorVersion < 7 {
r.DocType = "any" // deprecated with ES7, fails with ES8
}
err = r.Run()
if err != c.err {
return fmt.Errorf("got %v, want %v", err, c.err)
}
searchURL := fmt.Sprintf("%s/%s/_search", base, r.IndexName)
resp, err = pester.Get(searchURL)
if err != nil {
return fmt.Errorf("could not query es: %v", err)
}
defer resp.Body.Close()
b := logReader(t, resp.Body)
var (
sr7 SearchResponse7
sr6 SearchResponse6
)
if err = json.Unmarshal(b, &sr7); err != nil {
if err = json.Unmarshal(b, &sr6); err != nil {
t.Errorf("could not parse json response (6, 7): %v", err)
} else {
t.Log("es6 detected")
}
}
if sr7.Hits.Total.Value != c.numDocs && sr6.Hits.Total != c.numDocs {
t.Errorf("expected %d docs", c.numDocs)
}
}
// Save logs.
rc, err := c.Logs(ctx)
if err != nil {
log.Printf("logs not available: %v", err)
}
if err := os.MkdirAll("logs", 0755); err != nil {
if !os.IsExist(err) {
log.Printf("create dir failed: %v", err)
}
}
cname, err := c.Name(ctx)
if err != nil {
t.Logf("failed to get container name: %v", err)
}
fn := fmt.Sprintf("logs/%s-%s.log", time.Now().Format("20060102150405"), strings.TrimLeft(cname, "/"))
f, err := os.Create(fn)
if err != nil {
log.Printf("failed to create log file: %v", err)
}
defer f.Close()
log.Printf("logging to %s", fn)
if _, err := io.Copy(f, rc); err != nil {
log.Printf("log failed: %v", err)
}
return nil
}
if err := wrapper(); err != nil {
t.Fatal(err)
}
}
}
func TestGH32(t *testing.T) {
skipNoDocker(t)
ctx := context.Background()
// 7.17.7 bundles a Java version, that has improved cgroups2 support
c, err := startServer(ctx, "elasticsearch:7.17.7", 39200)
if err != nil {
t.Fatalf("could not start test container: %v", err)
}
defer func() {
if err := c.Terminate(ctx); err != nil {
t.Errorf("could not kill container: %v", err)
}
}()
base := fmt.Sprintf("http://localhost:%d", 39200)
resp, err := pester.Get(base)
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
logReader(t, resp.Body)
t.Logf("server should be up at %s", base)
f, err := os.Open("fixtures/v10k.jsonl")
if err != nil {
t.Errorf("could not open fixture: %v", err)
}
defer f.Close()
r := Runner{
Servers: []string{"http://localhost:39200"},
BatchSize: 5000,
NumWorkers: 1,
RefreshInterval: "1s",
Mapping: `{}`,
IndexName: "abc",
DocType: "any", // deprecated with ES7
File: f,
Verbose: true,
}
// this should fail with #32
err = r.Run()
if err != nil {
t.Logf("expected err: %v", err)
} else {
t.Fatalf("expected fail, see #32")
}
// w/o doctype, we should be good
r = Runner{
Servers: []string{"http://localhost:39200"},
BatchSize: 5000,
NumWorkers: 1,
RefreshInterval: "1s",
Mapping: `{}`,
IndexName: "abc",
File: f,
Verbose: true,
}
err = r.Run()
if err != nil {
t.Fatalf("unexpected failure: %v", err)
}
}
type SearchResponse6 struct {
Hits struct {
Hits []struct {
Id string `json:"_id"`
Index string `json:"_index"`
Score float64 `json:"_score"`
Source struct {
V string `json:"v"`
} `json:"_source"`
Type string `json:"_type"`
} `json:"hits"`
MaxScore float64 `json:"max_score"`
Total int64 `json:"total"`
} `json:"hits"`
Shards struct {
Failed int64 `json:"failed"`
Skipped int64 `json:"skipped"`
Successful int64 `json:"successful"`
Total int64 `json:"total"`
} `json:"_shards"`
TimedOut bool `json:"timed_out"`
Took int64 `json:"took"`
}
type SearchResponse7 struct {
Hits struct {
Hits []struct {
Id string `json:"_id"`
Index string `json:"_index"`
Score float64 `json:"_score"`
Source struct {
V string `json:"v"`
} `json:"_source"`
Type string `json:"_type"`
} `json:"hits"`
MaxScore float64 `json:"max_score"`
Total struct {
Relation string `json:"relation"`
Value int64 `json:"value"`
} `json:"total"`
} `json:"hits"`
Shards struct {
Failed int64 `json:"failed"`
Skipped int64 `json:"skipped"`
Successful int64 `json:"successful"`
Total int64 `json:"total"`
} `json:"_shards"`
TimedOut bool `json:"timed_out"`
Took int64 `json:"took"`
}
func TestContextCancellation(t *testing.T) {
tests := []struct {
name string
cancelDelay time.Duration
expectError bool
}{
{"early cancellation", 10 * time.Millisecond, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if tt.cancelDelay > 0 {
time.AfterFunc(tt.cancelDelay, cancel)
}
options := Options{
BatchSize: 10,
Verbose: false, // Reduce noise in test output
Servers: []string{"http://localhost:9200"},
Index: "test-index",
RequestTimeout: 5 * time.Second,
}
var (
lines = make(chan string, 100)
errChan = make(chan error, 1)
wg sync.WaitGroup
)
wg.Add(1)
for i := 0; i < 5; i++ {
lines <- `{"test": "data"}`
}
close(lines)
err := Worker(ctx, "test-worker", options, lines, &wg, errChan)
if tt.expectError {
select {
case <-ctx.Done():
t.Logf("Context cancelled as expected: %v", ctx.Err())
case err := <-errChan:
// May get connection errors, which is ok when context is cancelled
t.Logf("worker error (expected): %v", err)
case <-time.After(200 * time.Millisecond):
t.Error("expected context cancellation but worker didn't finish")
}
} else {
if err != nil {
t.Errorf("worker failed unexpectedly: %v", err)
}
}
})
}
}
func TestWorkerRespectsImmediateCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
options := Options{
BatchSize: 10,
Verbose: false,
Servers: []string{"http://localhost:9200"},
Index: "test-index",
RequestTimeout: 30 * time.Second,
}
var (
lines = make(chan string, 100)
errChan = make(chan error, 1)
)
var wg sync.WaitGroup
wg.Add(1)
var (
start = time.Now()
err = Worker(ctx, "test-worker", options, lines, &wg, errChan)
)
elapsed := time.Since(start)
if elapsed > 100*time.Millisecond {
t.Errorf("worker should return immediately when context is cancelled, but took %v", elapsed)
}
if err != nil {
t.Errorf("unexpected error: %v", err)
}
}
func TestCreateHTTPRequestWithContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
options := Options{
Username: "testuser",
Password: "testpass",
}
req, err := CreateHTTPRequestWithContext(ctx, "GET", "http://example.com", nil, options)
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
if req.Method != "GET" {
t.Errorf("expected method GET, got %s", req.Method)
}
if req.URL.String() != "http://example.com" {
t.Errorf("expected URL http://example.com, got %s", req.URL.String())
}
username, password, ok := req.BasicAuth()
if !ok {
t.Error("expected basic auth to be set")
}
if username != "testuser" || password != "testpass" {
t.Errorf("expected basic auth user:testuser pass:testpass, got %s:%s", username, password)
}
}
func TestCreateHTTPClientWithTimeout(t *testing.T) {
tests := []struct {
name string
insecureSkip bool
timeout time.Duration
expectedTimeout time.Duration
}{
{"default timeout", false, 0, 30 * time.Second},
{"custom timeout", false, 45 * time.Second, 45 * time.Second},
{"insecure with timeout", true, 60 * time.Second, 60 * time.Second},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := CreateHTTPClient(tt.insecureSkip, tt.timeout)
if client.Timeout != tt.expectedTimeout {
t.Errorf("expected timeout %v, got %v", tt.expectedTimeout, client.Timeout)
}
})
}
}