-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathintegration_test.go
More file actions
2245 lines (1939 loc) · 72.4 KB
/
Copy pathintegration_test.go
File metadata and controls
2245 lines (1939 loc) · 72.4 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
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"context"
"database/sql"
"fmt"
"io"
"net"
"os"
"os/exec"
"regexp"
"strings"
"sync"
"testing"
"time"
_ "github.com/lib/pq"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Debug configuration
var debugMode = os.Getenv("DEBUG") != ""
// Debug logging helper
func logDebug(t *testing.T, format string, args ...interface{}) {
if debugMode {
t.Logf("DEBUG: "+format, args...)
}
}
// loadTestEnvironment loads environment variables from .env.test
func loadTestEnvironment(t *testing.T) {
envFile := ".env.test"
if _, err := os.Stat(envFile); os.IsNotExist(err) {
t.Logf("Warning: %s file not found, using defaults", envFile)
return
}
file, err := os.Open(envFile)
if err != nil {
t.Logf("Warning: Failed to open %s: %v", envFile, err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) == 2 {
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
// Remove quotes if present
if len(value) >= 2 && ((value[0] == '"' && value[len(value)-1] == '"') || (value[0] == '\'' && value[len(value)-1] == '\'')) {
value = value[1 : len(value)-1]
}
os.Setenv(key, value)
}
}
if err := scanner.Err(); err != nil {
t.Logf("Warning: Error reading %s: %v", envFile, err)
}
}
// getDBConnectionString builds database connection string from environment variables
func getDBConnectionString() string {
dbUser := os.Getenv("DBUSER")
if dbUser == "" {
dbUser = "postgres"
}
dbPass := os.Getenv("DBPASS")
if dbPass == "" {
dbPass = "postgres"
}
dbName := os.Getenv("DBNAME")
if dbName == "" {
dbName = "minexus"
}
dbPort := os.Getenv("DBPORT")
if dbPort == "" {
dbPort = "5432"
}
return fmt.Sprintf("postgres://%s:%s@localhost:%s/%s?sslmode=disable", dbUser, dbPass, dbPort, dbName)
}
// Test configuration
const (
dockerComposeFile = "docker-compose.yml"
consoleExecutable = "./console-test"
maxRetries = 15 // Reduced from 30 (race conditions are fixed)
retryInterval = 500 * time.Millisecond // Reduced from 1s
minionPort = 11972 // Standard TLS port for minions
consolePort = 11973 // mTLS port for console
)
// Integration Test Conditional Execution System
//
// This file contains integration tests that require external Docker services.
// To separate fast unit tests from slower integration tests, these tests only
// run when the SLOW_TESTS environment variable is set.
//
// Usage:
// make test - Unit tests only (fast, ~5s)
// SLOW_TESTS=1 make test - All tests including integration (~60s)
//
// The integration tests automatically:
// 1. Check if Docker Compose services are running
// 2. Start required services (nexus, minion, database) if needed
// 3. Wait for services to be ready with health checks
// 4. Build console executable if needed
// 5. Run comprehensive end-to-end tests
//
// Required Services:
// - nexus_db: PostgreSQL database
// - nexus: Nexus gRPC dual-port server (port 11972 for minions, 11973 for console)
// - minion_1: Test minion client
//
// Test Categories:
// - Console command testing (help, version, listings)
// - Shell command execution via minions
// - File operations on remote systems
// - System information gathering
// - Error handling and edge cases
// - Database integrity and consistency
// - mTLS console connection testing
// - Dual-port server functionality testing
// - Certificate validation testing
// - Mixed traffic scenarios (console + minion simultaneously)
// - Certificate edge cases and authentication failures
// TestResult represents the result of a command execution
type TestResult struct {
Command string
Expected bool // true if command should succeed
Output string
CommandID string
Error error
}
// IntegrationTestSuite contains all integration tests
func TestIntegrationSuite(t *testing.T) {
// Check if integration tests should run
if os.Getenv("SLOW_TESTS") == "" {
t.Skip("Skipping integration tests. Set SLOW_TESTS=1 to run integration tests.")
return
}
// Load test environment variables from .env.test
loadTestEnvironment(t)
startTime := time.Now()
t.Log("TIMING: Starting integration tests (SLOW_TESTS is set)")
// Setup: Ensure Docker services are running
setupStart := time.Now()
t.Log("TIMING: Starting Docker services setup...")
setupDockerServices(t)
setupDockerDuration := time.Since(setupStart)
t.Logf("TIMING: Docker setup completed in %v", setupDockerDuration)
// Wait for services to be ready
waitStart := time.Now()
t.Log("TIMING: Starting service readiness checks...")
waitForServices(t)
waitDuration := time.Since(waitStart)
t.Logf("TIMING: Service readiness check completed in %v", waitDuration)
// Build console if needed
buildStart := time.Now()
t.Log("TIMING: Starting console build...")
buildConsole(t)
buildDuration := time.Since(buildStart)
t.Logf("TIMING: Console build completed in %v", buildDuration)
setupTotalDuration := time.Since(startTime)
t.Logf("TIMING: TOTAL SETUP TIME: %v", setupTotalDuration)
// Run test suites with parallelization for significant speed improvement
testsStart := time.Now()
t.Log("TIMING: Starting PARALLELIZED test suite execution...")
// Track test suite completion times with channels for parallel execution
testTimes := make(map[string]time.Duration)
var mu sync.Mutex
// Function to record test completion time
recordTime := func(name string, duration time.Duration) {
mu.Lock()
testTimes[name] = duration
mu.Unlock()
t.Logf("TIMING: %s test suite completed in %v", name, duration)
}
// Phase 1: Run independent test suites in parallel (most tests can run concurrently)
t.Log("TIMING: Phase 1 - Running independent test suites in parallel...")
phase1Start := time.Now()
t.Run("ParallelPhase1", func(t *testing.T) {
// Basic console and connectivity tests (can run in parallel)
t.Run("ConsoleCommands", func(t *testing.T) {
t.Parallel()
start := time.Now()
testConsoleCommands(t)
recordTime("ConsoleCommands", time.Since(start))
})
t.Run("MTLSConnectivity", func(t *testing.T) {
t.Parallel()
start := time.Now()
testMTLSConnectivity(t)
recordTime("MTLSConnectivity", time.Since(start))
})
t.Run("DualPortServer", func(t *testing.T) {
t.Parallel()
start := time.Now()
testDualPortServer(t)
recordTime("DualPortServer", time.Since(start))
})
t.Run("CertificateValidation", func(t *testing.T) {
t.Parallel()
start := time.Now()
testCertificateValidation(t)
recordTime("CertificateValidation", time.Since(start))
})
t.Run("CertificateEdgeCases", func(t *testing.T) {
t.Parallel()
start := time.Now()
testCertificateEdgeCases(t)
recordTime("CertificateEdgeCases", time.Since(start))
})
t.Run("ErrorCases", func(t *testing.T) {
t.Parallel()
start := time.Now()
testErrorCases(t)
recordTime("ErrorCases", time.Since(start))
})
})
phase1Duration := time.Since(phase1Start)
t.Logf("TIMING: Phase 1 (parallel basic tests) completed in %v", phase1Duration)
// Phase 2: Run command execution tests in parallel (these already use intelligent batching)
t.Log("TIMING: Phase 2 - Running command execution test suites in parallel...")
phase2Start := time.Now()
t.Run("ParallelPhase2", func(t *testing.T) {
t.Run("ShellCommands", func(t *testing.T) {
t.Parallel()
start := time.Now()
testShellCommands(t)
recordTime("ShellCommands", time.Since(start))
})
t.Run("FileCommands", func(t *testing.T) {
t.Parallel()
start := time.Now()
testFileCommands(t)
recordTime("FileCommands", time.Since(start))
})
t.Run("SystemCommands", func(t *testing.T) {
t.Parallel()
start := time.Now()
testSystemCommands(t)
recordTime("SystemCommands", time.Since(start))
})
t.Run("DockerComposeCommands", func(t *testing.T) {
t.Parallel()
start := time.Now()
testDockerComposeCommands(t)
recordTime("DockerComposeCommands", time.Since(start))
})
t.Run("MixedTrafficScenarios", func(t *testing.T) {
t.Parallel()
start := time.Now()
testMixedTrafficScenarios(t)
recordTime("MixedTrafficScenarios", time.Since(start))
})
})
phase2Duration := time.Since(phase2Start)
t.Logf("TIMING: Phase 2 (parallel command tests) completed in %v", phase2Duration)
// Phase 3: Run tests that need to be sequential (database integrity and disruptive tests)
t.Log("TIMING: Phase 3 - Running sequential tests that require isolation...")
phase3Start := time.Now()
// Database integrity should run after command tests to verify data consistency
dbStart := time.Now()
t.Run("DatabaseIntegrity", testDatabaseIntegrity)
dbDuration := time.Since(dbStart)
recordTime("DatabaseIntegrity", dbDuration)
// Race condition test must run last as it restarts services (disruptive)
raceConditionStart := time.Now()
t.Run("MinionReconnectionRaceCondition", testMinionReconnectionRaceCondition)
raceConditionDuration := time.Since(raceConditionStart)
recordTime("MinionReconnectionRaceCondition", raceConditionDuration)
phase3Duration := time.Since(phase3Start)
t.Logf("TIMING: Phase 3 (sequential tests) completed in %v", phase3Duration)
testsDuration := time.Since(testsStart)
totalDuration := time.Since(startTime)
// Enhanced timing summary with parallelization benefits
t.Log("TIMING: =============== PARALLELIZED PERFORMANCE SUMMARY ===============")
t.Logf("TIMING: Setup Phase:")
t.Logf("TIMING: - Docker setup: %8v (%5.1f%%)", setupDockerDuration, float64(setupDockerDuration)/float64(totalDuration)*100)
t.Logf("TIMING: - Service readiness: %8v (%5.1f%%)", waitDuration, float64(waitDuration)/float64(totalDuration)*100)
t.Logf("TIMING: - Console build: %8v (%5.1f%%)", buildDuration, float64(buildDuration)/float64(totalDuration)*100)
t.Logf("TIMING: - Total setup: %8v (%5.1f%%)", setupTotalDuration, float64(setupTotalDuration)/float64(totalDuration)*100)
t.Logf("TIMING: Parallel Execution Phases:")
t.Logf("TIMING: - Phase 1 (basic): %8v (%5.1f%%) - 6 suites in parallel", phase1Duration, float64(phase1Duration)/float64(totalDuration)*100)
t.Logf("TIMING: - Phase 2 (commands): %8v (%5.1f%%) - 5 suites in parallel", phase2Duration, float64(phase2Duration)/float64(totalDuration)*100)
t.Logf("TIMING: - Phase 3 (sequential): %8v (%5.1f%%) - 2 suites sequential", phase3Duration, float64(phase3Duration)/float64(totalDuration)*100)
t.Logf("TIMING: Individual Test Suites (actual runtime in parallel context):")
// Display individual test times in sorted order
testNames := []string{
"ConsoleCommands", "ShellCommands", "FileCommands", "SystemCommands",
"DockerComposeCommands", "ErrorCases", "DatabaseIntegrity", "MTLSConnectivity",
"DualPortServer", "CertificateValidation", "MixedTrafficScenarios",
"CertificateEdgeCases", "MinionReconnectionRaceCondition",
}
totalIndividualTime := time.Duration(0)
for _, name := range testNames {
if duration, exists := testTimes[name]; exists {
t.Logf("TIMING: - %-24s %8v (%5.1f%%)", name+":", duration, float64(duration)/float64(totalDuration)*100)
totalIndividualTime += duration
}
}
t.Logf("TIMING: Parallelization Efficiency:")
t.Logf("TIMING: - Total test execution: %8v (%5.1f%%)", testsDuration, float64(testsDuration)/float64(totalDuration)*100)
t.Logf("TIMING: - Sum of individual: %8v (if run sequentially)", totalIndividualTime)
if totalIndividualTime > testsDuration {
parallelSpeedup := float64(totalIndividualTime) / float64(testsDuration)
t.Logf("TIMING: - Parallel speedup: %.1fx faster than sequential", parallelSpeedup)
t.Logf("TIMING: - Time saved: %8v", totalIndividualTime-testsDuration)
}
t.Logf("TIMING: TOTAL INTEGRATION TIME: %8v", totalDuration)
t.Log("TIMING: ================================================================")
}
// setupDockerServices ensures nexus, nexus_db, and minion services are running
func setupDockerServices(t *testing.T) {
logDebug(t, "Checking Docker Compose services status...")
// Check if services are running
statusCheckStart := time.Now()
cmd := exec.Command("docker", "compose", "ps", "--format", "json")
output, err := cmd.Output()
statusCheckDuration := time.Since(statusCheckStart)
t.Logf("TIMING: Docker status check took %v", statusCheckDuration)
if err != nil {
t.Fatalf("Failed to check docker compose status: %v", err)
}
// Parse output to check service status
parseStart := time.Now()
services := parseDockerComposePS(string(output))
parseDuration := time.Since(parseStart)
t.Logf("TIMING: Docker status parsing took %v", parseDuration)
requiredServices := []string{"nexus_db", "nexus", "minion"}
missingServices := []string{}
for _, service := range requiredServices {
if status, exists := services[service]; !exists || status != "running" {
missingServices = append(missingServices, service)
}
}
if len(missingServices) > 0 {
logDebug(t, "TIMING: Services not running: %v. Starting them...", missingServices)
// Start services
serviceStartStart := time.Now()
cmd = exec.Command("docker", "compose", "up", "-d", "nexus", "minion")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to start docker compose services: %v", err)
}
serviceStartDuration := time.Since(serviceStartStart)
t.Logf("TIMING: Docker service startup took %v", serviceStartDuration)
logDebug(t, "Services started successfully")
} else {
logDebug(t, "All required services are already running")
}
}
// parseDockerComposePS parses docker compose ps output
func parseDockerComposePS(output string) map[string]string {
services := make(map[string]string)
lines := strings.Split(output, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" || line == "[]" {
continue
}
// Simple parsing - looking for service name and state
if strings.Contains(line, "nexus_db") {
if strings.Contains(line, "running") {
services["nexus_db"] = "running"
}
}
if strings.Contains(line, "nexus") {
if strings.Contains(line, "running") {
services["nexus"] = "running"
}
}
if strings.Contains(line, "minion") {
if strings.Contains(line, "running") {
services["minion"] = "running"
}
}
}
return services
}
// waitForServices waits for services to be ready
func waitForServices(t *testing.T) {
t.Log("TIMING: Starting service readiness checks...")
// Wait for database
logDebug(t, "Checking database connectivity...")
dbStart := time.Now()
for i := 0; i < maxRetries; i++ {
db, err := sql.Open("postgres", getDBConnectionString())
if err == nil {
if err := db.Ping(); err == nil {
db.Close()
dbDuration := time.Since(dbStart)
t.Logf("TIMING: Database ready after %v (attempt %d/%d)", dbDuration, i+1, maxRetries)
break
}
db.Close()
}
if i == maxRetries-1 {
t.Fatalf("TIMING: Database not ready after %d retries and %v", maxRetries, time.Since(dbStart))
}
if i%5 == 0 { // Log every 5 attempts
t.Logf("TIMING: Database attempt %d/%d (elapsed: %v)", i+1, maxRetries, time.Since(dbStart))
}
time.Sleep(retryInterval)
}
// Check Docker health status before port tests
logDebug(t, "Checking Docker Compose service health...")
healthCheckStart := time.Now()
cmd := exec.Command("docker", "compose", "ps", "--format", "table")
if output, err := cmd.Output(); err == nil {
logDebug(t, "Docker services status:\n%s", string(output))
}
healthCheckDuration := time.Since(healthCheckStart)
t.Logf("TIMING: Docker health check took %v", healthCheckDuration)
// Wait for nexus minion server (port 11972)
t.Logf("TIMING: Checking nexus minion server (port %d)...", minionPort)
minionStart := time.Now()
for i := 0; i < maxRetries; i++ {
conn, err := net.DialTimeout("tcp", fmt.Sprintf("localhost:%d", minionPort), 1*time.Second)
if err == nil {
conn.Close()
minionDuration := time.Since(minionStart)
t.Logf("TIMING: Minion server ready after %v (attempt %d/%d)", minionDuration, i+1, maxRetries)
break
}
if i == maxRetries-1 {
t.Fatalf("TIMING: Nexus minion server not ready after %d retries and %v. Last error: %v", maxRetries, time.Since(minionStart), err)
}
if i%3 == 0 { // Log every 3 attempts
t.Logf("TIMING: Minion port attempt %d/%d (elapsed: %v, error: %v)", i+1, maxRetries, time.Since(minionStart), err)
}
time.Sleep(retryInterval)
}
// Wait for nexus console server (port 11973)
t.Logf("TIMING: Checking nexus console server (port %d)...", consolePort)
consoleStart := time.Now()
for i := 0; i < maxRetries; i++ {
conn, err := net.DialTimeout("tcp", fmt.Sprintf("localhost:%d", consolePort), 1*time.Second)
if err == nil {
conn.Close()
consoleDuration := time.Since(consoleStart)
t.Logf("TIMING: Console server ready after %v (attempt %d/%d)", consoleDuration, i+1, maxRetries)
break
}
if i == maxRetries-1 {
t.Fatalf("TIMING: Nexus console server not ready after %d retries and %v. Last error: %v", maxRetries, time.Since(consoleStart), err)
}
if i%3 == 0 { // Log every 3 attempts
t.Logf("TIMING: Console port attempt %d/%d (elapsed: %v, error: %v)", i+1, maxRetries, time.Since(consoleStart), err)
}
time.Sleep(retryInterval)
}
t.Log("TIMING: All services are ready (database, minion port, console port)")
}
// buildConsole builds the console executable if it doesn't exist
func buildConsole(t *testing.T) {
if _, err := os.Stat(consoleExecutable); os.IsNotExist(err) {
logDebug(t, "Building console executable...")
buildStart := time.Now()
// Backup certs
backupStart := time.Now()
cmd := exec.Command("mv", "internal/certs/files", "internal/certs/files.backup")
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to backup certs: %v", err)
}
backupDuration := time.Since(backupStart)
t.Logf("TIMING: Cert backup took %v", backupDuration)
// Copy test certs
copyStart := time.Now()
cmd = exec.Command("cp", "-r", "internal/certs/files.backup/test", "internal/certs/files")
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to copy test certs: %v", err)
}
copyDuration := time.Since(copyStart)
t.Logf("TIMING: Test cert copy took %v", copyDuration)
// Build console
goBuildStart := time.Now()
cmd = exec.Command("go", "build", "-o", "console-test", "./cmd/console")
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to build console: %v", err)
}
goBuildDuration := time.Since(goBuildStart)
t.Logf("TIMING: Go build took %v", goBuildDuration)
// Cleanup
cleanupStart := time.Now()
cmd = exec.Command("rm", "-rf", "internal/certs/files")
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to remove certs: %v", err)
}
cmd = exec.Command("mv", "internal/certs/files.backup", "internal/certs/files")
if err := cmd.Run(); err != nil {
t.Fatalf("Failed to restore certs: %v", err)
}
cleanupDuration := time.Since(cleanupStart)
t.Logf("TIMING: Cleanup took %v", cleanupDuration)
totalBuildDuration := time.Since(buildStart)
t.Logf("TIMING: Total console build took %v", totalBuildDuration)
} else {
logDebug(t, "Console executable already exists, skipping build")
}
}
// runConsoleCommandWithTimeout executes a console command with timeout
func runConsoleCommandWithTimeout(command string, timeout time.Duration) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Pass command directly as stdin to avoid shell quote interpretation issues
// This approach handles JSON arguments with unmatched quotes reliably
cmd := exec.CommandContext(ctx, consoleExecutable, "--server", "localhost:11973")
cmd.Stdin = strings.NewReader(command + "\n")
// Use explicit --server flag instead of environment variables for reliability
// This ensures the console connects to localhost:11973 regardless of .env file settings
output, err := cmd.CombinedOutput()
return string(output), err
}
// extractCommandID extracts command ID from console output
func extractCommandID(output string) string {
re := regexp.MustCompile(`Command ID: ([a-f0-9-]+)`)
matches := re.FindStringSubmatch(output)
if len(matches) > 1 {
return matches[1]
}
return ""
}
// testConsoleCommands tests basic console commands
func testConsoleCommands(t *testing.T) {
tests := []struct {
name string
command string
shouldWork bool
contains []string
}{
{
name: "Help",
command: "help",
shouldWork: true,
contains: []string{"Console Commands", "help", "version", "minion-list"},
},
{
name: "Help alias",
command: "h",
shouldWork: true,
contains: []string{"Console Commands"},
},
{
name: "Version",
command: "version",
shouldWork: true,
contains: []string{"Console"},
},
{
name: "Version alias",
command: "v",
shouldWork: true,
contains: []string{"Console"},
},
{
name: "Minion list",
command: "minion-list",
shouldWork: true,
contains: []string{"Connected minions", "docker-minion"},
},
{
name: "Minion list alias",
command: "lm",
shouldWork: true,
contains: []string{"Connected minions"},
},
{
name: "Tag list",
command: "tag-list",
shouldWork: true,
contains: []string{"tags"},
},
{
name: "Tag list alias",
command: "lt",
shouldWork: true,
contains: []string{"tags"},
},
{
name: "Invalid command",
command: "invalid-command",
shouldWork: false,
contains: []string{"Unknown command"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel() // Enable parallel execution for console command tests
output, err := runConsoleCommandWithTimeout(tt.command, 5*time.Second) // Reduced from 10s
if tt.shouldWork {
assert.NoError(t, err, "Command should not fail")
}
for _, substr := range tt.contains {
assert.Contains(t, output, substr, "Output should contain expected text")
}
})
}
}
// testShellCommands tests shell command execution with OPTIMIZED intelligent polling
func testShellCommands(t *testing.T) {
tests := []struct {
name string
command string
shouldWork bool
expectError bool
numResults int // Number of expected results in database
}{
{
name: "Simple shell command",
command: "command-send all echo 'hello world'",
shouldWork: true,
numResults: 1, // Expect one result for this command
},
{
name: "List directory",
command: "command-send all ls /",
shouldWork: true,
numResults: 1,
},
{
name: "System info command",
command: "command-send all system:info",
shouldWork: true,
numResults: 1,
},
{
name: "System OS command",
command: "command-send all system:os",
shouldWork: true,
numResults: 1,
},
{
name: "Docker Compose PS with nonexistent path",
command: "command-send all docker-compose:ps /nonexistent/path",
shouldWork: true, // Command will be sent but will fail on minion
numResults: 1,
},
{
name: "Docker Compose PS with invalid JSON",
command: `command-send all '{"command": "ps", "path":'`,
shouldWork: true, // Command will be sent but will fail on minion
numResults: 1,
},
{
name: "Docker Compose UP with missing path",
command: `command-send all '{"command": "up"}'`,
shouldWork: true, // Command will be sent but will fail on minion
numResults: 1,
},
{
name: "Docker Compose DOWN with current directory",
command: "command-send all docker-compose:down .",
shouldWork: true, // Command will be sent but will fail on minion (no docker-compose.yml in current dir)
numResults: 1,
},
{
name: "Command with missing target",
command: "command-send",
shouldWork: false,
expectError: true,
numResults: 0,
},
{
name: "Command with invalid minion ID",
command: "command-send minion invalid-id echo test",
shouldWork: false, // Command should be rejected
expectError: true,
numResults: 0, // No results expected for invalid command
},
{
name: "Command with missing minion ID",
command: "command-send minion",
shouldWork: false,
expectError: true,
numResults: 0, // No results expected for invalid command
},
{
name: "Command with missing tag",
command: "command-send tag",
shouldWork: false,
expectError: true,
numResults: 0, // No results expected for invalid command
},
{
name: "Command with invalid tag format",
command: "command-send tag invalidtag echo test",
shouldWork: false,
expectError: true,
numResults: 0, // No results expected for invalid command
},
}
// TIMING: Execute commands in batch, then poll intelligently
var commandIDs []string
var testNames []string
batchStart := time.Now()
t.Log("TIMING: Starting shell command batch execution...")
// Phase 1: Send all successful commands rapidly (no waiting between sends)
for _, tt := range tests {
t.Run(fmt.Sprintf("send_%s", tt.name), func(t *testing.T) {
if tt.expectError {
// Handle error cases immediately
errorStart := time.Now()
output, err := runConsoleCommandWithTimeout(tt.command, 2*time.Second)
errorDuration := time.Since(errorStart)
logDebug(t, "Error case '%s' handled in %v", tt.name, errorDuration)
assert.True(t, err != nil || strings.Contains(output, "Error") ||
strings.Contains(output, "Usage:") || strings.Contains(output, "Command was not accepted"),
"Command should fail or show error message")
return
}
if !tt.shouldWork {
return
}
// Send command quickly
testStart := time.Now()
output, err := runConsoleCommandWithTimeout(tt.command, 3*time.Second)
commandExecTime := time.Since(testStart)
assert.NoError(t, err, "Command send should not fail")
assert.Contains(t, output, "Command dispatched successfully", "Should show success message")
commandID := extractCommandID(output)
assert.NotEmpty(t, commandID, "Should return a command ID")
// Quick DB verification
dbVerifyStart := time.Now()
verifyCommandInDB(t, commandID)
dbVerifyDuration := time.Since(dbVerifyStart)
// Store for batch polling
commandIDs = append(commandIDs, commandID)
testNames = append(testNames, tt.name)
if len(commandID) >= 8 {
t.Logf("TIMING: Sent command '%s' in %v (ID: %s, DB verify: %v)", tt.name, commandExecTime, commandID[:8], dbVerifyDuration)
} else {
t.Logf("TIMING: Sent command '%s' in %v (ID: %s, DB verify: %v)", tt.name, commandExecTime, commandID, dbVerifyDuration)
}
})
}
sendDuration := time.Since(batchStart)
t.Logf("TIMING: BATCH SEND completed: %d commands in %v (vs %v with sequential waits)",
len(commandIDs), sendDuration, time.Duration(len(commandIDs))*10*time.Second)
// Phase 2: Intelligent polling for ALL results
if len(commandIDs) > 0 {
pollStart := time.Now()
t.Logf("TIMING: Starting intelligent polling for %d commands...", len(commandIDs))
// Initial wait for execution to start
t.Log("TIMING: Initial wait period before polling...")
time.Sleep(1 * time.Second) // Reduced from 2 seconds
// Progressive polling with early termination
resultsFound := make(map[string]bool)
maxAttempts := 30 // 15 seconds max with 500ms polling (reduced from 60)
pollCount := 0
for attempt := 0; attempt < maxAttempts; attempt++ {
pollCount++
attemptStart := time.Now()
foundCount := 0
for i, commandID := range commandIDs {
if resultsFound[commandID] {
foundCount++
continue
}
actualResults := getNbResultsInDB(t, commandID)
if actualResults > 0 {
resultsFound[commandID] = true
foundCount++
elapsed := time.Since(pollStart)
idDisplay := commandID
if len(commandID) >= 8 {
idDisplay = commandID[:8]
}
t.Logf("TIMING: Results for '%s' (%s) found after %v (poll attempt %d)",
testNames[i], idDisplay, elapsed, pollCount)
}
}
attemptDuration := time.Since(attemptStart)
if attempt%10 == 0 { // Log every 10 attempts
t.Logf("TIMING: Poll attempt %d took %v, found %d/%d results", pollCount, attemptDuration, foundCount, len(commandIDs))
}
// Early termination when all results found
if foundCount == len(commandIDs) {
totalPollTime := time.Since(pollStart)
t.Logf("TIMING: ALL RESULTS FOUND: %d/%d in %v after %d poll attempts (early termination)",
foundCount, len(commandIDs), totalPollTime, pollCount)
break
}
// Adaptive polling: fast initially, slower later
pollInterval := 300 * time.Millisecond // Reduced from 500ms
if attempt > 15 { // Reduced threshold from 20
pollInterval = 500 * time.Millisecond // Reduced from 1s
}
time.Sleep(pollInterval)
}
totalPollTime := time.Since(pollStart)
finalCount := len(resultsFound)
originalTime := time.Duration(len(commandIDs)) * 10 * time.Second
timesSaved := originalTime - (sendDuration + totalPollTime)
t.Logf("TIMING: SHELL COMMAND OPTIMIZATION RESULTS:")
t.Logf("TIMING: Commands processed: %d/%d successful", finalCount, len(commandIDs))
t.Logf("TIMING: Total time: %v (send: %v + poll: %v)", sendDuration+totalPollTime, sendDuration, totalPollTime)
t.Logf("TIMING: Poll attempts: %d", pollCount)
t.Logf("TIMING: Original approach: %v (with 10s fixed sleeps)", originalTime)
t.Logf("TIMING: Time saved: %v (%.1f%% faster)", timesSaved, float64(timesSaved)/float64(originalTime)*100)
}
}
// testFileCommands tests file-related commands
func testFileCommands(t *testing.T) {
tests := []struct {
name string
command string
shouldWork bool
expectError bool
numResults int // Number of expected results in database
}{
{
name: "Get file content",
command: "command-send all file:get /etc/hostname",
shouldWork: true,
numResults: 1,
},
{
name: "Get file info",
command: "command-send all file:info /etc/hostname",
shouldWork: true,
numResults: 1,
},
{
name: "Get non-existent file",
command: "command-send all file:get /non/existent/file",
shouldWork: true, // Command is sent but will fail on execution
numResults: 1,
},
{
name: "File command with missing path",
command: "command-send all file:get",
shouldWork: true, // Command is sent but will fail due to missing argument
numResults: 1,
},
{
name: "File copy command",
command: "command-send all file:copy /etc/hostname /tmp/test-hostname",
shouldWork: true,
numResults: 1,
},
{
name: "File move command",
command: "command-send all file:move /tmp/test-hostname /tmp/moved-hostname",
shouldWork: true,
numResults: 1,
},
}
// TIMING: Apply same intelligent polling to file commands
var commandIDs []string
var testNames []string
batchStart := time.Now()
// Phase 1: Send file commands rapidly
for _, tt := range tests {
t.Run(fmt.Sprintf("send_%s", tt.name), func(t *testing.T) {
if tt.expectError {
output, err := runConsoleCommandWithTimeout(tt.command, 15*time.Second)
assert.True(t, err != nil || strings.Contains(output, "Error"),
"Command should fail or show error message")
return
}
if !tt.shouldWork {
return
}
testStart := time.Now()
output, err := runConsoleCommandWithTimeout(tt.command, 15*time.Second)
commandExecTime := time.Since(testStart)
assert.NoError(t, err, "File command send should not fail")
assert.Contains(t, output, "Command dispatched successfully", "Should show success message")
commandID := extractCommandID(output)
assert.NotEmpty(t, commandID, "Should return a command ID")
verifyCommandInDB(t, commandID)