-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrequests_test.go
653 lines (552 loc) · 16.3 KB
/
requests_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
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
package ctrl
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/fsnotify/fsnotify"
natsserver "github.com/nats-io/nats-server/v2/server"
)
var logging = flag.Bool("logging", false, "set to true to enable the normal logger of the package")
var persistTmp = flag.Bool("persistTmp", false, "set to true to persist the tmp folder")
var tstSrv *server
var tstConf *Configuration
var tstNats *natsserver.Server
var tstTempDir string
func TestMain(m *testing.M) {
flag.Parse()
if *persistTmp {
tstTempDir = "tmp"
} else {
tstTempDir = os.TempDir()
}
// NB: Forcing this for now.
tstTempDir = "tmp"
tstNats = newNatsServerForTesting(42222)
if err := natsserver.Run(tstNats); err != nil {
natsserver.PrintAndDie(err.Error())
}
tstSrv, tstConf = newServerForTesting("127.0.0.1:42222", tstTempDir)
tstSrv.Start()
exitCode := m.Run()
tstSrv.Stop()
tstNats.Shutdown()
os.Exit(exitCode)
}
func newServerForTesting(addressAndPort string, testFolder string) (*server, *Configuration) {
// Start ctrl instance
// ---------------------------------------
// tempdir := t.TempDir()
// Create the config to run a ctrl instance.
//tempdir := "./tmp"
conf := newConfigurationDefaults()
if *logging {
conf.LogLevel = "warning"
}
conf.BrokerAddress = addressAndPort
conf.NodeName = "central"
conf.CentralNodeName = "central"
conf.ConfigFolder = testFolder
conf.SubscribersDataFolder = testFolder
conf.SocketFolder = testFolder
conf.SubscribersDataFolder = testFolder
conf.DatabaseFolder = testFolder
conf.StartProcesses.IsCentralErrorLogger = true
conf.StartProcesses.IsCentralAcl = true
conf.LogLevel = "none"
ctrlServer, err := NewServer(&conf, "test")
if err != nil {
log.Fatalf(" * failed: could not start the ctrl instance %v\n", err)
}
return ctrlServer, &conf
}
// Start up the nats-server message broker for testing purposes.
func newNatsServerForTesting(port int) *natsserver.Server {
// Start up the nats-server message broker.
nsOpt := &natsserver.Options{
Host: "127.0.0.1",
Port: port,
JetStream: true,
}
ns, err := natsserver.NewServer(nsOpt)
if err != nil {
log.Fatalf(" * failed: could not start the nats-server %v\n", err)
}
return ns
}
// Write message to socket for testing purposes.
func writeMsgsToSocketTest(conf *Configuration, messages []Message, t *testing.T) {
js, err := json.Marshal(messages)
if err != nil {
t.Fatalf("writeMsgsToSocketTest: %v\n ", err)
}
socket, err := net.Dial("unix", filepath.Join(conf.SocketFolder, "ctrl.sock"))
if err != nil {
t.Fatalf(" * failed: could to open socket file for writing: %v\n", err)
}
defer socket.Close()
_, err = socket.Write(js)
if err != nil {
t.Fatalf(" * failed: could not write to socket: %v\n", err)
}
}
func TestRequest(t *testing.T) {
if !*logging {
log.SetOutput(io.Discard)
}
type containsOrEquals int
const (
REQTestContains containsOrEquals = iota
REQTestEquals containsOrEquals = iota
fileContains containsOrEquals = iota
)
type viaSocketOrCh int
const (
viaSocket viaSocketOrCh = iota
viaCh viaSocketOrCh = iota
)
type test struct {
info string
message Message
want []byte
containsOrEquals
viaSocketOrCh
}
// Web server for testing.
{
h := func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("web page content"))
}
http.HandleFunc("/", h)
go func() {
http.ListenAndServe(":10080", nil)
}()
}
tests := []test{
{
info: "hello test",
message: Message{
ToNode: "errorCentral",
FromNode: "errorCentral",
Method: ErrorLog,
MethodArgs: []string{},
MethodTimeout: 5,
Data: []byte("error data"),
// ReplyMethod: REQTest,
Directory: "error_log",
FileName: "error.results",
}, want: []byte("error data"),
containsOrEquals: fileContains,
viaSocketOrCh: viaCh,
},
{
info: "hello test",
message: Message{
ToNode: "central",
FromNode: "central",
Method: Hello,
MethodArgs: []string{},
MethodTimeout: 5,
// ReplyMethod: REQTest,
Directory: "test",
FileName: "hello.results",
}, want: []byte("Received hello from \"central\""),
containsOrEquals: fileContains,
viaSocketOrCh: viaCh,
},
{
info: "cliCommand test, echo gris",
message: Message{
ToNode: "central",
FromNode: "central",
Method: CliCommand,
MethodArgs: []string{"bash", "-c", "echo gris"},
MethodTimeout: 5,
ReplyMethod: Test,
}, want: []byte("gris"),
containsOrEquals: REQTestEquals,
viaSocketOrCh: viaCh,
},
{
info: "cliCommand test via socket, echo sau",
message: Message{
ToNode: "central",
FromNode: "central",
Method: CliCommand,
MethodArgs: []string{"bash", "-c", "echo sau"},
MethodTimeout: 5,
ReplyMethod: Test,
}, want: []byte("sau"),
containsOrEquals: REQTestEquals,
viaSocketOrCh: viaSocket,
},
{
info: "cliCommand test, echo sau, result in file",
message: Message{
ToNode: "central",
FromNode: "central",
Method: CliCommand,
MethodArgs: []string{"bash", "-c", "echo sau"},
MethodTimeout: 5,
ReplyMethod: File,
Directory: "test",
FileName: "file1.result",
}, want: []byte("sau"),
containsOrEquals: fileContains,
viaSocketOrCh: viaCh,
},
{
info: "cliCommand test, echo several, result in file continous",
message: Message{
ToNode: "central",
FromNode: "central",
Method: CliCommand,
MethodArgs: []string{"bash", "-c", "echo giraff && echo sau && echo apekatt"},
MethodTimeout: 5,
ReplyMethod: File,
Directory: "test",
FileName: "file2.result",
}, want: []byte("sau"),
containsOrEquals: fileContains,
viaSocketOrCh: viaCh,
},
{
info: "httpGet test, localhost:10080",
message: Message{
ToNode: "central",
FromNode: "central",
Method: HttpGet,
MethodArgs: []string{"http://localhost:10080"},
MethodTimeout: 5,
ReplyMethod: Test,
}, want: []byte("web page content"),
containsOrEquals: REQTestContains,
viaSocketOrCh: viaCh,
},
// TODO: Check out this one why it fails, and also why I'm checking for REQHttpGet here ??
//{
// info: "opProcessList test",
// message: Message{
// ToNode: "central",
// FromNode: "central",
// Method: REQOpProcessList,
// MethodArgs: []string{},
// MethodTimeout: 5,
// ReplyMethod: REQTest,
// }, want: []byte("central.REQHttpGet"),
// containsOrEquals: REQTestContains,
// viaSocketOrCh: viaCh,
//},
}
// Range over the tests defined, and execute them, one at a time.
for _, tt := range tests {
switch tt.viaSocketOrCh {
case viaCh:
tstSrv.newMessagesCh <- tt.message
case viaSocket:
msgs := []Message{tt.message}
writeMsgsToSocketTest(tstConf, msgs, t)
}
switch tt.containsOrEquals {
case REQTestEquals:
result := <-tstSrv.errorKernel.testCh
resStr := string(result)
resStr = strings.TrimSuffix(resStr, "\n")
result = []byte(resStr)
if !bytes.Equal(result, tt.want) {
t.Fatalf(" \U0001F631 [FAILED] :%v : want: %v, got: %v\n", tt.info, string(tt.want), string(result))
}
t.Logf(" \U0001f600 [SUCCESS] : %v\n", tt.info)
case REQTestContains:
result := <-tstSrv.errorKernel.testCh
resStr := string(result)
resStr = strings.TrimSuffix(resStr, "\n")
result = []byte(resStr)
if !strings.Contains(string(result), string(tt.want)) {
t.Fatalf(" \U0001F631 [FAILED] :%v : want: %v, got: %v\n", tt.info, string(tt.want), string(result))
}
t.Logf(" \U0001f600 [SUCCESS] : %v\n", tt.info)
case fileContains:
resultFile := filepath.Join(tstConf.SubscribersDataFolder, tt.message.Directory, string(tt.message.FromNode), tt.message.FileName)
found, err := findStringInFileTest(string(tt.want), resultFile)
if err != nil || found == false {
t.Fatalf(" \U0001F631 [FAILED] : %v: %v\n", tt.info, err)
}
t.Logf(" \U0001f600 [SUCCESS] : %v\n", tt.info)
}
}
// --- Other REQ tests that does not fit well into the general table above.
checkREQTailFileTest(tstConf, t, tstTempDir)
checkMetricValuesTest(tstSrv, t)
checkErrorKernelMalformedJSONtest(tstConf, t)
t.Log("*******starting with checkREQCopySrc\n")
checkREQCopySrc(tstConf, t, tstTempDir)
}
// Check the tailing of files type.
func checkREQTailFileTest(conf *Configuration, t *testing.T, tmpDir string) error {
// Create a file with some content.
fp := filepath.Join(tmpDir, "test.file")
fh, err := os.OpenFile(fp, os.O_APPEND|os.O_RDWR|os.O_CREATE|os.O_SYNC, 0660)
if err != nil {
return fmt.Errorf(" * failed: unable to open temporary file: %v", err)
}
defer fh.Close()
ctx, cancel := context.WithCancel(context.Background())
// Write content to the file with specified intervals.
go func() {
for i := 1; i <= 10; i++ {
_, err = fh.Write([]byte("some file content\n"))
if err != nil {
fmt.Printf(" * failed: writing to temporary file: %v\n", err)
}
fh.Sync()
time.Sleep(time.Millisecond * 500)
// Check if we've received a done, else default to continuing.
select {
case <-ctx.Done():
return
default:
// no done received, we're continuing.
}
}
}()
s := `[
{
"directory": "tail-files",
"fileName": "fileName.result",
"toNode": "central",
"methodArgs": ["` + fp + `"],
"method":"tailFile",
"ACKTimeout":5,
"retries":3,
"methodTimeout": 10
}
]`
writeToSocketTest(conf, s, t)
resultFile := filepath.Join(conf.SubscribersDataFolder, "tail-files", "central", "fileName.result")
// Wait n times for result file to be created.
n := 50
for i := 0; i <= n; i++ {
_, err := os.Stat(resultFile)
if os.IsNotExist(err) {
time.Sleep(time.Millisecond * 100)
continue
}
if os.IsNotExist(err) && i >= n {
cancel()
return fmt.Errorf(" \U0001F631 [FAILED] : checkREQTailFileTest: no result file created for request within the given time")
}
}
cancel()
_, err = findStringInFileTest("some file content", resultFile)
if err != nil {
return fmt.Errorf(" \U0001F631 [FAILED] : checkREQTailFileTest: %v", err)
}
t.Logf(" \U0001f600 [SUCCESS] : checkREQTailFileTest\n")
return nil
}
// Check the file copier.
func checkREQCopySrc(conf *Configuration, t *testing.T, tmpDir string) error {
testFiles := 5
for i := 1; i <= testFiles; i++ {
// Create a file with some content.
srcFileName := fmt.Sprintf("copysrc%v.file", i)
srcfp := filepath.Join(tmpDir, srcFileName)
fh, err := os.OpenFile(srcfp, os.O_APPEND|os.O_RDWR|os.O_CREATE|os.O_SYNC, 0660)
if err != nil {
t.Fatalf(" \U0001F631 [FAILED] : checkREQCopySrc: unable to open temporary file: %v", err)
}
defer fh.Close()
// Write content to the file.
_, err = fh.Write([]byte("some file content\n"))
if err != nil {
t.Fatalf(" \U0001F631 [FAILED] : checkREQCopySrc: writing to temporary file: %v\n", err)
}
dstFileName := fmt.Sprintf("copydst%v.file", i)
dstfp := filepath.Join(tmpDir, dstFileName)
s := `[
{
"toNode": "central",
"method":"copySrc",
"methodArgs": ["` + srcfp + `","central","` + dstfp + `","20","10"],
"ACKTimeout":5,
"retries":3,
"methodTimeout": 10,
"fileName": "filecopy2.log"
}
]`
writeToSocketTest(conf, s, t)
// Wait n times for result file to be created.
n := 50
for i := 0; i <= n; i++ {
_, err := os.Stat(dstfp)
if os.IsNotExist(err) {
time.Sleep(time.Millisecond * 100)
continue
}
if os.IsNotExist(err) && i >= n {
t.Fatalf(" \U0001F631 [FAILED] : checkREQCopySrc: no result file created for request within the given time")
}
}
t.Logf(" \U0001f600 [SUCCESS] : src=%v, dst=%v", srcfp, dstfp)
}
return nil
}
func checkMetricValuesTest(ctrlServer *server, t *testing.T) error {
mfs, err := ctrlServer.metrics.promRegistry.Gather()
if err != nil {
return fmt.Errorf("error: promRegistry.gathering: %v", mfs)
}
if len(mfs) <= 0 {
return fmt.Errorf("error: promRegistry.gathering: did not find any metric families: %v", mfs)
}
found := false
for _, mf := range mfs {
if mf.GetName() == "ctrl_processes_total" {
found = true
m := mf.GetMetric()
if m[0].Gauge.GetValue() <= 0 {
return fmt.Errorf("error: promRegistry.gathering: did not find any running processes in metric for processes_total : %v", m[0].Gauge.GetValue())
}
}
}
if !found {
return fmt.Errorf("error: promRegistry.gathering: did not find specified metric processes_total")
}
t.Logf(" \U0001f600 [SUCCESS] : checkMetricValuesTest")
return nil
}
// Check errorKernel
func checkErrorKernelMalformedJSONtest(conf *Configuration, t *testing.T) error {
// JSON message with error, missing brace.
m := `[
{
"directory": "some dir",
"fileName":"someext",
"toNode": "somenode",
"data": ["some data"],
"method": "errorLog"
missing brace here.....
]`
writeToSocketTest(conf, m, t)
resultFile := filepath.Join(conf.SubscribersDataFolder, "errorLog", "errorCentral", "error.log")
// Wait n times for error file to be created.
n := 50
for i := 0; i <= n; i++ {
_, err := os.Stat(resultFile)
if os.IsNotExist(err) {
time.Sleep(time.Millisecond * 100)
continue
}
if os.IsNotExist(err) && i >= n {
return fmt.Errorf(" \U0001F631 [FAILED] : checkErrorKernelMalformedJSONtest: no result file created for request within the given time")
}
}
// Start checking if the result file is being updated.
chUpdated := make(chan bool)
go checkFileUpdated(resultFile, chUpdated)
// We wait 5 seconds for an update, or else we fail.
ticker := time.NewTicker(time.Second * 5)
for {
select {
case <-chUpdated:
// We got an update, so we continue to check if we find the string we're
// looking for.
found, err := findStringInFileTest("error: malformed json", resultFile)
if !found && err != nil {
return fmt.Errorf(" \U0001F631 [FAILED] : checkErrorKernelMalformedJSONtest: %v", err)
}
if !found && err == nil {
continue
}
if found {
t.Logf(" \U0001f600 [SUCCESS] : checkErrorKernelMalformedJSONtest")
return nil
}
case <-ticker.C:
return fmt.Errorf(" * failed: did not get an update in the errorKernel log file")
}
}
}
// Check if file are getting updated with new content.
func checkFileUpdated(fileRealPath string, fileUpdated chan bool) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Println("Failed fsnotify.NewWatcher")
return
}
defer watcher.Close()
done := make(chan bool)
go func() {
//Give a true value to updated so it reads the file the first time.
fileUpdated <- true
for {
select {
case event := <-watcher.Events:
log.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
log.Println("modified file:", event.Name)
//testing with an update chan to get updates
fileUpdated <- true
}
case err := <-watcher.Errors:
log.Println("error:", err)
}
}
}()
err = watcher.Add(fileRealPath)
if err != nil {
log.Fatal(err)
}
<-done
}
// Check if a file contains the given string.
func findStringInFileTest(want string, fileName string) (bool, error) {
// Wait n seconds for the results file to be created
n := 50
for i := 0; i <= n; i++ {
_, err := os.Stat(fileName)
if os.IsNotExist(err) {
time.Sleep(time.Millisecond * 100)
continue
}
if os.IsNotExist(err) && i >= n {
return false, fmt.Errorf(" * failed: no result file created for request within the given time\n")
}
}
fh, err := os.Open(fileName)
if err != nil {
return false, fmt.Errorf(" * failed: could not open result file: %v", err)
}
result, err := io.ReadAll(fh)
if err != nil {
return false, fmt.Errorf(" * failed: could not read result file: %v", err)
}
found := strings.Contains(string(result), want)
if !found {
return false, nil
}
return true, nil
}
// Write message to socket for testing purposes.
func writeToSocketTest(conf *Configuration, messageText string, t *testing.T) {
socket, err := net.Dial("unix", filepath.Join(conf.SocketFolder, "ctrl.sock"))
if err != nil {
t.Fatalf(" * failed: could to open socket file for writing: %v\n", err)
}
defer socket.Close()
_, err = socket.Write([]byte(messageText))
if err != nil {
t.Fatalf(" * failed: could not write to socket: %v\n", err)
}
}