diff --git a/config_test.go b/config_test.go new file mode 100644 index 0000000..6b5b466 --- /dev/null +++ b/config_test.go @@ -0,0 +1,286 @@ +package main + +import ( + "bytes" + "context" + "flag" + "io" + "net/url" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// parseFlagsForTest parses args into a fresh flag set and returns the resulting Config. +// The slice and host flags accumulate across parses, so they are cleared first. +func parseFlagsForTest(t *testing.T, args []string) (Config, error) { + t.Helper() + resetGlobals(t) + + templatesFlag, stdoutTailFlag, stderrTailFlag = nil, nil, nil + headersFlag, waitFlag, delimsFlag = nil, nil, "" + + oldCommandLine, oldUsage := flag.CommandLine, flag.Usage + t.Cleanup(func() { + flag.CommandLine, flag.Usage = oldCommandLine, oldUsage + }) + flag.CommandLine = flag.NewFlagSet("dockerize", flag.ContinueOnError) + + registerFlags() + require.NoError(t, flag.CommandLine.Parse(args)) + return parseConfigFromFlags() +} + +func urlStrings(urls []url.URL) []string { + out := make([]string, 0, len(urls)) + for _, u := range urls { + out = append(out, u.String()) + } + return out +} + +func TestParseConfigFromFlags(t *testing.T) { + t.Run("defaults", func(t *testing.T) { + cfg, err := parseFlagsForTest(t, []string{}) + require.NoError(t, err) + + assert.False(t, cfg.version) + assert.False(t, cfg.poll) + assert.False(t, cfg.noOverwrite) + assert.Equal(t, 10*time.Second, cfg.waitTimeout) + assert.Equal(t, defaultWaitRetryInterval, cfg.waitRetryInterval) + assert.Empty(t, cfg.templates) + assert.Empty(t, cfg.stdoutTails) + assert.Empty(t, cfg.stderrTails) + assert.Empty(t, cfg.delims) + assert.Empty(t, cfg.headers) + assert.Empty(t, cfg.urls) + assert.Empty(t, cfg.waits) + assert.Empty(t, cfg.args) + }) + + t.Run("full flag set", func(t *testing.T) { + cfg, err := parseFlagsForTest(t, []string{ + "-template", "a.tmpl:/etc/a.conf", + "-template", "dir:/etc/conf.d", + "-wait", "tcp://db:5432", + "-wait", "http://web:8000/health", + "-wait", "file:///tmp/ready", + "-wait-http-header", "Accept-Encoding: gzip", + "-wait-http-header", "X-Token:abc", + "-delims", "<%:%>", + "-timeout", "5s", + "-wait-retry-interval", "2s", + "-no-overwrite", + "-poll", + "-stdout", "/var/log/a.log", + "-stdout", "/var/log/b.log", + "-stderr", "/var/log/err.log", + "nginx", "-g", "daemon off;", + }) + require.NoError(t, err) + + assert.True(t, cfg.poll) + assert.True(t, cfg.noOverwrite) + assert.False(t, cfg.version) + assert.Equal(t, []string{"a.tmpl:/etc/a.conf", "dir:/etc/conf.d"}, cfg.templates) + assert.Equal(t, []string{"/var/log/a.log", "/var/log/b.log"}, cfg.stdoutTails) + assert.Equal(t, []string{"/var/log/err.log"}, cfg.stderrTails) + assert.Equal(t, []string{"Accept-Encoding: gzip", "X-Token:abc"}, cfg.headersFlag) + assert.Equal(t, []string{"<%", "%>"}, cfg.delims) + assert.Equal(t, []HttpHeader{ + {name: "Accept-Encoding", value: "gzip"}, + {name: "X-Token", value: "abc"}, + }, cfg.headers) + assert.Equal(t, []string{"tcp://db:5432", "http://web:8000/health", "file:///tmp/ready"}, cfg.waits) + assert.Equal(t, []string{"tcp://db:5432", "http://web:8000/health", "file:///tmp/ready"}, urlStrings(cfg.urls)) + assert.Equal(t, "tcp", cfg.urls[0].Scheme) + assert.Equal(t, "http", cfg.urls[1].Scheme) + assert.Equal(t, "file", cfg.urls[2].Scheme) + assert.Equal(t, 5*time.Second, cfg.waitTimeout) + assert.Equal(t, 2*time.Second, cfg.waitRetryInterval) + assert.Equal(t, []string{"nginx", "-g", "daemon off;"}, cfg.args) + }) + + t.Run("version flag", func(t *testing.T) { + cfg, err := parseFlagsForTest(t, []string{"-version"}) + require.NoError(t, err) + assert.True(t, cfg.version) + }) + + t.Run("bad delimiters", func(t *testing.T) { + cfg, err := parseFlagsForTest(t, []string{"-delims", "a:b:c"}) + assert.EqualError(t, err, `bad delimiters argument: a:b:c. expected "left:right"`) + assert.Equal(t, Config{}, cfg) + }) + + t.Run("header without wait", func(t *testing.T) { + cfg, err := parseFlagsForTest(t, []string{"-wait-http-header", "Accept: text/html"}) + assert.ErrorContains(t, err, `-wait-http-header "Accept: text/html" provided with no -wait option`) + assert.Equal(t, Config{}, cfg) + }) + + t.Run("header without colon", func(t *testing.T) { + cfg, err := parseFlagsForTest(t, []string{"-wait", "tcp://db:5432", "-wait-http-header", "Accept"}) + assert.ErrorContains(t, err, `bad HTTP Headers argument: Accept.`) + assert.Equal(t, Config{}, cfg) + }) + + t.Run("bad wait URL", func(t *testing.T) { + cfg, err := parseFlagsForTest(t, []string{"-wait", "http://[::1"}) + assert.ErrorContains(t, err, "bad hostname provided: http://[::1.") + assert.Equal(t, Config{}, cfg) + }) +} + +func TestParseConfigFromFlagsRestoresCommandLine(t *testing.T) { + before := flag.CommandLine + t.Run("parse", func(t *testing.T) { + _, err := parseFlagsForTest(t, []string{}) + require.NoError(t, err) + }) + assert.Same(t, before, flag.CommandLine) +} + +func TestStartCommandRunsCommand(t *testing.T) { + resetGlobals(t) + oldCommandLine := flag.CommandLine + t.Cleanup(func() { flag.CommandLine = oldCommandLine }) + flag.CommandLine = flag.NewFlagSet("dockerize", flag.ContinueOnError) + require.NoError(t, flag.CommandLine.Parse([]string{"true"})) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + startCommand(ctx, cancel) + + waitOrFail(t, "command did not finish") + assert.Error(t, ctx.Err(), "context should be cancelled once the command exits") +} + +func TestStartCommandWithoutArgsAddsNothing(t *testing.T) { + resetGlobals(t) + oldCommandLine := flag.CommandLine + t.Cleanup(func() { flag.CommandLine = oldCommandLine }) + flag.CommandLine = flag.NewFlagSet("dockerize", flag.ContinueOnError) + require.NoError(t, flag.CommandLine.Parse([]string{})) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + startCommand(ctx, cancel) + + waitOrFail(t, "wait group should be empty") + assert.NoError(t, ctx.Err(), "context should not be cancelled") +} + +func TestStartTailersStopsWhenContextCanceled(t *testing.T) { + resetGlobals(t) + dir := t.TempDir() + stdoutPath := filepath.Join(dir, "stdout.log") + stderrPath := filepath.Join(dir, "stderr.log") + require.NoError(t, os.WriteFile(stdoutPath, []byte{}, 0o644)) + require.NoError(t, os.WriteFile(stderrPath, []byte{}, 0o644)) + + stdoutTailFlag = sliceVar{stdoutPath} + stderrTailFlag = sliceVar{stderrPath} + poll = true + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + startTailers(ctx) + time.Sleep(100 * time.Millisecond) + cancel() + + waitOrFail(t, "tailers did not stop after context cancellation") +} + +// waitOrFail waits for wg with a timeout, failing the test with msg if it does not finish. +func waitOrFail(t *testing.T, msg string) { + t.Helper() + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal(msg) + } +} + +func TestUsage(t *testing.T) { + if fatalCase("usage") { + flag.CommandLine = flag.NewFlagSet("dockerize", flag.ContinueOnError) + registerFlags() + usage() + return + } + + // usage writes with the builtin println, which bypasses os.Stderr, so its text is checked in a child process. + usage() + + exitCode, stderr := runFatalCase(t, "TestUsage", "usage") + assert.Equal(t, 0, exitCode) + assert.Contains(t, stderr, "Usage: dockerize [options] [command]") + assert.Contains(t, stderr, "-wait-http-header") + assert.Contains(t, stderr, "For more information, see https://github.com/jwilder/dockerize") +} + +func TestMainPrintsVersion(t *testing.T) { + resetGlobals(t) + oldArgs, oldCommandLine, oldUsage, oldBuildVersion := os.Args, flag.CommandLine, flag.Usage, buildVersion + t.Cleanup(func() { + os.Args, flag.CommandLine, flag.Usage, buildVersion = oldArgs, oldCommandLine, oldUsage, oldBuildVersion + }) + flag.CommandLine = flag.NewFlagSet("dockerize", flag.ContinueOnError) + os.Args = []string{"dockerize", "-version"} + buildVersion = "v1.2.3" + + oldStdout := os.Stdout + r, w, err := os.Pipe() + require.NoError(t, err) + os.Stdout = w + t.Cleanup(func() { os.Stdout = oldStdout }) + + main() + + require.NoError(t, w.Close()) + os.Stdout = oldStdout + var buf bytes.Buffer + _, err = io.Copy(&buf, r) + require.NoError(t, err) + assert.Equal(t, "v1.2.3\n", buf.String()) +} + +func TestMainFatalCases(t *testing.T) { + if fatalCase("no-args") { + flag.CommandLine = flag.NewFlagSet("dockerize", flag.ContinueOnError) + os.Args = []string{"dockerize"} + main() + } + if fatalCase("bad-delims") { + flag.CommandLine = flag.NewFlagSet("dockerize", flag.ContinueOnError) + os.Args = []string{"dockerize", "-delims", "a:b:c"} + main() + } + + t.Run("no args prints usage and exits 1", func(t *testing.T) { + exitCode, stderr := runFatalCase(t, "TestMainFatalCases", "no-args") + assert.Equal(t, 1, exitCode) + assert.Contains(t, stderr, "Usage: dockerize [options] [command]") + }) + + t.Run("bad delimiters exit 1 with error", func(t *testing.T) { + exitCode, stderr := runFatalCase(t, "TestMainFatalCases", "bad-delims") + assert.Equal(t, 1, exitCode) + assert.Contains(t, stderr, `bad delimiters argument: a:b:c. expected "left:right"`) + }) +} diff --git a/exec.go b/exec.go index 18d78e9..d040d54 100644 --- a/exec.go +++ b/exec.go @@ -62,6 +62,8 @@ func runCmd(ctx context.Context, cancel context.CancelFunc, cmd string, args ... } +var signalKillTimeout = 10 * time.Second + func signalProcessWithTimeout(process *exec.Cmd, sig os.Signal, waitDone ...<-chan struct{}) { // pretty sure this doesn't do anything. It seems like the signal is automatically sent to the command? if err := process.Process.Signal(sig); err != nil && !errors.Is(err, os.ErrProcessDone) { @@ -79,7 +81,7 @@ func signalProcessWithTimeout(process *exec.Cmd, sig os.Signal, waitDone ...<-ch select { case <-waitDone[0]: return - case <-time.After(10 * time.Second): + case <-time.After(signalKillTimeout): log.Println("Killing command due to timeout.") if err := process.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) { log.Printf("Error killing command: %s\n", err) diff --git a/exec_test.go b/exec_test.go new file mode 100644 index 0000000..af780f7 --- /dev/null +++ b/exec_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "bufio" + "os/exec" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSignalKillTimeoutDefault(t *testing.T) { + assert.Equal(t, 10*time.Second, signalKillTimeout) +} + +func TestSignalProcessWithTimeoutDeliversSignal(t *testing.T) { + t.Parallel() + + cmd := exec.Command("sleep", "30") + require.NoError(t, cmd.Start()) + + signalProcessWithTimeout(cmd, syscall.SIGTERM) + + require.NotNil(t, cmd.ProcessState) + status, ok := cmd.ProcessState.Sys().(syscall.WaitStatus) + require.True(t, ok) + assert.True(t, status.Signaled()) + assert.Equal(t, syscall.SIGTERM, status.Signal()) +} + +func TestSignalProcessWithTimeoutKillsAfterTimeout(t *testing.T) { + // Not parallel: it overrides the package-level signalKillTimeout. + oldTimeout := signalKillTimeout + signalKillTimeout = 200 * time.Millisecond + t.Cleanup(func() { signalKillTimeout = oldTimeout }) + + // exec replaces the shell with sleep, so the ignored TERM disposition + // is inherited and SIGKILL is the only thing that stops it. + cmd := exec.Command("sh", "-c", `trap "" TERM; echo ready; exec sleep 30`) + stdout, err := cmd.StdoutPipe() + require.NoError(t, err) + require.NoError(t, cmd.Start()) + + // Wait until the trap is installed before signalling. + line, err := bufio.NewReader(stdout).ReadString('\n') + require.NoError(t, err) + require.Equal(t, "ready\n", line) + + // Reap the process in our own goroutine: the kill branch returns without + // waiting, so reading ProcessState afterwards would race with cmd.Wait. + waitDone := make(chan struct{}) + go func() { + _ = cmd.Wait() + close(waitDone) + }() + + start := time.Now() + signalProcessWithTimeout(cmd, syscall.SIGTERM, waitDone) + assert.Less(t, time.Since(start), 2*time.Second) + + select { + case <-waitDone: + case <-time.After(5 * time.Second): + t.Fatal("process was not killed after the timeout") + } + + status, ok := cmd.ProcessState.Sys().(syscall.WaitStatus) + require.True(t, ok) + assert.True(t, status.Signaled()) + assert.Equal(t, syscall.SIGKILL, status.Signal()) +} + +func TestSignalProcessWithTimeoutReturnsWhenAlreadyDone(t *testing.T) { + // Not parallel: it overrides the package-level signalKillTimeout. + oldTimeout := signalKillTimeout + signalKillTimeout = 5 * time.Second + t.Cleanup(func() { signalKillTimeout = oldTimeout }) + + cmd := exec.Command("sleep", "30") + require.NoError(t, cmd.Start()) + + waitDone := make(chan struct{}) + close(waitDone) + + start := time.Now() + signalProcessWithTimeout(cmd, syscall.SIGTERM, waitDone) + assert.Less(t, time.Since(start), time.Second) + + _ = cmd.Wait() +} diff --git a/main.go b/main.go index 593e549..9451dc1 100644 --- a/main.go +++ b/main.go @@ -170,6 +170,7 @@ func waitForHTTP(u url.URL) { if err != nil { log.Printf("Problem creating request for %s: %v. Sleeping %s\n", u.String(), err.Error(), waitRetryInterval) time.Sleep(waitRetryInterval) + continue } if len(headers) > 0 { for _, header := range headers { diff --git a/main_test.go b/main_test.go index 9ed5349..4bd8f1e 100644 --- a/main_test.go +++ b/main_test.go @@ -9,10 +9,8 @@ import ( "net/http/httptest" "net/url" "os" - "os/exec" "path/filepath" "sync" - "syscall" "testing" "time" @@ -24,6 +22,8 @@ func TestMain(m *testing.M) { } func TestSliceVarString(t *testing.T) { + t.Parallel() + var sv sliceVar if err := sv.Set("test1"); err != nil { t.Fatal(err) @@ -36,6 +36,8 @@ func TestSliceVarString(t *testing.T) { } func TestHostFlagsVarString(t *testing.T) { + t.Parallel() + var hf hostFlagsVar if err := hf.Set("host1"); err != nil { t.Fatal(err) @@ -48,6 +50,8 @@ func TestHostFlagsVarString(t *testing.T) { } func TestExists(t *testing.T) { + t.Parallel() + tempFile, err := os.CreateTemp("", "test-exists") assert.NoError(t, err) t.Cleanup(func() { _ = os.Remove(tempFile.Name()) }) @@ -63,6 +67,8 @@ func TestExists(t *testing.T) { } func TestContains(t *testing.T) { + t.Parallel() + testMap := map[string]string{ "key1": "value1", "key2": "value2", @@ -74,6 +80,8 @@ func TestContains(t *testing.T) { } func TestContextEnvReturnsCurrentEnvironment(t *testing.T) { + t.Parallel() + ctx := &Context{} env := ctx.Env() expected := make(map[string]string) @@ -96,6 +104,8 @@ func TestContextEnvReturnsCurrentEnvironment(t *testing.T) { } func TestDefaultValue(t *testing.T) { + t.Parallel() + result, err := defaultValue("test-value") assert.NoError(t, err) assert.Equal(t, "test-value", result) @@ -116,6 +126,8 @@ func TestDefaultValue(t *testing.T) { } func TestParseUrl(t *testing.T) { + t.Parallel() + url := parseUrl("http://example.com/path") assert.Equal(t, "http", url.Scheme) assert.Equal(t, "example.com", url.Host) @@ -128,6 +140,8 @@ func TestParseUrl(t *testing.T) { } func TestAdd(t *testing.T) { + t.Parallel() + result := add(5, 3) assert.Equal(t, 8, result) @@ -139,6 +153,8 @@ func TestAdd(t *testing.T) { } func TestIsTrue(t *testing.T) { + t.Parallel() + assert.True(t, isTrue("true")) assert.True(t, isTrue("TRUE")) assert.True(t, isTrue("1")) @@ -155,6 +171,8 @@ func TestIsTrue(t *testing.T) { } func TestLoop(t *testing.T) { + t.Parallel() + ch, err := loop(3) assert.NoError(t, err) @@ -190,6 +208,8 @@ func TestLoop(t *testing.T) { } func TestParseDelimiters(t *testing.T) { + t.Parallel() + tests := []struct { name string input string @@ -219,6 +239,8 @@ func TestParseDelimiters(t *testing.T) { } func TestParseWaitURLs(t *testing.T) { + t.Parallel() + tests := []struct { name string input hostFlagsVar @@ -254,6 +276,8 @@ func TestParseWaitURLs(t *testing.T) { } func TestParseHeaders(t *testing.T) { + t.Parallel() + tests := []struct { name string values []string @@ -292,6 +316,8 @@ func TestParseHeaders(t *testing.T) { } func TestProcessTemplatesFileAndDirectoryArguments(t *testing.T) { + resetGlobals(t) + fileTemplateDir := t.TempDir() filePath := filepath.Join(fileTemplateDir, "source.tmpl") fileDest := filepath.Join(fileTemplateDir, "out.txt") @@ -310,18 +336,9 @@ func TestProcessTemplatesFileAndDirectoryArguments(t *testing.T) { } func TestWaitForSocketUsesPassedTimeoutForDial(t *testing.T) { - oldDialTimeout := dialTimeout - oldTimeout := waitTimeoutFlag - oldRetry := waitRetryInterval - wg = sync.WaitGroup{} + resetGlobals(t) waitTimeoutFlag = 200 * time.Millisecond waitRetryInterval = 10 * time.Millisecond - defer func() { - dialTimeout = oldDialTimeout - waitTimeoutFlag = oldTimeout - waitRetryInterval = oldRetry - wg = sync.WaitGroup{} - }() timeoutArg := make(chan time.Duration, 1) dialTimeout = func(network, address string, timeout time.Duration) (net.Conn, error) { @@ -363,18 +380,9 @@ func TestWaitForSocketConnectsToTCPServer(t *testing.T) { log.SetOutput(&logs) defer log.SetOutput(oldLogWriter) - oldRetry := waitRetryInterval - oldTimeout := waitTimeoutFlag - oldDialTimeout := dialTimeout - wg = sync.WaitGroup{} + resetGlobals(t) waitRetryInterval = 10 * time.Millisecond waitTimeoutFlag = 200 * time.Millisecond - defer func() { - wg = sync.WaitGroup{} - waitRetryInterval = oldRetry - waitTimeoutFlag = oldTimeout - dialTimeout = oldDialTimeout - }() acceptDone := make(chan struct{}) go func() { @@ -457,6 +465,8 @@ func TestWaitForDependenciesWaitsForFileAndHTTP(t *testing.T) { requestCount++ seenHeader = r.Header.Get("X-Test") if requestCount == 1 { + // Make the file dependency ready only once the HTTP dependency has been hit. + _ = os.WriteFile(readyFile, []byte("ready"), 0o644) w.WriteHeader(http.StatusServiceUnavailable) return } @@ -468,30 +478,12 @@ func TestWaitForDependenciesWaitsForFileAndHTTP(t *testing.T) { assert.NoError(t, err) fileURL := url.URL{Scheme: "file", Path: readyFile} - oldURLs := urls - oldHeaders := headers - oldWaitFlag := waitFlag - oldRetry := waitRetryInterval - oldTimeout := waitTimeoutFlag + resetGlobals(t) urls = []url.URL{fileURL, *httpURL} headers = []HttpHeader{{name: "X-Test", value: "value"}} waitFlag = hostFlagsVar{"file://" + readyFile, server.URL} - wg = sync.WaitGroup{} waitRetryInterval = 10 * time.Millisecond - waitTimeoutFlag = time.Second - defer func() { - urls = oldURLs - headers = oldHeaders - waitFlag = oldWaitFlag - wg = sync.WaitGroup{} - waitRetryInterval = oldRetry - waitTimeoutFlag = oldTimeout - }() - - go func() { - time.Sleep(30 * time.Millisecond) - _ = os.WriteFile(readyFile, []byte("ready"), 0o644) - }() + waitTimeoutFlag = 10 * time.Second waitForDependencies() @@ -502,27 +494,12 @@ func TestWaitForDependenciesWaitsForFileAndHTTP(t *testing.T) { assert.Contains(t, logs.String(), "Received 503 from "+server.URL) } -func TestSignalProcessWithTimeoutPassesSignal(t *testing.T) { - cmd := exec.Command("sh", "-c", "sleep 10") - err := cmd.Start() - assert.NoError(t, err) - - signalProcessWithTimeout(cmd, syscall.SIGTERM) - assert.NotNil(t, cmd.ProcessState) - assert.NotNil(t, cmd.Process) - err = cmd.Process.Signal(syscall.Signal(0)) - assert.Error(t, err) -} - func TestRunCmdCancelsContextWhenCommandExits(t *testing.T) { + resetGlobals(t) + ctx, cancelFn := context.WithCancel(context.Background()) defer cancelFn() - wg = sync.WaitGroup{} - defer func() { - wg = sync.WaitGroup{} - }() - wg.Add(1) go runCmd(ctx, cancelFn, "sh", "-c", "exit 0") diff --git a/tail_test.go b/tail_test.go index 5987d85..97cc70a 100644 --- a/tail_test.go +++ b/tail_test.go @@ -5,10 +5,14 @@ import ( "bytes" "context" "errors" + "io" "log" "os" "path/filepath" + "runtime" "strings" + "sync" + "syscall" "testing" "time" ) @@ -199,3 +203,210 @@ func TestTailFileStopsOnWriteError(t *testing.T) { t.Fatalf("expected write error in log output, got %q", got) } } + +func TestTailFilePicksUpFileCreatedLater(t *testing.T) { + resetGlobals(t) + logs := captureLog(t) + + tailDir := t.TempDir() + sourcePath := filepath.Join(tailDir, "later.log") + dest, destPath := newDestFile(t, tailDir) + + stop := startTailFile(t, sourcePath, false, dest) + + waitForLogContaining(t, logs, "Warning: unable to stat "+sourcePath) + + if err := os.WriteFile(sourcePath, []byte("created late\nappended later\n"), 0o644); err != nil { + t.Fatalf("create source file: %v", err) + } + + waitForFileContaining(t, destPath, "created late", "appended later") + stop() +} + +func TestTailFileReadsNamedPipe(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("named pipes via syscall.Mkfifo are not available on Windows") + } + resetGlobals(t) + + tailDir := t.TempDir() + pipePath := filepath.Join(tailDir, "pipe.log") + if err := syscall.Mkfifo(pipePath, 0o600); err != nil { + t.Fatalf("create fifo: %v", err) + } + dest, destPath := newDestFile(t, tailDir) + + stop := startTailFile(t, pipePath, false, dest) + + // Opening the write end blocks until tailFile opens the read end, so bound it with a timeout. + writerCh := make(chan *os.File, 1) + errCh := make(chan error, 1) + go func() { + w, err := os.OpenFile(pipePath, os.O_WRONLY, 0) + if err != nil { + errCh <- err + return + } + writerCh <- w + }() + + var writer *os.File + select { + case writer = <-writerCh: + t.Cleanup(func() { _ = writer.Close() }) + case err := <-errCh: + t.Fatalf("open fifo for writing: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for tailFile to open the fifo for reading") + } + + if _, err := writer.WriteString("from pipe\nsecond pipe line\n"); err != nil { + t.Fatalf("write to fifo: %v", err) + } + + waitForFileContaining(t, destPath, "from pipe", "second pipe line") + + // The tail library blocks reading the pipe until the write end closes, so close it before stopping. + if err := writer.Close(); err != nil { + t.Fatalf("close fifo writer: %v", err) + } + stop() +} + +func TestTailFilePollModeReadsExistingAndAppendedLines(t *testing.T) { + resetGlobals(t) + + tailDir := t.TempDir() + sourcePath := filepath.Join(tailDir, "poll.log") + dest, destPath := newDestFile(t, tailDir) + + if err := os.WriteFile(sourcePath, []byte("existing line\n"), 0o644); err != nil { + t.Fatalf("write source file: %v", err) + } + + stop := startTailFile(t, sourcePath, true, dest) + + f, err := os.OpenFile(sourcePath, os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + t.Fatalf("open source for append: %v", err) + } + if _, err := f.WriteString("appended line\n"); err != nil { + _ = f.Close() + t.Fatalf("append source line: %v", err) + } + if err := f.Close(); err != nil { + t.Fatalf("close source file: %v", err) + } + + waitForFileContaining(t, destPath, "existing line", "appended line") + stop() +} + +// newDestFile creates a destination file in dir and closes it when the test ends. +func newDestFile(t *testing.T, dir string) (*os.File, string) { + t.Helper() + + destPath := filepath.Join(dir, "dest.log") + dest, err := os.Create(destPath) + if err != nil { + t.Fatalf("create dest file: %v", err) + } + t.Cleanup(func() { _ = dest.Close() }) + return dest, destPath +} + +// startTailFile runs tailFile in the background. The returned stop func cancels it and fails +// the test if it has not returned within five seconds; it is also called on test cleanup. +func startTailFile(t *testing.T, file string, poll bool, dest *os.File) (stop func()) { + t.Helper() + + ctx, cancel := context.WithCancel(context.Background()) + wg.Add(1) + go tailFile(ctx, file, poll, dest) + + stop = func() { + cancel() + + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("tailFile did not return after context cancellation") + } + } + t.Cleanup(stop) + return stop +} + +// syncBuffer receives log output from the tailFile goroutine while the test reads it. +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// captureLog sends the standard logger to a buffer until the test ends. +func captureLog(t *testing.T) *syncBuffer { + t.Helper() + + var buf syncBuffer + oldOutput := log.Writer() + log.SetOutput(io.Writer(&buf)) + t.Cleanup(func() { log.SetOutput(oldOutput) }) + return &buf +} + +func waitForLogContaining(t *testing.T, logs *syncBuffer, want string) { + t.Helper() + + deadline := time.Now().Add(5 * time.Second) + for !strings.Contains(logs.String(), want) { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for log %q, got %q", want, logs.String()) + } + time.Sleep(50 * time.Millisecond) + } +} + +func waitForFileContaining(t *testing.T, path string, wants ...string) { + t.Helper() + + deadline := time.Now().Add(5 * time.Second) + for { + got, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + all := true + for _, want := range wants { + if !strings.Contains(string(got), want) { + all = false + break + } + } + if all { + return + } + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %q in %s, got %q", wants, path, string(got)) + } + time.Sleep(50 * time.Millisecond) + } +} diff --git a/template_errors_test.go b/template_errors_test.go new file mode 100644 index 0000000..fe2c7a9 --- /dev/null +++ b/template_errors_test.go @@ -0,0 +1,137 @@ +package main + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// writeTemplateFile writes content to dir/name and returns the path. +func writeTemplateFile(t *testing.T, dir, name, content string) string { + t.Helper() + + path := filepath.Join(dir, name) + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatalf("write template: %v", err) + } + return path +} + +// templateFatalCase is one log.Fatalf path in template processing. run sets up its fixtures and makes the +// fatal call; it runs only in the re-executed child, which must exit 1 with wantErr on stderr. +type templateFatalCase struct { + name string + skipRoot bool + run func(t *testing.T) + wantErr string +} + +var templateFatalCases = []templateFatalCase{ + { + name: "missing-src", + run: func(t *testing.T) { + src := filepath.Join(t.TempDir(), "missing.tmpl") + processTemplates([]string{src + ":" + filepath.Join(t.TempDir(), "out")}) + }, + wantErr: "unable to stat", + }, + { + name: "dir-dest-missing", + run: func(t *testing.T) { + srcDir := t.TempDir() + writeTemplateFile(t, srcDir, "a.tmpl", "a") + processTemplates([]string{srcDir + ":" + filepath.Join(t.TempDir(), "missing")}) + }, + wantErr: "unable to stat", + }, + { + name: "dir-dest-is-file", + run: func(t *testing.T) { + srcDir := t.TempDir() + writeTemplateFile(t, srcDir, "a.tmpl", "a") + destFile := writeTemplateFile(t, t.TempDir(), "dest", "") + processTemplates([]string{srcDir + ":" + destFile}) + }, + wantErr: "if template is a directory, dest must also be a directory", + }, + { + name: "dir-unreadable", + skipRoot: true, + run: func(t *testing.T) { + srcDir := filepath.Join(t.TempDir(), "tmpl") + if err := os.Mkdir(srcDir, 0o755); err != nil { + t.Fatalf("mkdir: %v", err) + } + writeTemplateFile(t, srcDir, "a.tmpl", "a") + if err := os.Chmod(srcDir, 0); err != nil { + t.Fatalf("chmod: %v", err) + } + processTemplates([]string{srcDir + ":" + t.TempDir()}) + }, + wantErr: "bad directory", + }, + { + name: "parse-url", + run: func(t *testing.T) { + _ = parseUrl("http://[::1") + }, + wantErr: "unable to parse url", + }, + { + name: "template-syntax", + run: func(t *testing.T) { + src := writeTemplateFile(t, t.TempDir(), "bad.tmpl", "{{ if }}") + processTemplates([]string{src + ":" + filepath.Join(t.TempDir(), "out")}) + }, + wantErr: "unable to parse template", + }, + { + name: "template-exec", + run: func(t *testing.T) { + // add takes ints, so passing a string fails at execution. + src := writeTemplateFile(t, t.TempDir(), "bad.tmpl", `{{ add "a" 1 }}`) + processTemplates([]string{src + ":" + filepath.Join(t.TempDir(), "out")}) + }, + wantErr: "template error", + }, +} + +func TestTemplateFatalPaths(t *testing.T) { + for _, tc := range templateFatalCases { + if fatalCase(tc.name) { + tc.run(t) + return + } + } + + for _, tc := range templateFatalCases { + t.Run(tc.name, func(t *testing.T) { + if tc.skipRoot && os.Getuid() == 0 { + t.Skip("unreadable directory is readable to root") + } + + exitCode, stderr := runFatalCase(t, "TestTemplateFatalPaths", tc.name) + assert.Equal(t, 1, exitCode) + assert.Contains(t, stderr, tc.wantErr) + }) + } +} + +func TestProcessTemplatesSplitsDestOnFirstColon(t *testing.T) { + resetGlobals(t) + delims = nil + noOverwriteFlag = false + + tempDir := t.TempDir() + src := writeTemplateFile(t, tempDir, "config.tmpl", "{{ lower \"OK\" }}") + dest := filepath.Join(tempDir, "a:b.out") + + processTemplates([]string{src + ":" + dest}) + + got, err := os.ReadFile(dest) + require.NoError(t, err) + assert.Equal(t, "ok", string(got)) +} diff --git a/template_test.go b/template_test.go index 6bebc84..85d788c 100644 --- a/template_test.go +++ b/template_test.go @@ -11,13 +11,7 @@ import ( ) func TestGenerateFileRendersTemplateFunctions(t *testing.T) { - oldDelims := delims - oldNoOverwrite := noOverwriteFlag - defer func() { - delims = oldDelims - noOverwriteFlag = oldNoOverwrite - }() - + resetGlobals(t) delims = nil noOverwriteFlag = false @@ -46,13 +40,7 @@ func TestGenerateFileRendersTemplateFunctions(t *testing.T) { } func TestGenerateFileUsesCustomDelimiters(t *testing.T) { - oldDelims := delims - oldNoOverwrite := noOverwriteFlag - defer func() { - delims = oldDelims - noOverwriteFlag = oldNoOverwrite - }() - + resetGlobals(t) delims = []string{"[[", "]]"} noOverwriteFlag = false @@ -79,13 +67,7 @@ func TestGenerateFileUsesCustomDelimiters(t *testing.T) { } func TestGenerateFileNoOverwrite(t *testing.T) { - oldDelims := delims - oldNoOverwrite := noOverwriteFlag - defer func() { - delims = oldDelims - noOverwriteFlag = oldNoOverwrite - }() - + resetGlobals(t) delims = nil noOverwriteFlag = true @@ -115,13 +97,7 @@ func TestGenerateFileNoOverwrite(t *testing.T) { } func TestGenerateFileDefaultDoesNotPanicOnNonStringValue(t *testing.T) { - oldDelims := delims - oldNoOverwrite := noOverwriteFlag - defer func() { - delims = oldDelims - noOverwriteFlag = oldNoOverwrite - }() - + resetGlobals(t) delims = nil noOverwriteFlag = false @@ -143,6 +119,8 @@ func TestGenerateFileDefaultDoesNotPanicOnNonStringValue(t *testing.T) { } func TestExistsErrorIncludesFilePath(t *testing.T) { + t.Parallel() + // A path through a regular file fails with ENOTDIR rather than ENOENT, // regardless of the user running the test. file := filepath.Join(t.TempDir(), "file") @@ -161,6 +139,8 @@ func TestExistsErrorIncludesFilePath(t *testing.T) { } func TestJSONQueryErrorsIncludeContext(t *testing.T) { + t.Parallel() + tests := []struct { name string jsonObj string @@ -197,6 +177,8 @@ func TestJSONQueryErrorsIncludeContext(t *testing.T) { } func TestLoopChannelConsumesAllProducedValuesInOrder(t *testing.T) { + t.Parallel() + ch, err := loop(1, 10, 3) if err != nil { t.Fatalf("loop returned error: %v", err) @@ -219,13 +201,7 @@ func TestLoopChannelConsumesAllProducedValuesInOrder(t *testing.T) { } func TestGenerateDirRendersAllTemplates(t *testing.T) { - oldDelims := delims - oldNoOverwrite := noOverwriteFlag - defer func() { - delims = oldDelims - noOverwriteFlag = oldNoOverwrite - }() - + resetGlobals(t) delims = nil noOverwriteFlag = false diff --git a/testhelpers_test.go b/testhelpers_test.go new file mode 100644 index 0000000..8cde215 --- /dev/null +++ b/testhelpers_test.go @@ -0,0 +1,98 @@ +package main + +import ( + "bytes" + "context" + "errors" + "log" + "os" + "os/exec" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +// fatalCaseEnv names the environment variable that selects a log.Fatalf case in a re-executed test binary. +const fatalCaseEnv = "DOCKERIZE_FATAL_CASE" + +// resetGlobals snapshots the package globals tests mutate, resets wg, and restores the snapshot in t.Cleanup. +// Tests that call it must not run in parallel. +func resetGlobals(t *testing.T) { + t.Helper() + + oldVersion, oldPoll := version, poll + oldDelims, oldHeaders, oldURLs := delims, headers, urls + oldWaitFlag, oldWaitTimeout, oldWaitRetry := waitFlag, waitTimeoutFlag, waitRetryInterval + oldDialTimeout, oldNoOverwrite := dialTimeout, noOverwriteFlag + oldCtx, oldCancel := ctx, cancel + + t.Cleanup(func() { + version, poll = oldVersion, oldPoll + delims, headers, urls = oldDelims, oldHeaders, oldURLs + waitFlag, waitTimeoutFlag, waitRetryInterval = oldWaitFlag, oldWaitTimeout, oldWaitRetry + dialTimeout, noOverwriteFlag = oldDialTimeout, oldNoOverwrite + ctx, cancel = oldCtx, oldCancel + wg = sync.WaitGroup{} + }) + + wg = sync.WaitGroup{} +} + +// runFatalCase re-runs testName in a child test binary with caseName set, returning its exit code and stderr. +// The child runs the case body guarded by fatalCase(caseName). +func runFatalCase(t *testing.T, testName, caseName string) (int, string) { + t.Helper() + + runCtx, cancelRun := context.WithTimeout(context.Background(), 10*time.Second) + defer cancelRun() + + cmd := exec.CommandContext(runCtx, os.Args[0], "-test.run=^"+testName+"$") + cmd.Env = append(os.Environ(), fatalCaseEnv+"="+caseName) + var stderr bytes.Buffer + cmd.Stderr = &stderr + + err := cmd.Run() + if runCtx.Err() != nil { + t.Fatalf("fatal case %q timed out", caseName) + } + + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return exitErr.ExitCode(), stderr.String() + } + if err != nil { + t.Fatalf("run fatal case %q: %v", caseName, err) + } + return 0, stderr.String() +} + +// fatalCase reports whether this process is the child re-run selected for name. +func fatalCase(name string) bool { + return os.Getenv(fatalCaseEnv) == name +} + +func TestResetGlobalsRestoresPackageState(t *testing.T) { + before := waitTimeoutFlag + beforeNoOverwrite := noOverwriteFlag + + t.Run("mutates", func(t *testing.T) { + resetGlobals(t) + waitTimeoutFlag = before + time.Hour + noOverwriteFlag = !beforeNoOverwrite + }) + + assert.Equal(t, before, waitTimeoutFlag) + assert.Equal(t, beforeNoOverwrite, noOverwriteFlag) +} + +func TestRunFatalCaseCapturesLogFatalf(t *testing.T) { + if fatalCase("boom") { + log.Fatalf("boom") + } + + exitCode, stderr := runFatalCase(t, "TestRunFatalCaseCapturesLogFatalf", "boom") + assert.Equal(t, 1, exitCode) + assert.Contains(t, stderr, "boom") +} diff --git a/wait_deps_test.go b/wait_deps_test.go new file mode 100644 index 0000000..33e7137 --- /dev/null +++ b/wait_deps_test.go @@ -0,0 +1,124 @@ +package main + +import ( + "net" + "net/url" + "path/filepath" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// closedTCPPort returns a local TCP port with nothing listening on it. +func closedTCPPort(t *testing.T) int { + t.Helper() + + l, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + port := l.Addr().(*net.TCPAddr).Port + require.NoError(t, l.Close()) + return port +} + +// waitForDependenciesReturns runs waitForDependencies and fails the test if it does not return within d. +func waitForDependenciesReturns(t *testing.T, d time.Duration) { + t.Helper() + + done := make(chan struct{}) + go func() { + defer close(done) + waitForDependencies() + }() + + select { + case <-done: + case <-time.After(d): + t.Fatalf("waitForDependencies did not return within %s", d) + } +} + +func TestWaitForDependenciesUnsupportedSchemeFatal(t *testing.T) { + if fatalCase("unsupported-scheme") { + waitTimeoutFlag = 10 * time.Second + waitRetryInterval = 10 * time.Millisecond + urls = []url.URL{{Scheme: "ftp", Host: "x"}} + waitForDependencies() + return + } + + exitCode, stderr := runFatalCase(t, "TestWaitForDependenciesUnsupportedSchemeFatal", "unsupported-scheme") + assert.Equal(t, 1, exitCode) + assert.Contains(t, stderr, "invalid host protocol provided: ftp") +} + +func TestWaitForDependenciesTimeoutFatal(t *testing.T) { + if fatalCase("timeout") { + port := closedTCPPort(t) + waitTimeoutFlag = 300 * time.Millisecond + waitRetryInterval = 10 * time.Millisecond + urls = []url.URL{{Scheme: "tcp", Host: "127.0.0.1:" + strconv.Itoa(port)}} + waitForDependencies() + return + } + + exitCode, stderr := runFatalCase(t, "TestWaitForDependenciesTimeoutFatal", "timeout") + assert.Equal(t, 1, exitCode) + assert.Contains(t, stderr, "Timeout after") +} + +func TestWaitForDependenciesUnixSocket(t *testing.T) { + resetGlobals(t) + + sockPath := filepath.Join(t.TempDir(), "s.sock") + l, err := net.Listen("unix", sockPath) + require.NoError(t, err) + defer func() { _ = l.Close() }() + + u, err := url.Parse("unix://" + sockPath) + require.NoError(t, err) + + urls = []url.URL{*u} + waitTimeoutFlag = 5 * time.Second + waitRetryInterval = 10 * time.Millisecond + + waitForDependenciesReturns(t, 10*time.Second) +} + +func TestWaitForDependenciesTCP4(t *testing.T) { + resetGlobals(t) + + l, err := net.Listen("tcp4", "127.0.0.1:0") + require.NoError(t, err) + defer func() { _ = l.Close() }() + + u, err := url.Parse("tcp4://" + l.Addr().String()) + require.NoError(t, err) + + urls = []url.URL{*u} + waitTimeoutFlag = 5 * time.Second + waitRetryInterval = 10 * time.Millisecond + + waitForDependenciesReturns(t, 10*time.Second) +} + +func TestWaitForDependenciesTCP6(t *testing.T) { + l, err := net.Listen("tcp6", "[::1]:0") + if err != nil { + t.Skipf("IPv6 loopback not available: %v", err) + } + defer func() { _ = l.Close() }() + + resetGlobals(t) + + u, err := url.Parse("tcp6://" + l.Addr().String()) + require.NoError(t, err) + + urls = []url.URL{*u} + waitTimeoutFlag = 5 * time.Second + waitRetryInterval = 10 * time.Millisecond + + waitForDependenciesReturns(t, 10*time.Second) +} diff --git a/wait_http_test.go b/wait_http_test.go new file mode 100644 index 0000000..27bcf6a --- /dev/null +++ b/wait_http_test.go @@ -0,0 +1,147 @@ +package main + +import ( + "log" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// waitGroupDone returns a channel that is closed once wg is done. +func waitGroupDone() <-chan struct{} { + done := make(chan struct{}) + go func() { + defer close(done) + wg.Wait() + }() + return done +} + +// within reports whether done is closed within d. +func within(done <-chan struct{}, d time.Duration) bool { + select { + case <-done: + return true + case <-time.After(d): + return false + } +} + +func TestWaitForHTTPInvalidURLDoesNotPanic(t *testing.T) { + // The retry goroutine never ends on its own, so the case runs in a child process. + // Without the fix, the nil request panics in the child and the exit code is not 0. + if fatalCase("invalid-url") { + // The child process exits when the test returns, so it does not restore globals or the log output. + waitTimeoutFlag = 10 * time.Second + waitRetryInterval = 10 * time.Millisecond + var logs syncBuffer + log.SetOutput(&logs) + + // A control character in the host makes url.Parse fail inside http.NewRequest. + waitForHTTP(url.URL{Scheme: "http", Host: "bad\x7fhost"}) + + deadline := time.Now().Add(5 * time.Second) + for strings.Count(logs.String(), "Problem creating request") < 2 { + if time.Now().After(deadline) { + t.Fatalf("expected at least two retries, got logs: %q", logs.String()) + } + time.Sleep(5 * time.Millisecond) + } + return + } + + exitCode, stderr := runFatalCase(t, "TestWaitForHTTPInvalidURLDoesNotPanic", "invalid-url") + assert.Equal(t, 0, exitCode) + assert.NotContains(t, stderr, "panic:") +} + +func TestWaitForHTTPStatusCodes(t *testing.T) { + tests := []struct { + name string + code int + wantRetry bool + }{ + {name: "200 succeeds", code: http.StatusOK}, + {name: "204 succeeds", code: http.StatusNoContent}, + {name: "301 without Location retries", code: http.StatusMovedPermanently, wantRetry: true}, + {name: "404 retries", code: http.StatusNotFound, wantRetry: true}, + {name: "500 retries", code: http.StatusInternalServerError, wantRetry: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resetGlobals(t) + waitTimeoutFlag = 5 * time.Second + waitRetryInterval = 10 * time.Millisecond + logs := captureLog(t) + + var code atomic.Int32 + var hits atomic.Int32 + code.Store(int32(tt.code)) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.WriteHeader(int(code.Load())) + })) + defer srv.Close() + + u, err := url.Parse(srv.URL) + require.NoError(t, err) + + waitForHTTP(*u) + done := waitGroupDone() + + finalCode := tt.code + if tt.wantRetry { + require.Eventually(t, func() bool { return hits.Load() > 1 }, 5*time.Second, 5*time.Millisecond) + assert.Contains(t, logs.String(), "Received "+strconv.Itoa(tt.code)+" from") + assert.False(t, within(done, 50*time.Millisecond), "waitForHTTP returned on status %d", tt.code) + + finalCode = http.StatusOK + code.Store(int32(finalCode)) + } + + require.True(t, within(done, 5*time.Second), "waitForHTTP did not return after status %d", tt.code) + assert.Contains(t, logs.String(), "Received "+strconv.Itoa(finalCode)+" from") + }) + } +} + +func TestWaitForHTTPSendsHeaders(t *testing.T) { + resetGlobals(t) + waitTimeoutFlag = 5 * time.Second + waitRetryInterval = 10 * time.Millisecond + captureLog(t) + + headers = []HttpHeader{ + {name: "X-Test-One", value: "first"}, + {name: "X-Test-Two", value: "second"}, + } + + got := make(chan http.Header, 1) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case got <- r.Header.Clone(): + default: + } + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + + u, err := url.Parse(srv.URL) + require.NoError(t, err) + + waitForHTTP(*u) + require.True(t, within(waitGroupDone(), 5*time.Second), "waitForHTTP did not return") + + h := <-got + assert.Equal(t, "first", h.Get("X-Test-One")) + assert.Equal(t, "second", h.Get("X-Test-Two")) +}