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 new file mode 100644 index 0000000..ce50577 --- /dev/null +++ b/go.mod @@ -0,0 +1,11 @@ +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 + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..fa4b6e6 --- /dev/null +++ b/go.sum @@ -0,0 +1,10 @@ +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 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 new file mode 100644 index 0000000..a6e7a10 --- /dev/null +++ b/idock.go @@ -0,0 +1,353 @@ +// SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +// SPDX-License-Identifier: Apache-2.0 + +package idock + +import ( + "context" + "errors" + "fmt" + "net" + "os" + "os/exec" + "sort" + "sync" + "time" +) + +const ( + // 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 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 default environment variable that controls + // how long to wait for the program to start. + PROGRAM_MAX_WAIT_FLAG = "IDOCK_PROGRAM_MAX_WAIT" + + // 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") +) + +// 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(context.Context, *IDock) + program func() + programTCPPorts []int + programMaxWait time.Duration + afterProgram func(context.Context, *IDock) + cleanupAttempts int + localhost string + verbosity int + noDockerCompose bool + dockerStarted 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) +} + +func emptyProgram() {} +func emptyAfter(context.Context, *IDock) {} + +// New creates a new IDock struct with the given options. +func New(opts ...Option) *IDock { + 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(), + dockerMaxWait(), + programMaxWait(), + }...) + + for _, opt := range opts { + opt.apply(&c) + } + + return &c +} + +// 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 +} + +// 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 + } + + 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)) + } + + 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 +} + +// 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(ctx context.Context) error { + if c.dockerComposeFile == "" { + return nil + } + + verbose := c.verbosity > 1 + args := []string{"-f", c.dockerComposeFile, "up", "-d"} + if verbose { + args = append([]string{"--verbose"}, args...) + } + + ctx, cancel := context.WithTimeout(ctx, c.dockerMaxWait) + defer cancel() + + cmd, err := dockerCompose(ctx, verbose, args...) + if err != nil { + return err + } + + dockerStart := time.Now() + err = cmd.Start() + if err != nil { + return err + } + c.dockerStarted = true + + c.Logf(1, "Waiting for services to start...\n") + 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 + } + dockerReady := time.Now() + c.Logf(1, "docker-compose services took %s to start\n", dockerReady.Sub(dockerStart)) + + return nil +} + +func (c *IDock) cleanup() { + c.Logf(1, "Cleaning up...\n") + + if !c.dockerStarted || c.cleanupAttempts < 1 { + return + } + + 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() + ctx, cancel := context.WithTimeout(ctx, c.programMaxWait) + defer cancel() + + go c.program() + + 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)) + + return nil +} + +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 { + if ctx.Err() == nil { + err = errTimedOut + } + return err + } + conn.Close() + + return nil +} + +func (c *IDock) waitForPorts(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, c.tcpPortMaxWait) + + err := c.isPortOpen(sub, port) + if err == nil { + results <- port + cancel() + wg.Done() + return + } + + // 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 + } + }(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)) + } else { + succeeded = append(succeeded, result) + } + } + + 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 +} + +// 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 c.verbosity >= level { + fmt.Printf(format, a...) + } +} + +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") + } + + // 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") + } + } + + if cmd.Err != nil { + return nil, cmd.Err + } + + if useStdout { + cmd.Stderr = os.Stdout + cmd.Stdout = os.Stdout + } + + return cmd, nil +} diff --git a/idock_test.go b/idock_test.go new file mode 100644 index 0000000..6bc575e --- /dev/null +++ b/idock_test.go @@ -0,0 +1,414 @@ +// SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +// SPDX-License-Identifier: Apache-2.0 + +package idock + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +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 + makeServer bool + expectErr error + }{ + { + description: "program returns", + have: IDock{ + program: func() {}, + programMaxWait: time.Millisecond * 100, + }, + }, { + description: "program never returns", + have: IDock{ + tcpPortMaxWait: 10 * time.Millisecond, + program: func() { + for { + time.Sleep(time.Second) + } + }, + programMaxWait: time.Millisecond * 100, + }, + }, { + 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) + } + }, + 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) + 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) + } + }) + } +} + +func TestIDock_isPortOpen(t *testing.T) { + tests := []struct { + description string + wait time.Duration + expectErr error + }{ + { + description: "port is not open", + wait: 100 * time.Millisecond, + expectErr: unknownErr, + }, { + description: "port is open", + wait: 100 * time.Millisecond, + }, + } + 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.expectErr == nil { + 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() + + 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 TestNewAndOptions(t *testing.T) { + tests := []struct { + description string + opts []Option + env map[string]string + validate func(*assert.Assertions, *IDock) + }{ + { + 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) + + 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() + + 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) + + 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 new file mode 100644 index 0000000..40dbf37 --- /dev/null +++ b/options.go @@ -0,0 +1,224 @@ +// SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC +// SPDX-License-Identifier: Apache-2.0 + +package idock + +import ( + "context" + "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(context.Context, *IDock)) Option { + return optionFunc(func(c *IDock) { + c.afterDocker = emptyAfter + if f != nil { + c.afterDocker = f + } + }) +} + +// Program is the function that is called to start the program. +func Program(f func()) Option { + return optionFunc(func(c *IDock) { + c.program = emptyProgram + if f != nil { + 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(context.Context, *IDock)) Option { + return optionFunc(func(c *IDock) { + c.afterProgram = emptyAfter + if f != nil { + c.afterProgram = f + } + }) +} + +// 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 CleanupAttempts(n int) Option { + return optionFunc(func(c *IDock) { + if n < 0 { + panic(fmt.Sprintf("cleanupRetries must be >= 0: %d\n", n)) + } + c.cleanupAttempts = 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. +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(c.verbosityFlag, 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.cleanupAttempts = envToInt(c.cleanupAttemptsFlag, c.cleanupAttempts) + }) +} + +// 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(c.dockerMaxWaitFlag, 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(c.programMaxWaitFlag, 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 +}