Skip to content
Merged
4 changes: 1 addition & 3 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
version: "2"

linters:
disable:
# TODO: Re-enable after fixing pre-existing unchecked error returns
- errcheck
enable:
- errcheck
- govet
- ineffassign
- staticcheck
Expand Down
74 changes: 45 additions & 29 deletions e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func TestMain(m *testing.M) {
if err != nil {
log.Fatalf("failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
defer func() { _ = os.RemoveAll(tmpDir) }()

dockerizeBin = filepath.Join(tmpDir, "dockerize")

Expand Down Expand Up @@ -103,7 +103,7 @@ func TestTemplateBasic(t *testing.T) {
tmplFile := filepath.Join(dir, "test.tmpl")
destFile := filepath.Join(dir, "output.conf")

os.WriteFile(tmplFile, []byte(`server {{ .Env.TEST_HOST }}:{{ .Env.TEST_PORT }}`), 0644)
writeFile(t, tmplFile, []byte(`server {{ .Env.TEST_HOST }}:{{ .Env.TEST_PORT }}`))

cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile)
cmd.Env = append(os.Environ(), "TEST_HOST=localhost", "TEST_PORT=8080")
Expand All @@ -122,7 +122,7 @@ func TestTemplateBasic(t *testing.T) {
func TestTemplateToStdout(t *testing.T) {
dir := t.TempDir()
tmplFile := filepath.Join(dir, "hello.tmpl")
os.WriteFile(tmplFile, []byte(`hello {{ .Env.NAME }}`), 0644)
writeFile(t, tmplFile, []byte(`hello {{ .Env.NAME }}`))

cmd := exec.Command(dockerizeBin, "-template", tmplFile)
cmd.Env = append(os.Environ(), "NAME=world")
Expand All @@ -141,7 +141,7 @@ func TestTemplateCustomDelims(t *testing.T) {
tmplFile := filepath.Join(dir, "custom.tmpl")
destFile := filepath.Join(dir, "output.txt")

os.WriteFile(tmplFile, []byte(`value=<% .Env.MY_VAR %>`), 0644)
writeFile(t, tmplFile, []byte(`value=<% .Env.MY_VAR %>`))

cmd := exec.Command(dockerizeBin, "-delims", "<%:%>", "-template", tmplFile+":"+destFile)
cmd.Env = append(os.Environ(), "MY_VAR=custom_delims_work")
Expand All @@ -161,8 +161,8 @@ func TestTemplateNoOverwrite(t *testing.T) {
tmplFile := filepath.Join(dir, "tmpl.tmpl")
destFile := filepath.Join(dir, "dest.txt")

os.WriteFile(tmplFile, []byte(`new content`), 0644)
os.WriteFile(destFile, []byte(`original content`), 0644)
writeFile(t, tmplFile, []byte(`new content`))
writeFile(t, destFile, []byte(`original content`))

cmd := exec.Command(dockerizeBin, "-no-overwrite", "-template", tmplFile+":"+destFile)
out, err := cmd.CombinedOutput()
Expand All @@ -180,11 +180,11 @@ func TestTemplateDirectory(t *testing.T) {
dir := t.TempDir()
tmplDir := filepath.Join(dir, "templates")
destDir := filepath.Join(dir, "output")
os.MkdirAll(tmplDir, 0755)
os.MkdirAll(destDir, 0755)
mkdirAll(t, tmplDir)
mkdirAll(t, destDir)

os.WriteFile(filepath.Join(tmplDir, "a.conf"), []byte(`a={{ .Env.A }}`), 0644)
os.WriteFile(filepath.Join(tmplDir, "b.conf"), []byte(`b={{ .Env.B }}`), 0644)
writeFile(t, filepath.Join(tmplDir, "a.conf"), []byte(`a={{ .Env.A }}`))
writeFile(t, filepath.Join(tmplDir, "b.conf"), []byte(`b={{ .Env.B }}`))

cmd := exec.Command(dockerizeBin, "-template", tmplDir+":"+destDir)
cmd.Env = append(os.Environ(), "A=alpha", "B=beta")
Expand All @@ -209,7 +209,7 @@ func TestTemplateSprigFunctions(t *testing.T) {
destFile := filepath.Join(dir, "out.txt")

tmpl := `{{ .Env.GREETING | upper }}_{{ " padded " | trimAll " " }}`
os.WriteFile(tmplFile, []byte(tmpl), 0644)
writeFile(t, tmplFile, []byte(tmpl))

cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile)
cmd.Env = append(os.Environ(), "GREETING=hello")
Expand All @@ -230,7 +230,7 @@ func TestStdoutTail(t *testing.T) {
dir := t.TempDir()
logFile := filepath.Join(dir, "app.log")

os.WriteFile(logFile, []byte("line1\nline2\n"), 0644)
writeFile(t, logFile, []byte("line1\nline2\n"))

cmd := exec.Command(dockerizeBin, "-stdout", logFile, "-poll", "sh", "-c", "sleep 0.5")
out, err := cmd.CombinedOutput()
Expand All @@ -247,7 +247,7 @@ func TestStdoutTail(t *testing.T) {
func TestStderrTail(t *testing.T) {
dir := t.TempDir()
logFile := filepath.Join(dir, "error.log")
os.WriteFile(logFile, []byte("err1\nerr2\n"), 0644)
writeFile(t, logFile, []byte("err1\nerr2\n"))

cmd := exec.Command(dockerizeBin, "-stderr", logFile, "-poll", "sh", "-c", "sleep 0.5")
var stderr bytes.Buffer
Expand All @@ -270,7 +270,7 @@ func TestWaitTCP(t *testing.T) {
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer ln.Close()
t.Cleanup(func() { _ = ln.Close() })

addr := ln.Addr().String()

Expand Down Expand Up @@ -349,7 +349,7 @@ func TestWaitFile(t *testing.T) {

go func() {
time.Sleep(1 * time.Second)
os.WriteFile(waitFile, []byte("ok"), 0644)
_ = os.WriteFile(waitFile, []byte("ok"), 0644)
}()

cmd := exec.Command(dockerizeBin, "-wait", "file://"+waitFile, "-timeout", "5s", "echo", "file-ready")
Expand All @@ -372,8 +372,8 @@ func TestWaitMultiple(t *testing.T) {
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
defer ln1.Close()
defer ln2.Close()
t.Cleanup(func() { _ = ln1.Close() })
t.Cleanup(func() { _ = ln2.Close() })

cmd := exec.Command(dockerizeBin,
"-wait", "tcp://"+ln1.Addr().String(),
Expand Down Expand Up @@ -476,7 +476,7 @@ func TestTemplateEnvContext(t *testing.T) {
destFile := filepath.Join(dir, "out.txt")

tmpl := `host={{ .Env.DB_HOST }} port={{ .Env.DB_PORT }} pass={{ .Env.DB_PASS }}`
os.WriteFile(tmplFile, []byte(tmpl), 0644)
writeFile(t, tmplFile, []byte(tmpl))

cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile)
cmd.Env = append(os.Environ(), "DB_HOST=pg.local", "DB_PORT=5432", "DB_PASS=p@ss=w0rd!")
Expand All @@ -499,7 +499,7 @@ func TestTemplateEnvRange(t *testing.T) {

// Range over .Env filtering by prefix
tmpl := `{{ range $k, $v := .Env }}{{ if hasPrefix "MYAPP_" $k }}{{ $k }}={{ $v }}` + "\n" + `{{ end }}{{ end }}`
os.WriteFile(tmplFile, []byte(tmpl), 0644)
writeFile(t, tmplFile, []byte(tmpl))

cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile)
cmd.Env = []string{"MYAPP_HOST=web1", "MYAPP_PORT=9090", "OTHER_VAR=ignore"}
Expand All @@ -523,7 +523,7 @@ func TestTemplateEnvMissing(t *testing.T) {
destFile := filepath.Join(dir, "out.txt")

tmpl := `before[{{ .Env.DEFINITELY_NOT_SET }}]after`
os.WriteFile(tmplFile, []byte(tmpl), 0644)
writeFile(t, tmplFile, []byte(tmpl))

cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile)
// Deliberately don't set DEFINITELY_NOT_SET
Expand All @@ -547,7 +547,7 @@ func TestTemplateFuncDefault(t *testing.T) {
destFile := filepath.Join(dir, "out.txt")

tmpl := `port={{ default .Env.PORT "3000" }}`
os.WriteFile(tmplFile, []byte(tmpl), 0644)
writeFile(t, tmplFile, []byte(tmpl))

// Test with PORT unset — should use default
cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile)
Expand Down Expand Up @@ -580,7 +580,7 @@ func TestTemplateFuncContains(t *testing.T) {
destFile := filepath.Join(dir, "out.txt")

tmpl := `{{ if contains .Env "SECRET" }}has-secret{{ else }}no-secret{{ end }}`
os.WriteFile(tmplFile, []byte(tmpl), 0644)
writeFile(t, tmplFile, []byte(tmpl))

// With SECRET set
cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile)
Expand Down Expand Up @@ -610,15 +610,15 @@ func TestTemplateFuncContains(t *testing.T) {
func TestTemplateFuncExists(t *testing.T) {
dir := t.TempDir()
existingFile := filepath.Join(dir, "present.conf")
os.WriteFile(existingFile, []byte("x"), 0644)
writeFile(t, existingFile, []byte("x"))

tmplFile := filepath.Join(dir, "exists.tmpl")
destFile := filepath.Join(dir, "out.txt")

// exists returns (bool, error) — use with index or assign
tmpl := fmt.Sprintf(`{{ $e := exists "%s" }}{{ $m := exists "%s/absent.conf" }}{{ $e }}-{{ $m }}`,
existingFile, dir)
os.WriteFile(tmplFile, []byte(tmpl), 0644)
writeFile(t, tmplFile, []byte(tmpl))

cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile)
cmd.Env = os.Environ()
Expand All @@ -643,7 +643,7 @@ replaced={{ replace .Env.GREETING "hello" "hi" 1 }}
lower={{ lower .Env.UPPER }}
upper={{ upper .Env.LOWER }}
sum={{ add (atoi .Env.A) (atoi .Env.B) }}`
os.WriteFile(tmplFile, []byte(tmpl), 0644)
writeFile(t, tmplFile, []byte(tmpl))

cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile)
cmd.Env = []string{"CSV=one,two,three", "GREETING=hello world", "UPPER=LOUD", "LOWER=quiet", "A=10", "B=32"}
Expand All @@ -665,7 +665,7 @@ func TestTemplateFuncParseUrl(t *testing.T) {
destFile := filepath.Join(dir, "out.txt")

tmpl := `{{ $u := parseUrl .Env.DATABASE_URL }}host={{ $u.Host }} scheme={{ $u.Scheme }} path={{ $u.Path }}`
os.WriteFile(tmplFile, []byte(tmpl), 0644)
writeFile(t, tmplFile, []byte(tmpl))

cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile)
cmd.Env = []string{"DATABASE_URL=postgres://db.example.com:5432/mydb"}
Expand All @@ -687,7 +687,7 @@ func TestTemplateFuncIsTrue(t *testing.T) {
destFile := filepath.Join(dir, "out.txt")

tmpl := `{{ if isTrue .Env.ENABLED }}on{{ else }}off{{ end }}-{{ if isTrue .Env.DISABLED }}on{{ else }}off{{ end }}`
os.WriteFile(tmplFile, []byte(tmpl), 0644)
writeFile(t, tmplFile, []byte(tmpl))

tests := []struct {
enabled string
Expand Down Expand Up @@ -723,7 +723,7 @@ func TestTemplateFuncJsonQuery(t *testing.T) {
destFile := filepath.Join(dir, "out.txt")

tmpl := `name={{ jsonQuery .Env.CONFIG "name" }} version={{ jsonQuery .Env.CONFIG "version" }}`
os.WriteFile(tmplFile, []byte(tmpl), 0644)
writeFile(t, tmplFile, []byte(tmpl))

jsonVal := `{"name":"myapp","version":"1.2.3"}`
cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile)
Expand All @@ -749,7 +749,7 @@ func TestTemplateFuncLoop(t *testing.T) {
tmpl := `a={{ range $i := loop 3 }}{{ $i }}{{ end }}
b={{ range $i := loop 2 5 }}{{ $i }}{{ end }}
c={{ range $i := loop 0 10 3 }}{{ $i }}{{ end }}`
os.WriteFile(tmplFile, []byte(tmpl), 0644)
writeFile(t, tmplFile, []byte(tmpl))

cmd := exec.Command(dockerizeBin, "-template", tmplFile+":"+destFile)
cmd.Env = []string{"HOME=/tmp"}
Expand All @@ -764,3 +764,19 @@ c={{ range $i := loop 0 10 3 }}{{ $i }}{{ end }}`
t.Fatalf("expected:\n%s\ngot:\n%s", expected, string(got))
}
}

// writeFile writes data to name, failing the test if it cannot be written.
func writeFile(t *testing.T, name string, data []byte) {
t.Helper()
if err := os.WriteFile(name, data, 0644); err != nil {
t.Fatalf("failed to write %s: %v", name, err)
}
}

// mkdirAll creates path and any missing parents, failing the test on error.
func mkdirAll(t *testing.T, path string) {
t.Helper()
if err := os.MkdirAll(path, 0755); err != nil {
t.Fatalf("failed to create %s: %v", path, err)
}
}
12 changes: 9 additions & 3 deletions exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,15 @@ func runCmd(ctx context.Context, cancel context.CancelFunc, cmd string, args ...
}

func signalProcessWithTimeout(process *exec.Cmd, sig os.Signal, waitDone ...<-chan struct{}) {
process.Process.Signal(sig) // pretty sure this doesn't do anything. It seems like the signal is automatically sent to the command?
// 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) {
log.Printf("Error sending signal to command: %s\n", err)
}
if len(waitDone) == 0 {
done := make(chan struct{})
go func() {
process.Wait()
// Only signals completion; the caller's own Wait reports the exit status.
_ = process.Wait()
close(done)
}()
waitDone = []<-chan struct{}{done}
Expand All @@ -81,6 +85,8 @@ func signalProcessWithTimeout(process *exec.Cmd, sig os.Signal, waitDone ...<-ch
return
case <-time.After(10 * time.Second):
log.Println("Killing command due to timeout.")
process.Process.Kill()
if err := process.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
log.Printf("Error killing command: %s\n", err)
}
}
}
62 changes: 59 additions & 3 deletions exec_signal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"bytes"
"context"
"log"
"os"
"os/exec"
"strings"
Expand Down Expand Up @@ -39,13 +40,14 @@ func TestRunCmdSignalShutdown(t *testing.T) {
t.Fatalf("signal helper: %v", err)
}

waitErrCh := make(chan error, 1)
waitDone := make(chan struct{})
go func() {
waitErrCh <- cmd.Wait()
_ = cmd.Wait()
close(waitDone)
}()

select {
case <-waitErrCh:
case <-waitDone:
case <-time.After(20 * time.Second):
_ = cmd.Process.Kill()
t.Fatal("timed out waiting for helper to exit")
Expand All @@ -55,3 +57,57 @@ func TestRunCmdSignalShutdown(t *testing.T) {
t.Fatalf("unexpected data race reported: %s", stderr.String())
}
}

func TestSignalProcessWithTimeoutAlreadyExited(t *testing.T) {
cmd := exec.Command("true")
if err := cmd.Run(); err != nil {
t.Fatalf("run command: %v", err)
}

var logBuf bytes.Buffer
prevOutput := log.Writer()
log.SetOutput(&logBuf)
defer log.SetOutput(prevOutput)

done := make(chan struct{})
go func() {
signalProcessWithTimeout(cmd, syscall.SIGTERM)
close(done)
}()

select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("signalProcessWithTimeout did not return for an exited command")
}

if logBuf.Len() != 0 {
t.Errorf("expected no log output, got: %q", logBuf.String())
}
}

func TestSignalProcessWithTimeoutStopsLiveProcess(t *testing.T) {
cmd := exec.Command("sleep", "30")
if err := cmd.Start(); err != nil {
t.Fatalf("start sleep: %v", err)
}

waitDone := make(chan struct{})
go func() {
_ = cmd.Wait()
close(waitDone)
}()

start := time.Now()
signalProcessWithTimeout(cmd, syscall.SIGTERM, waitDone)
if elapsed := time.Since(start); elapsed >= 10*time.Second {
t.Fatalf("signalProcessWithTimeout took %s, expected the signal to stop sleep before the timeout", elapsed)
}

select {
case <-waitDone:
case <-time.After(5 * time.Second):
_ = cmd.Process.Kill()
t.Fatal("sleep was not stopped")
}
}
Loading
Loading