From ec813e86978fb3821b4bc3b9847c31b7a041a7be Mon Sep 17 00:00:00 2001 From: schmidtw Date: Mon, 4 Dec 2023 08:31:16 -0800 Subject: [PATCH 1/3] Transfer working modes. --- go.mod | 10 ++ go.sum | 9 ++ idock.go | 320 ++++++++++++++++++++++++++++++++++++++++++++++++++ idock_test.go | 145 +++++++++++++++++++++++ options.go | 183 +++++++++++++++++++++++++++++ 5 files changed, 667 insertions(+) create mode 100644 go.mod create mode 100644 go.sum create mode 100644 idock.go create mode 100644 idock_test.go create mode 100644 options.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c1d390f --- /dev/null +++ b/go.mod @@ -0,0 +1,10 @@ +module github.com/xmidt-org/idock + +go 1.21.3 + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/testify v1.8.4 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..8cf6655 --- /dev/null +++ b/go.sum @@ -0,0 +1,9 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/idock.go b/idock.go new file mode 100644 index 0000000..be90a9a --- /dev/null +++ b/idock.go @@ -0,0 +1,320 @@ +// SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +// SPDX-License-Identifier: Apache-2.0 + +package idock + +import ( + "context" + "errors" + "fmt" + "net" + "os" + "os/exec" + "testing" + "time" +) + +const ( + // IDOCK_RUN_FLAG is the environment variable that controls whether or not + // to run the integration tests. + RUN_FLAG = "IDOCK_RUN" + + // IDOCK_VERBOSITY_FLAG is the environment variable that controls the + // verbosity of the output. + VERBOSITY_FLAG = "IDOCK_VERBOSITY" + + // DOCKER_MAX_WAIT_FLAG is the environment variable that controls how long + // to wait for the docker-compose program to start. + DOCKER_MAX_WAIT_FLAG = "IDOCK_DOCKER_MAX_WAIT" + + // PROGRAM_MAX_WAIT_FLAG is the environment variable that controls how long + // to wait for the program to start. + PROGRAM_MAX_WAIT_FLAG = "IDOCK_PROGRAM_MAX_WAIT" + + // CLEANUP_RETRIES_FLAG is the environment variable that controls how many + // times to retry the cleanup process. + CLEANUP_RETRIES_FLAG = "IDOCK_CLEANUP_RETRIES" +) + +var ( + errTimedOut = fmt.Errorf("timed out") + errProgramExited = fmt.Errorf("program exited") +) + +// IDock is the main struct for the idock package. +type IDock struct { + tcpPortMaxWait time.Duration + dockerComposeFile string + dockerTCPPorts []int + dockerMaxWait time.Duration + afterDocker func(*IDock) + program func() + programTCPPorts []int + programMaxWait time.Duration + afterProgram func(*IDock) error + cleanupRetries int + localhost string + verbosity int + noDockerCompose bool +} + +// Option is an option interface for the IDock struct. +type Option interface { + apply(*IDock) +} + +type optionFunc func(*IDock) + +func (f optionFunc) apply(c *IDock) { + f(c) +} + +// New creates a new IDock struct with the given options. +func New(opts ...Option) *IDock { + c := &IDock{ + tcpPortMaxWait: 2 * time.Second, + afterDocker: func(*IDock) {}, + program: func() {}, + afterProgram: func(*IDock) error { + return nil + }, + programMaxWait: 2 * time.Second, + localhost: "localhost", + cleanupRetries: 3, + } + + opts = append(opts, []Option{ + verbosity(), + cleanupRetries(), + dockerMaxWait(), + programMaxWait(), + }...) + + for _, opt := range opts { + opt.apply(c) + } + + return c +} + +// Verbosity gets the verbosity level. +func (c *IDock) Verbosity() int { + return c.verbosity +} + +// Run runs the integration tests. +func (c *IDock) Run(m *testing.M) { + if os.Getenv(RUN_FLAG) == "" { + return + } + + code := c.run(m) + + c.Logf(1, "Exiting with code %d\n", code) + + os.Exit(code) +} + +func (c *IDock) startDocker() error { + if c.dockerComposeFile == "" { + c.cleanupRetries = 0 + return nil + } + + args := []string{"-f", c.dockerComposeFile, "up", "-d"} + if c.verbosity > 1 { + args = append([]string{"--verbose"}, args...) + } + + cmd := exec.Command("docker-compose", args...) + + // Some systems don't have docker-compose installed, so try to use the docker-compose + // binary from the docker image instead. + if errors.Is(cmd.Err, exec.ErrNotFound) { + args = append([]string{"compose"}, args...) + cmd = exec.Command("docker", args...) + c.noDockerCompose = true + } + + if c.verbosity > 1 { + cmd.Stderr = os.Stdout + cmd.Stdout = os.Stdout + } + + dockerStart := time.Now() + err := cmd.Start() + if err != nil { + c.cleanupRetries = 0 + return err + } + + c.Logf(1, "Waiting for services to start...\n") + err = c.wait(c.dockerTCPPorts, nil) + if err != nil { + c.Logf(1, "docker-compose services took too long to start (%s)\n", c.dockerMaxWait) + return err + } + dockerReady := time.Now() + c.Logf(1, "docker-compose services took %s to start\n", dockerReady.Sub(dockerStart)) + + return nil +} + +func (c *IDock) run(m *testing.M) int { + err := c.startDocker() + if 0 <= c.cleanupRetries { + defer c.cleanup() + } + if err != nil { + c.Logf(0, "docker startup failed: %s\n", err) + return -1 + } + + if c.afterDocker != nil { + start := time.Now() + c.afterDocker(c) + end := time.Now() + c.Logf(1, "customization after docker took %s\n", end.Sub(start)) + } + + start := time.Now() + done := make(chan struct{}) + c.safelyWrap() + err = c.wait(c.programTCPPorts, done) + end := time.Now() + c.Logf(1, "program startup took %s\n", end.Sub(start)) + + if err != nil { + if errors.Is(err, errProgramExited) { + c.Logf(0, "program exited before services were ready\n") + } else if errors.Is(err, errTimedOut) { + c.Logf(0, "program took too long to start\n") + } else { + c.Logf(0, "program had some unknown error: %s\n", err) + } + return -1 + } + + if c.afterProgram != nil { + start := time.Now() + err = c.afterProgram(c) + end := time.Now() + c.Logf(1, "customization after program took %s\n", end.Sub(start)) + if err != nil { + c.Logf(0, "customization after program started issued an error: %s\n", err) + return -1 + } + } + + c.Logf(2, "running the tests\n") + return m.Run() +} + +func (c *IDock) isPortOpen(ctx context.Context, port int) bool { + var d net.Dialer + + address := fmt.Sprintf("%s:%d", c.localhost, port) + + conn, err := d.DialContext(ctx, "tcp", address) + if err != nil { + return false + } + conn.Close() + + return true +} + +func (c *IDock) wait(ports []int, timeout time.Duration) error { + ctx, cancel := context.WithTimeout(context.Background(), c.dockerMaxWait) + defer cancel() + for { + select { + case <-done: + return errProgramExited + case <-ctx.Done(): + return errTimedOut + default: + allOpen := true + for _, port := range ports { + //shortctx, shortCancel := context.WithTimeout(ctx, c.tcpPortMaxWait) + open := c.isPortOpen(ctx, port) + if !open { + c.Logf(1, "Checking port %d - not responding\n", port) + allOpen = false + break + } else { + c.Logf(2, "Checking port %d - responding\n", port) + } + } + if allOpen { + goto done + } + } + time.Sleep(100 * time.Millisecond) + } + +done: + c.Logf(1, "All services are ready.\n") + return nil +} + +// Logf prints a message if the verbosity level is greater than or equal to the +// given level. +func (c *IDock) Logf(level int, format string, a ...any) { + if level <= c.verbosity { + return + } + fmt.Printf(format, a...) +} + +func (c *IDock) cleanup() { + c.Logf(1, "Cleaning up...\n") + + var cmd *exec.Cmd + if c.noDockerCompose { + cmd = exec.Command("docker", "compose", "-f", c.dockerComposeFile, "down", "--remove-orphans") + } else { + cmd = exec.Command("docker-compose", "-f", c.dockerComposeFile, "down", "--remove-orphans") + } + + if c.verbosity > 1 { + cmd.Stderr = os.Stdout + cmd.Stdout = os.Stdout + } + + for i := 0; i < c.cleanupRetries; i++ { + err := cmd.Run() + if err == nil { + return + } + c.Logf(1, "Failed to clean up docker-compose services on try %d: %s\n", i+1, err) + } + + fmt.Printf("Failed to clean up docker services. Please run `docker-compose down --remove-orphans` manually\n") +} + +func (c *IDock) safelyWrap() bool { + ctx, cancel := context.WithTimeout(context.Background(), c.programMaxWait) + defer cancel() + + failure := make(chan bool) + go func() { + defer func() { + if r := recover(); r != nil { + fmt.Println("recovered from panic") + fmt.Println(r) + failure <- true + } + }() + + c.program() + }() + + select { + case <-failure: + return success + case <-ctx.Done(): + // The program started and didn't fail in the given time, so return true. + return true + } +} diff --git a/idock_test.go b/idock_test.go new file mode 100644 index 0000000..b1fd3ee --- /dev/null +++ b/idock_test.go @@ -0,0 +1,145 @@ +// SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +// SPDX-License-Identifier: Apache-2.0 + +package idock + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestIDock_safelyWrap(t *testing.T) { + tests := []struct { + description string + have IDock + expect bool + }{ + { + description: "program returns", + have: IDock{ + program: func() {}, + programMaxWait: time.Second, + }, + expect: true, + }, { + description: "program panics", + have: IDock{ + program: func() { panic("program panics") }, + programMaxWait: time.Second, + }, + }, { + expect: true, + description: "program never returns", + have: IDock{ + program: func() { + for { + time.Sleep(time.Second) + } + }, + programMaxWait: time.Second, + }, + }, + } + for _, tc := range tests { + t.Run(tc.description, func(t *testing.T) { + assert := assert.New(t) + got := tc.have.safelyWrap() + assert.Equal(tc.expect, got) + }) + } +} + +func TestIDock_isPortOpen(t *testing.T) { + tests := []struct { + description string + wait time.Duration + expect bool + }{ + { + description: "port is not open", + wait: 100 * time.Millisecond, + }, { + description: "port is open", + wait: 100 * time.Millisecond, + expect: true, + }, + } + for _, tc := range tests { + t.Run(tc.description, func(t *testing.T) { + assert := assert.New(t) + require := require.New(t) + + authority := "localhost" + port := 51 // probably not used + + if tc.expect { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + w.Write([]byte("Mock response")) + })) + defer server.Close() + + u, err := url.Parse(server.URL) + require.NoError(err) + authority = u.Hostname() + port, err = strconv.Atoi(u.Port()) + require.NoError(err) + } + c := &IDock{ + localhost: authority, + } + + ctx, cancel := context.WithTimeout(context.Background(), tc.wait) + defer cancel() + + assert.Equal(tc.expect, c.isPortOpen(ctx, port)) + }) + } +} + +func TestIDock_wait(t *testing.T) { + tests := []struct { + description string + ports []int + done chan struct{} + expectedErr error + }{ + { + description: "", + // TODO: Add test cases. + }, + } + for _, tc := range tests { + t.Run(tc.description, func(t *testing.T) { + assert := assert.New(t) + require := require.New(t) + c := &IDock{ + tcpPortMaxWait: tc.fields.tcpPortMaxWait, + dockerComposeFile: tc.fields.dockerComposeFile, + dockerTCPPorts: tc.fields.dockerTCPPorts, + dockerMaxWait: tc.fields.dockerMaxWait, + afterDocker: tc.fields.afterDocker, + program: tc.fields.program, + programTCPPorts: tc.fields.programTCPPorts, + programMaxWait: tc.fields.programMaxWait, + afterProgram: tc.fields.afterProgram, + cleanupRetries: tc.fields.cleanupRetries, + localhost: tc.fields.localhost, + verbosity: tc.fields.verbosity, + noDockerCompose: tc.fields.noDockerCompose, + } + + err := c.wait(tc.ports, tc.done) + + assert.ErrorIs(err, tc.expectedErr) + }) + } +} diff --git a/options.go b/options.go new file mode 100644 index 0000000..04eba9e --- /dev/null +++ b/options.go @@ -0,0 +1,183 @@ +// SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +// SPDX-License-Identifier: Apache-2.0 + +package idock + +import ( + "fmt" + "os" + "strconv" + "strings" + "time" +) + +// DockerComposeFile sets the docker-compose file to use if docker-compose is +// used. +func DockerComposeFile(file string) Option { + return optionFunc(func(c *IDock) { + c.dockerComposeFile = file + }) +} + +// RequireDockerTCPPorts ensures that the given ports are active before +// continuing on to the next step of starting the program. +func RequireDockerTCPPorts(ports ...int) Option { + return optionFunc(func(c *IDock) { + c.dockerTCPPorts = append(c.dockerTCPPorts, ports...) + }) +} + +// DockerMaxWait sets the maximum amount of time to wait for the docker-compose +// programs to start. +func DockerMaxWait(d time.Duration) Option { + return optionFunc(func(c *IDock) { + if d < 0 { + panic(fmt.Sprintf("dockerMaxWait must be >= 0: %s\n", d)) + } + c.dockerMaxWait = d + }) +} + +// AfterDocker is a function that is called after the docker-compose program +// has started but before the program is started. +func AfterDocker(f func(*IDock)) Option { + return optionFunc(func(c *IDock) { + if f == nil { + f = func(*IDock) {} + } + c.afterDocker = f + }) +} + +// Program is the function that is called to start the program. +func Program(f func()) Option { + return optionFunc(func(c *IDock) { + if f == nil { + f = func() {} + } + c.program = f + }) +} + +// RequireProgramTCPPorts ensures that the given ports are active before +// continuing on to the next step of running the tests. +func RequireProgramTCPPorts(ports ...int) Option { + return optionFunc(func(c *IDock) { + c.programTCPPorts = append(c.programTCPPorts, ports...) + }) +} + +// ProgramMaxWait sets the maximum amount of time to wait for the program to +// start. +// The default value is 2 seconds. +func ProgramMaxWait(d time.Duration) Option { + return optionFunc(func(c *IDock) { + if d < 0 { + panic(fmt.Sprintf("programMaxWait must be >= 0: %s\n", d)) + } + c.programMaxWait = d + }) +} + +// AfterProgram is a function that is called after the program has started but +// before the tests are run. +func AfterProgram(f func(*IDock) error) Option { + return optionFunc(func(c *IDock) { + if f == nil { + f = func(*IDock) error { + return nil + } + } + c.afterProgram = f + }) +} + +// CleanupRetries sets the number of times to retry the cleanup process before +// giving up and leaving any docker containers running. +// The default value is 3. +func CleanupRetries(n int) Option { + return optionFunc(func(c *IDock) { + if n < 0 { + panic(fmt.Sprintf("cleanupRetries must be >= 0: %d\n", n)) + } + c.cleanupRetries = n + }) +} + +// Localhost sets the localhost address to use when connecting to the program. +// The default value of 'localhost' is used. +func Localhost(s string) Option { + return optionFunc(func(c *IDock) { + c.localhost = s + }) +} + +// TCPPortMaxWait sets the maximum amount of time to wait while dialing a TCP +// port. +// The default value is 2 seconds. +func TCPPortMaxWait(d time.Duration) Option { + return optionFunc(func(c *IDock) { + if d < 0 { + panic(fmt.Sprintf("tcpPortMaxWait must be >= 0: %s\n", d)) + } + c.tcpPortMaxWait = d + }) +} + +// verbosity sets the verbosity level based on the environment variable. +func verbosity() Option { + return optionFunc(func(c *IDock) { + c.verbosity = envToInt(VERBOSITY_FLAG, c.verbosity) + }) +} + +// cleanupRetries sets the number of times to retry the cleanup process before +// giving up and leaving any docker containers running based on the environment +// variable. +func cleanupRetries() Option { + return optionFunc(func(c *IDock) { + c.cleanupRetries = envToInt(CLEANUP_RETRIES_FLAG, c.cleanupRetries) + }) +} + +// dockerMaxWait sets the maximum amount of time to wait for the docker-compose +// programs to start based on the environment variable. +func dockerMaxWait() Option { + return optionFunc(func(c *IDock) { + c.dockerMaxWait = envToDuration(DOCKER_MAX_WAIT_FLAG, c.dockerMaxWait) + }) +} + +// programMaxWait sets the maximum amount of time to wait for the program to +// start based on the environment variable. +func programMaxWait() Option { + return optionFunc(func(c *IDock) { + c.programMaxWait = envToDuration(PROGRAM_MAX_WAIT_FLAG, c.programMaxWait) + }) +} + +func envToDuration(name string, def time.Duration) time.Duration { + s := strings.TrimSpace(os.Getenv(name)) + if s == "" { + return def + } + d, err := time.ParseDuration(s) + if err != nil { + panic(fmt.Sprintf("%s having value '%s' must be a duration: %s\n", + name, s, err)) + } + return d +} + +func envToInt(name string, def int) int { + s := strings.TrimSpace(os.Getenv(name)) + if s == "" { + return def + } + n, err := strconv.Atoi(s) + if err != nil { + panic(fmt.Sprintf("%s having value '%s' must be an integer: %s\n", + name, s, err)) + } + return n +} From 29aa4dea23f0faac7c672b87e7d670c98f9ca76c Mon Sep 17 00:00:00 2001 From: schmidtw Date: Tue, 5 Dec 2023 20:48:05 -0800 Subject: [PATCH 2/3] Progress & switching. --- idock.go | 84 +++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 55 insertions(+), 29 deletions(-) diff --git a/idock.go b/idock.go index be90a9a..acecdd0 100644 --- a/idock.go +++ b/idock.go @@ -10,6 +10,8 @@ import ( "net" "os" "os/exec" + "sort" + "sync" "testing" "time" ) @@ -149,7 +151,9 @@ func (c *IDock) startDocker() error { } c.Logf(1, "Waiting for services to start...\n") - err = c.wait(c.dockerTCPPorts, nil) + ctx, cancel := context.WithTimeout(context.Background(), c.dockerMaxWait) + defer cancel() + err = c.wait(ctx, nil) if err != nil { c.Logf(1, "docker-compose services took too long to start (%s)\n", c.dockerMaxWait) return err @@ -180,7 +184,9 @@ func (c *IDock) run(m *testing.M) int { start := time.Now() done := make(chan struct{}) c.safelyWrap() - err = c.wait(c.programTCPPorts, done) + ctx, cancel := context.WithTimeout(context.Background(), c.programMaxWait) + defer cancel() + err = c.wait(ctx, c.programTCPPorts) end := time.Now() c.Logf(1, "program startup took %s\n", end.Sub(start)) @@ -210,50 +216,70 @@ func (c *IDock) run(m *testing.M) int { return m.Run() } -func (c *IDock) isPortOpen(ctx context.Context, port int) bool { +func (c *IDock) isPortOpen(ctx context.Context, port int) (bool, error) { var d net.Dialer address := fmt.Sprintf("%s:%d", c.localhost, port) conn, err := d.DialContext(ctx, "tcp", address) if err != nil { - return false + return false, err } conn.Close() - return true + return true, nil } -func (c *IDock) wait(ports []int, timeout time.Duration) error { - ctx, cancel := context.WithTimeout(context.Background(), c.dockerMaxWait) - defer cancel() - for { - select { - case <-done: - return errProgramExited - case <-ctx.Done(): - return errTimedOut - default: - allOpen := true - for _, port := range ports { - //shortctx, shortCancel := context.WithTimeout(ctx, c.tcpPortMaxWait) - open := c.isPortOpen(ctx, port) - if !open { - c.Logf(1, "Checking port %d - not responding\n", port) - allOpen = false +func (c *IDock) wait(ctx context.Context, ports []int) error { + var wg sync.WaitGroup + + results := make(chan int, len(ports)) + for _, port := range ports { + wg.Add(1) + go func(ctx context.Context, port int) { + for { + sub, cancel := context.WithTimeout(ctx, 10*time.Millisecond) + got, err := c.isPortOpen(sub, port) + cancel() + + if err == nil && got { + results <- port + break + } + if err != nil { + results <- (-1 * port) break - } else { - c.Logf(2, "Checking port %d - responding\n", port) } } - if allOpen { - goto done - } + wg.Done() + }(ctx, port) + } + + wg.Wait() + + succeeded := make([]int, 0, len(ports)) + failed := make([]int, 0, len(ports)) + for result := range results { + if result < 0 { + failed = append(failed, (-1 * result)) + } else { + succeeded = append(succeeded, result) } - time.Sleep(100 * time.Millisecond) } -done: + sort.Ints(succeeded) + for _, port := range succeeded { + c.Logf(1, "Port %d started\n", port) + } + + sort.Ints(failed) + for _, port := range failed { + c.Logf(1, "Port %d failed to start\n", port) + } + if len(failed) > 0 { + return errTimedOut + } + c.Logf(1, "All services are ready.\n") return nil } From 03be7ae0ea0a17dd5d21743ed439454fa40a45b5 Mon Sep 17 00:00:00 2001 From: schmidtw Date: Sun, 10 Dec 2023 11:35:21 -0800 Subject: [PATCH 3/3] The docker compose for testing code is there and working. --- .github/dependabot.yml | 26 ++ .github/workflows/ci.yml | 26 ++ .github/workflows/dependabot-approver.yml | 15 + .github/workflows/proj-xmidt-team.yml | 17 ++ .reuse/dep5 | 36 +++ LICENSE | 73 +++++ LICENSES/Apache-2.0.txt | 73 +++++ MAINTAINERS.md | 4 + docker-compose.yml | 9 + go.mod | 3 +- go.sum | 1 + idock.go | 323 ++++++++++---------- idock_test.go | 349 +++++++++++++++++++--- options.go | 83 +++-- 14 files changed, 818 insertions(+), 220 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/dependabot-approver.yml create mode 100644 .github/workflows/proj-xmidt-team.yml create mode 100644 .reuse/dep5 create mode 100644 LICENSE create mode 100644 LICENSES/Apache-2.0.txt create mode 100644 MAINTAINERS.md create mode 100644 docker-compose.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..9dd02e9 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +# SPDX-License-Identifier: Apache-2.0 + +version: 2 +updates: + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + # Check for updates to GitHub Actions every week + interval: "daily" + labels: + - "dependencies" + commit-message: + prefix: "chore" + include: "scope" + + - package-ecosystem: gomod + directory: / + schedule: + interval: daily + labels: + - "dependencies" + commit-message: + prefix: "feat" + include: "scope" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c9a181c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: 2022 Comcast Cable Communications Management, LLC +# SPDX-License-Identifier: Apache-2.0 +--- +name: CI + +on: + push: + branches: + - main + paths-ignore: + - README.md + - CONTRIBUTING.md + - MAINTAINERS.md + - LICENSE + - NOTICE + tags: + - 'v[0-9]+.[0-9]+.[0-9]+' + pull_request: + workflow_dispatch: + +jobs: + ci: + uses: xmidt-org/shared-go/.github/workflows/ci.yml@d0737af7255c581ce3cc09b69b96ba16a5913b4e # v4.0.0 + with: + release-type: library + secrets: inherit diff --git a/.github/workflows/dependabot-approver.yml b/.github/workflows/dependabot-approver.yml new file mode 100644 index 0000000..073a930 --- /dev/null +++ b/.github/workflows/dependabot-approver.yml @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2022 Comcast Cable Communications Management, LLC +# SPDX-License-Identifier: Apache-2.0 +--- +name: 'Dependabot auto approval' + +on: + pull_request_target +permissions: + pull-requests: write + contents: write + +jobs: + package: + uses: xmidt-org/.github/.github/workflows/dependabot-approver-template.yml@main + secrets: inherit diff --git a/.github/workflows/proj-xmidt-team.yml b/.github/workflows/proj-xmidt-team.yml new file mode 100644 index 0000000..1ccd4ed --- /dev/null +++ b/.github/workflows/proj-xmidt-team.yml @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: 2022 Comcast Cable Communications Management, LLC +# SPDX-License-Identifier: Apache-2.0 +--- +name: 'PROJ: xmidt-team' + +on: + issues: + types: + - opened + pull_request: + types: + - opened + +jobs: + package: + uses: xmidt-org/.github/.github/workflows/proj-template.yml@proj-v1 + secrets: inherit diff --git a/.reuse/dep5 b/.reuse/dep5 new file mode 100644 index 0000000..2fc59da --- /dev/null +++ b/.reuse/dep5 @@ -0,0 +1,36 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: rbus-go +Upstream-Contact: Weston Schmidt +Source: https://github.com/xmidt-org/rbus-go + +Files: CODE_OF_CONDUCT.md +Copyright: SPDX-FileCopyrightText: 2014-2021 Coraline Ada Ehmke and contributors +License: CC-BY-4.0 + +Files: .golangci.yml +Copyright: SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +License: Apache-2.0 + +Files: go.mod +Copyright: SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +License: Apache-2.0 + +Files: go.sum +Copyright: SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +License: Apache-2.0 + +Files: .gitignore +Copyright: SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +License: Apache-2.0 + +Files: MAINTAINERS.md +Copyright: SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +License: Apache-2.0 + +Files: README.md +Copyright: SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +License: Apache-2.0 + +Files: .whitesource +Copyright: SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +License: Apache-2.0 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..137069b --- /dev/null +++ b/LICENSE @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000..137069b --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/MAINTAINERS.md b/MAINTAINERS.md new file mode 100644 index 0000000..2fc18f9 --- /dev/null +++ b/MAINTAINERS.md @@ -0,0 +1,4 @@ +Maintainers of this repository: + +* Weston Schmidt @schmidtw +* John Bass @johnabass diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..44d6c4e --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +# SPDX-License-Identifier: Apache-2.0 +--- +services: + nginx: + image: nginx + ports: + - "8000:80" +version: "3.8" \ No newline at end of file diff --git a/go.mod b/go.mod index c1d390f..ce50577 100644 --- a/go.mod +++ b/go.mod @@ -2,9 +2,10 @@ module github.com/xmidt-org/idock go 1.21.3 +require github.com/stretchr/testify v1.8.4 + require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/stretchr/testify v1.8.4 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 8cf6655..fa4b6e6 100644 --- a/go.sum +++ b/go.sum @@ -4,6 +4,7 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/idock.go b/idock.go index acecdd0..a6e7a10 100644 --- a/idock.go +++ b/idock.go @@ -12,52 +12,53 @@ import ( "os/exec" "sort" "sync" - "testing" "time" ) const ( - // IDOCK_RUN_FLAG is the environment variable that controls whether or not - // to run the integration tests. - RUN_FLAG = "IDOCK_RUN" - - // IDOCK_VERBOSITY_FLAG is the environment variable that controls the - // verbosity of the output. + // IDOCK_VERBOSITY_FLAG is the default environment variable that controls + // the verbosity of the output. VERBOSITY_FLAG = "IDOCK_VERBOSITY" - // DOCKER_MAX_WAIT_FLAG is the environment variable that controls how long - // to wait for the docker-compose program to start. + // DOCKER_MAX_WAIT_FLAG is the default environment variable that controls + // how long to wait for the docker-compose program to start. DOCKER_MAX_WAIT_FLAG = "IDOCK_DOCKER_MAX_WAIT" - // PROGRAM_MAX_WAIT_FLAG is the environment variable that controls how long - // to wait for the program to start. + // PROGRAM_MAX_WAIT_FLAG is the default environment variable that controls + // how long to wait for the program to start. PROGRAM_MAX_WAIT_FLAG = "IDOCK_PROGRAM_MAX_WAIT" - // CLEANUP_RETRIES_FLAG is the environment variable that controls how many - // times to retry the cleanup process. - CLEANUP_RETRIES_FLAG = "IDOCK_CLEANUP_RETRIES" + // CLEANUP_ATTEMPTS_FLAG is the default environment variable that controls + // how many times to retry the cleanup process. + CLEANUP_ATTEMPTS_FLAG = "IDOCK_CLEANUP_RETRIES" ) var ( - errTimedOut = fmt.Errorf("timed out") - errProgramExited = fmt.Errorf("program exited") + errTimedOut = fmt.Errorf("timed out") ) // IDock is the main struct for the idock package. type IDock struct { + // env variable names + verbosityFlag string + dockerMaxWaitFlag string + programMaxWaitFlag string + cleanupAttemptsFlag string + tcpPortMaxWait time.Duration dockerComposeFile string dockerTCPPorts []int dockerMaxWait time.Duration - afterDocker func(*IDock) + afterDocker func(context.Context, *IDock) program func() programTCPPorts []int programMaxWait time.Duration - afterProgram func(*IDock) error - cleanupRetries int + afterProgram func(context.Context, *IDock) + cleanupAttempts int localhost string verbosity int noDockerCompose bool + dockerStarted bool } // Option is an option interface for the IDock struct. @@ -71,20 +72,28 @@ func (f optionFunc) apply(c *IDock) { f(c) } +func emptyProgram() {} +func emptyAfter(context.Context, *IDock) {} + // New creates a new IDock struct with the given options. func New(opts ...Option) *IDock { - c := &IDock{ - tcpPortMaxWait: 2 * time.Second, - afterDocker: func(*IDock) {}, - program: func() {}, - afterProgram: func(*IDock) error { - return nil - }, - programMaxWait: 2 * time.Second, - localhost: "localhost", - cleanupRetries: 3, + var c IDock + + defaults := []Option{ + VerbosityEnvarName(VERBOSITY_FLAG), + CleanupAttemptsEnvarName(CLEANUP_ATTEMPTS_FLAG), + DockerMaxWaitEnvarName(DOCKER_MAX_WAIT_FLAG), + ProgramMaxWaitEnvarName(PROGRAM_MAX_WAIT_FLAG), + TCPPortMaxWait(10 * time.Millisecond), + AfterDocker(nil), + Program(nil), + AfterProgram(nil), + ProgramMaxWait(2 * time.Second), + Localhost("localhost"), + CleanupAttempts(3), } + opts = append(defaults, opts...) opts = append(opts, []Option{ verbosity(), cleanupRetries(), @@ -93,67 +102,89 @@ func New(opts ...Option) *IDock { }...) for _, opt := range opts { - opt.apply(c) + opt.apply(&c) } - return c + return &c } -// Verbosity gets the verbosity level. +// Verbosity gets the verbosity level. The verbosity level is set by the +// IDOCK_VERBOSITY environment variable, or by the Verbosity option. The +// environment variable takes precedence over the option. The default value is +// 0. func (c *IDock) Verbosity() int { return c.verbosity } -// Run runs the integration tests. -func (c *IDock) Run(m *testing.M) { - if os.Getenv(RUN_FLAG) == "" { - return +// Start starts the docker-compose services and the program. It waits for the +// docker-compose services and the program to start before returning. If the +// docker-compose services or the program fail to start, then an error is +// returned. +func (c *IDock) Start() error { + ctx := context.Background() + err := c.startDocker(ctx) + if err != nil { + c.Logf(0, "docker startup failed: %s\n", err) + return err } - code := c.run(m) + if c.afterDocker != nil { + start := time.Now() + c.afterDocker(ctx, c) + end := time.Now() + c.Logf(1, "customization after docker took %s\n", end.Sub(start)) + } - c.Logf(1, "Exiting with code %d\n", code) + err = c.startProgram(ctx) + if err != nil { + c.Logf(0, "program startup failed: %s\n", err) + return err + } + + if c.afterProgram != nil { + start := time.Now() + c.afterProgram(ctx, c) + end := time.Now() + c.Logf(1, "customization after program took %s\n", end.Sub(start)) + } + + return nil +} - os.Exit(code) +// Stop stops the docker-compose services and cleans up any docker containers +// that were started. +func (c *IDock) Stop() { + c.cleanup() } -func (c *IDock) startDocker() error { +func (c *IDock) startDocker(ctx context.Context) error { if c.dockerComposeFile == "" { - c.cleanupRetries = 0 return nil } + verbose := c.verbosity > 1 args := []string{"-f", c.dockerComposeFile, "up", "-d"} - if c.verbosity > 1 { + if verbose { args = append([]string{"--verbose"}, args...) } - cmd := exec.Command("docker-compose", args...) - - // Some systems don't have docker-compose installed, so try to use the docker-compose - // binary from the docker image instead. - if errors.Is(cmd.Err, exec.ErrNotFound) { - args = append([]string{"compose"}, args...) - cmd = exec.Command("docker", args...) - c.noDockerCompose = true - } + ctx, cancel := context.WithTimeout(ctx, c.dockerMaxWait) + defer cancel() - if c.verbosity > 1 { - cmd.Stderr = os.Stdout - cmd.Stdout = os.Stdout + cmd, err := dockerCompose(ctx, verbose, args...) + if err != nil { + return err } dockerStart := time.Now() - err := cmd.Start() + err = cmd.Start() if err != nil { - c.cleanupRetries = 0 return err } + c.dockerStarted = true c.Logf(1, "Waiting for services to start...\n") - ctx, cancel := context.WithTimeout(context.Background(), c.dockerMaxWait) - defer cancel() - err = c.wait(ctx, nil) + err = c.waitForPorts(ctx, c.dockerTCPPorts) if err != nil { c.Logf(1, "docker-compose services took too long to start (%s)\n", c.dockerMaxWait) return err @@ -164,73 +195,64 @@ func (c *IDock) startDocker() error { return nil } -func (c *IDock) run(m *testing.M) int { - err := c.startDocker() - if 0 <= c.cleanupRetries { - defer c.cleanup() - } - if err != nil { - c.Logf(0, "docker startup failed: %s\n", err) - return -1 +func (c *IDock) cleanup() { + c.Logf(1, "Cleaning up...\n") + + if !c.dockerStarted || c.cleanupAttempts < 1 { + return } - if c.afterDocker != nil { - start := time.Now() - c.afterDocker(c) - end := time.Now() - c.Logf(1, "customization after docker took %s\n", end.Sub(start)) + args := []string{"-f", c.dockerComposeFile, "down", "--remove-orphans"} + cmd, err := dockerCompose(context.Background(), c.verbosity > 1, args...) + if err == nil { + for i := 0; i < c.cleanupAttempts; i++ { + err := cmd.Run() + if err == nil { + return + } + c.Logf(1, "Failed to clean up docker-compose services on try %d: %s\n", i+1, err) + } } + fmt.Printf("Failed to clean up docker services. Please run `docker-compose down --remove-orphans` manually\n") +} + +func (c *IDock) startProgram(ctx context.Context) error { start := time.Now() - done := make(chan struct{}) - c.safelyWrap() - ctx, cancel := context.WithTimeout(context.Background(), c.programMaxWait) + ctx, cancel := context.WithTimeout(ctx, c.programMaxWait) defer cancel() - err = c.wait(ctx, c.programTCPPorts) - end := time.Now() - c.Logf(1, "program startup took %s\n", end.Sub(start)) - if err != nil { - if errors.Is(err, errProgramExited) { - c.Logf(0, "program exited before services were ready\n") - } else if errors.Is(err, errTimedOut) { - c.Logf(0, "program took too long to start\n") - } else { - c.Logf(0, "program had some unknown error: %s\n", err) - } - return -1 - } + go c.program() - if c.afterProgram != nil { - start := time.Now() - err = c.afterProgram(c) - end := time.Now() - c.Logf(1, "customization after program took %s\n", end.Sub(start)) - if err != nil { - c.Logf(0, "customization after program started issued an error: %s\n", err) - return -1 - } + err := c.waitForPorts(ctx, c.programTCPPorts) + end := time.Now() + if err != nil { + c.Logf(1, "program took too long to start: %s\n", end.Sub(start)) + return err } + c.Logf(1, "program startup took %s\n", end.Sub(start)) - c.Logf(2, "running the tests\n") - return m.Run() + return nil } -func (c *IDock) isPortOpen(ctx context.Context, port int) (bool, error) { +func (c *IDock) isPortOpen(ctx context.Context, port int) error { var d net.Dialer address := fmt.Sprintf("%s:%d", c.localhost, port) conn, err := d.DialContext(ctx, "tcp", address) if err != nil { - return false, err + if ctx.Err() == nil { + err = errTimedOut + } + return err } conn.Close() - return true, nil + return nil } -func (c *IDock) wait(ctx context.Context, ports []int) error { +func (c *IDock) waitForPorts(ctx context.Context, ports []int) error { var wg sync.WaitGroup results := make(chan int, len(ports)) @@ -238,27 +260,37 @@ func (c *IDock) wait(ctx context.Context, ports []int) error { wg.Add(1) go func(ctx context.Context, port int) { for { - sub, cancel := context.WithTimeout(ctx, 10*time.Millisecond) - got, err := c.isPortOpen(sub, port) - cancel() + sub, cancel := context.WithTimeout(ctx, c.tcpPortMaxWait) - if err == nil && got { + err := c.isPortOpen(sub, port) + if err == nil { results <- port - break + cancel() + wg.Done() + return } - if err != nil { - results <- (-1 * port) - break + + // timing out while checking is not fatal unless the + // root context is done. + if errors.Is(err, errTimedOut) && ctx.Err() == nil { + cancel() + continue } + + results <- (-1 * port) + cancel() + wg.Done() + return } - wg.Done() }(ctx, port) } wg.Wait() + close(results) succeeded := make([]int, 0, len(ports)) failed := make([]int, 0, len(ports)) + for result := range results { if result < 0 { failed = append(failed, (-1 * result)) @@ -287,60 +319,35 @@ func (c *IDock) wait(ctx context.Context, ports []int) error { // Logf prints a message if the verbosity level is greater than or equal to the // given level. func (c *IDock) Logf(level int, format string, a ...any) { - if level <= c.verbosity { - return + if c.verbosity >= level { + fmt.Printf(format, a...) } - fmt.Printf(format, a...) } -func (c *IDock) cleanup() { - c.Logf(1, "Cleaning up...\n") - - var cmd *exec.Cmd - if c.noDockerCompose { - cmd = exec.Command("docker", "compose", "-f", c.dockerComposeFile, "down", "--remove-orphans") - } else { - cmd = exec.Command("docker-compose", "-f", c.dockerComposeFile, "down", "--remove-orphans") - } - - if c.verbosity > 1 { - cmd.Stderr = os.Stdout - cmd.Stdout = os.Stdout +func dockerCompose(ctx context.Context, useStdout bool, args ...string) (*exec.Cmd, error) { + cmd := exec.CommandContext(ctx, "docker-compose", args...) + if cmd == nil { + return nil, errors.New("failed to create docker-compose command") } - for i := 0; i < c.cleanupRetries; i++ { - err := cmd.Run() - if err == nil { - return + // Some systems don't have docker-compose installed, so try to use the docker-compose + // binary from the docker image instead. + if errors.Is(cmd.Err, exec.ErrNotFound) { + args = append([]string{"compose"}, args...) + cmd = exec.CommandContext(ctx, "docker", args...) + if cmd == nil { + return nil, errors.New("failed to create docker-compose command") } - c.Logf(1, "Failed to clean up docker-compose services on try %d: %s\n", i+1, err) } - fmt.Printf("Failed to clean up docker services. Please run `docker-compose down --remove-orphans` manually\n") -} - -func (c *IDock) safelyWrap() bool { - ctx, cancel := context.WithTimeout(context.Background(), c.programMaxWait) - defer cancel() - - failure := make(chan bool) - go func() { - defer func() { - if r := recover(); r != nil { - fmt.Println("recovered from panic") - fmt.Println(r) - failure <- true - } - }() - - c.program() - }() + if cmd.Err != nil { + return nil, cmd.Err + } - select { - case <-failure: - return success - case <-ctx.Done(): - // The program started and didn't fail in the given time, so return true. - return true + if useStdout { + cmd.Stderr = os.Stdout + cmd.Stdout = os.Stdout } + + return cmd, nil } diff --git a/idock_test.go b/idock_test.go index b1fd3ee..6bc575e 100644 --- a/idock_test.go +++ b/idock_test.go @@ -5,6 +5,7 @@ package idock import ( "context" + "errors" "net/http" "net/http/httptest" "net/url" @@ -16,43 +17,171 @@ import ( "github.com/stretchr/testify/require" ) -func TestIDock_safelyWrap(t *testing.T) { +var unknownErr = errors.New("unknown error") + +func TestIDock_startDocker(t *testing.T) { + var noDockerCompose bool + tests := []struct { + description string + have IDock + makeServer bool + expectErr error + }{ + { + description: "no docker-compose file", + }, { + description: "a docker-compose file, but not enought time", + have: IDock{ + dockerComposeFile: "docker-compose.yml", + dockerMaxWait: 1 * time.Nanosecond, + }, + expectErr: unknownErr, + }, { + description: "success, no verbosity", + have: IDock{ + tcpPortMaxWait: 10 * time.Millisecond, + dockerComposeFile: "docker-compose.yml", + dockerMaxWait: 15 * time.Second, + localhost: "localhost", + dockerTCPPorts: []int{8000}, + }, + }, { + description: "success, verbosity", + have: IDock{ + verbosity: 99, + tcpPortMaxWait: 10 * time.Millisecond, + dockerComposeFile: "docker-compose.yml", + dockerMaxWait: 15 * time.Second, + localhost: "localhost", + dockerTCPPorts: []int{8000}, + }, + }, { + description: "a docker-compose file, but not enough ports", + have: IDock{ + tcpPortMaxWait: 10 * time.Millisecond, + dockerComposeFile: "docker-compose.yml", + dockerMaxWait: 3 * time.Second, + localhost: "localhost", + dockerTCPPorts: []int{8000, 9999}, + }, + expectErr: unknownErr, + }, + } + for _, tc := range tests { + t.Run(tc.description, func(t *testing.T) { + assert := assert.New(t) + //require := require.New(t) + + err := tc.have.startDocker(context.Background()) + + if tc.have.noDockerCompose { + noDockerCompose = true + } + switch tc.expectErr { + case nil: + assert.NoError(err) + case unknownErr: + assert.Error(err) + default: + assert.ErrorIs(err, tc.expectErr) + } + }) + } + + clean := IDock{ + dockerComposeFile: "docker-compose.yml", + dockerStarted: true, + cleanupAttempts: 5, + verbosity: 99, + noDockerCompose: noDockerCompose, + } + clean.cleanup() +} + +func TestIDock_startProgram(t *testing.T) { tests := []struct { description string have IDock - expect bool + makeServer bool + expectErr error }{ { description: "program returns", have: IDock{ program: func() {}, - programMaxWait: time.Second, + programMaxWait: time.Millisecond * 100, }, - expect: true, }, { - description: "program panics", + description: "program never returns", have: IDock{ - program: func() { panic("program panics") }, - programMaxWait: time.Second, + tcpPortMaxWait: 10 * time.Millisecond, + program: func() { + for { + time.Sleep(time.Second) + } + }, + programMaxWait: time.Millisecond * 100, }, }, { - expect: true, - description: "program never returns", + description: "program never returns, ports are open", + have: IDock{ + tcpPortMaxWait: 10 * time.Millisecond, + program: func() { + for { + time.Sleep(time.Second) + } + }, + programMaxWait: time.Millisecond * 100, + }, + makeServer: true, + }, { + description: "program never returns, not enough ports are open", have: IDock{ + tcpPortMaxWait: 10 * time.Millisecond, program: func() { for { time.Sleep(time.Second) } }, - programMaxWait: time.Second, + programTCPPorts: []int{51}, + programMaxWait: time.Millisecond * 100, }, + makeServer: true, + expectErr: unknownErr, }, } for _, tc := range tests { t.Run(tc.description, func(t *testing.T) { assert := assert.New(t) - got := tc.have.safelyWrap() - assert.Equal(tc.expect, got) + require := require.New(t) + + if tc.makeServer { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("Mock response")) + })) + defer server.Close() + + u, err := url.Parse(server.URL) + require.NoError(err) + authority := u.Hostname() + port, err := strconv.Atoi(u.Port()) + require.NoError(err) + + tc.have.localhost = authority + tc.have.programTCPPorts = append(tc.have.programTCPPorts, port) + } + + err := tc.have.startProgram(context.Background()) + + switch tc.expectErr { + case nil: + assert.NoError(err) + case unknownErr: + assert.Error(err) + default: + assert.ErrorIs(err, tc.expectErr) + } }) } } @@ -61,15 +190,15 @@ func TestIDock_isPortOpen(t *testing.T) { tests := []struct { description string wait time.Duration - expect bool + expectErr error }{ { description: "port is not open", wait: 100 * time.Millisecond, + expectErr: unknownErr, }, { description: "port is open", wait: 100 * time.Millisecond, - expect: true, }, } for _, tc := range tests { @@ -80,10 +209,10 @@ func TestIDock_isPortOpen(t *testing.T) { authority := "localhost" port := 51 // probably not used - if tc.expect { + if tc.expectErr == nil { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - w.Write([]byte("Mock response")) + _, _ = w.Write([]byte("Mock response")) })) defer server.Close() @@ -100,46 +229,186 @@ func TestIDock_isPortOpen(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), tc.wait) defer cancel() - assert.Equal(tc.expect, c.isPortOpen(ctx, port)) + err := c.isPortOpen(ctx, port) + + switch tc.expectErr { + case nil: + assert.NoError(err) + + case unknownErr: + assert.Error(err) + default: + assert.ErrorIs(err, tc.expectErr) + } }) } } -func TestIDock_wait(t *testing.T) { +func TestNewAndOptions(t *testing.T) { tests := []struct { description string - ports []int - done chan struct{} - expectedErr error + opts []Option + env map[string]string + validate func(*assert.Assertions, *IDock) }{ { - description: "", - // TODO: Add test cases. + description: "All the options", + opts: []Option{ + TCPPortMaxWait(15 * time.Millisecond), + Localhost("localhost"), + + DockerComposeFile("docker-compose.yml"), + DockerMaxWait(5 * time.Second), + RequireDockerTCPPorts(8000), + + AfterDocker(func(context.Context, *IDock) {}), + + Program(func() {}), + ProgramMaxWait(5 * time.Second), + RequireProgramTCPPorts(8000), + + AfterProgram(func(context.Context, *IDock) {}), + CleanupAttempts(3), + Verbosity(5), + }, + env: map[string]string{ + "IDOCK_VERBOSITY": "2", + "IDOCK_DOCKER_MAX_WAIT": "15s", + "IDOCK_PROGRAM_MAX_WAIT": "15s", + "IDOCK_CLEANUP_RETRIES": "5", + }, + validate: func(assert *assert.Assertions, c *IDock) { + if !assert.NotNil(c) { + return + } + assert.Equal(15*time.Millisecond, c.tcpPortMaxWait) + assert.Equal("localhost", c.localhost) + + assert.Equal("docker-compose.yml", c.dockerComposeFile) + assert.Equal(15*time.Second, c.dockerMaxWait) + assert.Equal([]int{8000}, c.dockerTCPPorts) + + assert.NotNil(c.afterDocker) + + assert.NotNil(c.program) + assert.Equal(15*time.Second, c.programMaxWait) + assert.Equal([]int{8000}, c.programTCPPorts) + + assert.NotNil(c.afterProgram) + assert.Equal(5, c.cleanupAttempts) + assert.Equal(2, c.Verbosity()) + }, }, } for _, tc := range tests { t.Run(tc.description, func(t *testing.T) { assert := assert.New(t) - require := require.New(t) - c := &IDock{ - tcpPortMaxWait: tc.fields.tcpPortMaxWait, - dockerComposeFile: tc.fields.dockerComposeFile, - dockerTCPPorts: tc.fields.dockerTCPPorts, - dockerMaxWait: tc.fields.dockerMaxWait, - afterDocker: tc.fields.afterDocker, - program: tc.fields.program, - programTCPPorts: tc.fields.programTCPPorts, - programMaxWait: tc.fields.programMaxWait, - afterProgram: tc.fields.afterProgram, - cleanupRetries: tc.fields.cleanupRetries, - localhost: tc.fields.localhost, - verbosity: tc.fields.verbosity, - noDockerCompose: tc.fields.noDockerCompose, + + for k, v := range tc.env { + t.Setenv(k, v) } + c := New(tc.opts...) + tc.validate(assert, c) + }) + } +} + +func TestRun(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("Mock response")) + })) + defer server.Close() - err := c.wait(tc.ports, tc.done) + require := require.New(t) + u, err := url.Parse(server.URL) + require.NoError(err) + authority := u.Hostname() + port, err := strconv.Atoi(u.Port()) + require.NoError(err) - assert.ErrorIs(err, tc.expectedErr) + var afterDockerCallCount int + var programCallCount int + var afterProgramCallCount int + + tests := []struct { + description string + opts []Option + expectErr error + }{ + { + description: "Many options", + opts: []Option{ + TCPPortMaxWait(15 * time.Millisecond), + Localhost(authority), + + DockerComposeFile("docker-compose.yml"), + DockerMaxWait(15 * time.Second), + RequireDockerTCPPorts(8000), + + AfterDocker(func(context.Context, *IDock) { + afterDockerCallCount++ + }), + + Program(func() { + programCallCount++ + }), + ProgramMaxWait(15 * time.Second), + RequireProgramTCPPorts(port), + + AfterProgram(func(context.Context, *IDock) { + afterProgramCallCount++ + }), + CleanupAttempts(5), + }, + }, { + description: "fail starting docker", + opts: []Option{ + TCPPortMaxWait(15 * time.Millisecond), + Localhost(authority), + + DockerComposeFile("docker-compose.yml"), + DockerMaxWait(15 * time.Millisecond), + RequireDockerTCPPorts(8001), + CleanupAttempts(5), + }, + expectErr: unknownErr, + }, { + description: "fail starting program", + opts: []Option{ + TCPPortMaxWait(15 * time.Millisecond), + Localhost(authority), + + DockerComposeFile("docker-compose.yml"), + DockerMaxWait(15 * time.Second), + RequireDockerTCPPorts(8000), + + ProgramMaxWait(100 * time.Millisecond), + RequireProgramTCPPorts(port, 99), + + CleanupAttempts(5), + }, + expectErr: unknownErr, + }, + } + + for _, tc := range tests { + t.Run(tc.description, func(t *testing.T) { + assert := assert.New(t) + + c := New(tc.opts...) + err := c.Start() + + switch tc.expectErr { + case nil: + c.Stop() + assert.NoError(err) + + case unknownErr: + assert.Error(err) + default: + assert.ErrorIs(err, tc.expectErr) + } }) } } diff --git a/options.go b/options.go index 04eba9e..40dbf37 100644 --- a/options.go +++ b/options.go @@ -4,6 +4,7 @@ package idock import ( + "context" "fmt" "os" "strconv" @@ -40,22 +41,22 @@ func DockerMaxWait(d time.Duration) Option { // AfterDocker is a function that is called after the docker-compose program // has started but before the program is started. -func AfterDocker(f func(*IDock)) Option { +func AfterDocker(f func(context.Context, *IDock)) Option { return optionFunc(func(c *IDock) { - if f == nil { - f = func(*IDock) {} + c.afterDocker = emptyAfter + if f != nil { + c.afterDocker = f } - c.afterDocker = f }) } // Program is the function that is called to start the program. func Program(f func()) Option { return optionFunc(func(c *IDock) { - if f == nil { - f = func() {} + c.program = emptyProgram + if f != nil { + c.program = f } - c.program = f }) } @@ -81,26 +82,27 @@ func ProgramMaxWait(d time.Duration) Option { // AfterProgram is a function that is called after the program has started but // before the tests are run. -func AfterProgram(f func(*IDock) error) Option { +func AfterProgram(f func(context.Context, *IDock)) Option { return optionFunc(func(c *IDock) { - if f == nil { - f = func(*IDock) error { - return nil - } + c.afterProgram = emptyAfter + if f != nil { + c.afterProgram = f } - c.afterProgram = f }) } -// CleanupRetries sets the number of times to retry the cleanup process before -// giving up and leaving any docker containers running. +// CleanupAttempts sets the number of times to attempt to cleanup the docker +// containers process before giving up and leaving any docker containers running. +// A value of 0 means do not attempt to cleanup the docker containers. This is +// useful for debugging or speeding up tests. +// // The default value is 3. -func CleanupRetries(n int) Option { +func CleanupAttempts(n int) Option { return optionFunc(func(c *IDock) { if n < 0 { panic(fmt.Sprintf("cleanupRetries must be >= 0: %d\n", n)) } - c.cleanupRetries = n + c.cleanupAttempts = n }) } @@ -124,10 +126,49 @@ func TCPPortMaxWait(d time.Duration) Option { }) } +// Verbosity sets the verbosity level. +func Verbosity(n int) Option { + return optionFunc(func(c *IDock) { + c.verbosity = n + }) +} + +// VerbosityEnvarName sets the environment variable name to use for the +// verbosity level. +func VerbosityEnvarName(name string) Option { + return optionFunc(func(c *IDock) { + c.verbosityFlag = name + }) +} + +// CleanupAttemptsEnvarName sets the environment variable name to use for the +// cleanup attempts. +func CleanupAttemptsEnvarName(name string) Option { + return optionFunc(func(c *IDock) { + c.cleanupAttemptsFlag = name + }) +} + +// DockerMaxWaitEnvarName sets the environment variable name to use for the +// docker max wait. +func DockerMaxWaitEnvarName(name string) Option { + return optionFunc(func(c *IDock) { + c.dockerMaxWaitFlag = name + }) +} + +// ProgramMaxWaitEnvarName sets the environment variable name to use for the +// program max wait. +func ProgramMaxWaitEnvarName(name string) Option { + return optionFunc(func(c *IDock) { + c.programMaxWaitFlag = name + }) +} + // verbosity sets the verbosity level based on the environment variable. func verbosity() Option { return optionFunc(func(c *IDock) { - c.verbosity = envToInt(VERBOSITY_FLAG, c.verbosity) + c.verbosity = envToInt(c.verbosityFlag, c.verbosity) }) } @@ -136,7 +177,7 @@ func verbosity() Option { // variable. func cleanupRetries() Option { return optionFunc(func(c *IDock) { - c.cleanupRetries = envToInt(CLEANUP_RETRIES_FLAG, c.cleanupRetries) + c.cleanupAttempts = envToInt(c.cleanupAttemptsFlag, c.cleanupAttempts) }) } @@ -144,7 +185,7 @@ func cleanupRetries() Option { // programs to start based on the environment variable. func dockerMaxWait() Option { return optionFunc(func(c *IDock) { - c.dockerMaxWait = envToDuration(DOCKER_MAX_WAIT_FLAG, c.dockerMaxWait) + c.dockerMaxWait = envToDuration(c.dockerMaxWaitFlag, c.dockerMaxWait) }) } @@ -152,7 +193,7 @@ func dockerMaxWait() Option { // start based on the environment variable. func programMaxWait() Option { return optionFunc(func(c *IDock) { - c.programMaxWait = envToDuration(PROGRAM_MAX_WAIT_FLAG, c.programMaxWait) + c.programMaxWait = envToDuration(c.programMaxWaitFlag, c.programMaxWait) }) }