Skip to content

Commit

Permalink
Improve Docker Compose container execution (#687)
Browse files Browse the repository at this point in the history
`WaitForHealthy()` does not implement any logic to timeout if the
healthy condition is never met.

By adding a timeout we make sure this function ends if the expected
condition cannot be met in a certain (known) time frame.
  • Loading branch information
endorama authored Feb 9, 2022
1 parent ff015b7 commit b5bc909
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion internal/compose/compose.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ import (
"github.com/elastic/elastic-package/internal/signal"
)

const (
// waitForHealthyTimeout is the maximum duration for WaitForHealthy().
waitForHealthyTimeout = 10 * time.Minute
// waitForHealthyInterval is the check interval for WaitForHealthy().
waitForHealthyInterval = 1 * time.Second
)

// Project represents a Docker Compose project.
type Project struct {
name string
Expand Down Expand Up @@ -275,12 +282,20 @@ func (p *Project) WaitForHealthy(opts CommandOptions) error {
return err
}

startTime := time.Now()
timeout := startTime.Add(waitForHealthyTimeout)

containerIDs := strings.Split(strings.TrimSpace(b.String()), "\n")
for {
if time.Now().After(timeout) {
return errors.New("timeout waiting for healthy container")
}

if signal.SIGINT() {
return errors.New("SIGINT: cancel waiting for policy assigned")
}

// NOTE: healthy must be reinitialized at each iteration
healthy := true

logger.Debugf("Wait for healthy containers: %s", strings.Join(containerIDs, ","))
Expand Down Expand Up @@ -316,12 +331,15 @@ func (p *Project) WaitForHealthy(opts CommandOptions) error {
healthy = false
}

// end loop before timeout if healthy
if healthy {
break
}

time.Sleep(time.Second)
// NOTE: using sleep does not guarantee interval but it's ok for this use case
time.Sleep(waitForHealthyInterval)
}

return nil
}

Expand Down

0 comments on commit b5bc909

Please sign in to comment.