Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(docker): ensure orphaned contributoor containers can be managed #46

Merged
merged 3 commits into from
Jan 15, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 27 additions & 10 deletions internal/sidecar/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ func (s *dockerSidecar) Start() error {

// Stop stops and removes the docker container using docker-compose.
func (s *dockerSidecar) Stop() error {
// Stop and remove containers, volumes, and networks
// First try to stop via compose. If there has been any sort of configuration change
// between versions, then this will not stop the container.
//nolint:gosec // validateComposePath() and filepath.Clean() in-use.
cmd := exec.Command("docker", "compose", "-f", s.composePath, "down",
"--remove-orphans",
Expand All @@ -93,7 +94,15 @@ func (s *dockerSidecar) Stop() error {
cmd.Env = s.getComposeEnv()

if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to stop containers: %w\nOutput: %s", err, string(output))
// Don't return error here, try our fallback.
s.logger.Warnf("failed to stop via compose: %v\noutput: %s", err, string(output))
}

// Fallback in the case of a configuration change between versions, attempt to remove
// the container by name.
cmd = exec.Command("docker", "rm", "-f", "contributoor")
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to stop container: %w\nOutput: %s", err, string(output))
}

fmt.Printf("%sContributoor stopped successfully%s\n", tui.TerminalColorGreen, tui.TerminalColorReset)
Expand All @@ -103,23 +112,31 @@ func (s *dockerSidecar) Stop() error {

// IsRunning checks if the docker container is running.
func (s *dockerSidecar) IsRunning() (bool, error) {
// Check via compose first. If there has been any sort of configuration change between
// versions, then this will return a non running state.
//nolint:gosec // validateComposePath() and filepath.Clean() in-use.
cmd := exec.Command("docker", "compose", "-f", s.composePath, "ps", "--format", "{{.State}}")
cmd.Env = s.getComposeEnv()

output, err := cmd.Output()
if err != nil {
return false, fmt.Errorf("failed to check container status: %w", err)
if err == nil {
states := strings.Split(strings.TrimSpace(string(output)), "\n")
for _, state := range states {
if strings.Contains(strings.ToLower(state), "running") {
return true, nil
}
}
}

states := strings.Split(strings.TrimSpace(string(output)), "\n")
for _, state := range states {
if strings.Contains(strings.ToLower(state), "running") {
return true, nil
}
// In that case, we will fallback to checking for any container with the name 'contributoor'.
cmd = exec.Command("docker", "ps", "-q", "-f", "name=contributoor", "-f", "status=running")

output, err = cmd.Output()
if err != nil {
return false, fmt.Errorf("failed to check container status: %w", err)
}

return false, nil
return len(strings.TrimSpace(string(output))) > 0, nil
}

// Update pulls the latest image and restarts the container.
Expand Down
36 changes: 36 additions & 0 deletions internal/sidecar/docker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
Expand Down Expand Up @@ -174,4 +175,39 @@ func TestDockerService_Integration(t *testing.T) {
require.NoError(t, err)
require.False(t, running)
})

t.Run("lifecycle_with_external_container", func(t *testing.T) {
// Write out compose file.
require.NoError(t, os.WriteFile(filepath.Join(tmpDir, "docker-compose.yml"), []byte(composeFile), 0644))

// Start a container directly with docker (not via compose) of the same name. This mimics
// a container the installer isn't aware of.
cmd := exec.Command("docker", "run", "-d", "--name", "contributoor", "busybox",
"sh", "-c", "while true; do echo 'Container is running'; sleep 1; done")
output, err := cmd.CombinedOutput()
require.NoError(t, err, "failed to start container: %s", string(output))

// IsRunning should detect the external container.
running, err := ds.IsRunning()
require.NoError(t, err)
require.True(t, running, "IsRunning should detect externally started container")

// Stop should be able to handle the external container.
require.NoError(t, ds.Stop())

// Verify container is stopped.
running, err = ds.IsRunning()
require.NoError(t, err)
require.False(t, running, "Container should be stopped")

// Finally, test normal compose lifecycle works after cleaning up external container.
require.NoError(t, ds.Start())
checkContainerHealth(t)

require.NoError(t, ds.Stop())

running, err = ds.IsRunning()
require.NoError(t, err)
require.False(t, running)
})
}
Loading