2020-03-01 16:06:34 +00:00
|
|
|
package wait
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
"time"
|
2020-09-06 12:31:23 +00:00
|
|
|
|
|
|
|
"github.com/docker/go-connections/nat"
|
2020-03-01 16:06:34 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
//ForSQL constructs a new waitForSql strategy for the given driver
|
|
|
|
func ForSQL(port nat.Port, driver string, url func(nat.Port) string) *waitForSql {
|
|
|
|
return &waitForSql{
|
2020-09-06 12:31:23 +00:00
|
|
|
Port: port,
|
|
|
|
URL: url,
|
|
|
|
Driver: driver,
|
|
|
|
startupTimeout: defaultStartupTimeout(),
|
2021-01-17 18:00:46 +00:00
|
|
|
PollInterval: defaultPollInterval(),
|
2020-03-01 16:06:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type waitForSql struct {
|
|
|
|
URL func(port nat.Port) string
|
|
|
|
Driver string
|
|
|
|
Port nat.Port
|
|
|
|
startupTimeout time.Duration
|
2021-01-17 18:00:46 +00:00
|
|
|
PollInterval time.Duration
|
2020-03-01 16:06:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
//Timeout sets the maximum waiting time for the strategy after which it'll give up and return an error
|
|
|
|
func (w *waitForSql) Timeout(duration time.Duration) *waitForSql {
|
|
|
|
w.startupTimeout = duration
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
2021-01-17 18:00:46 +00:00
|
|
|
//WithPollInterval can be used to override the default polling interval of 100 milliseconds
|
|
|
|
func (w *waitForSql) WithPollInterval(pollInterval time.Duration) *waitForSql {
|
|
|
|
w.PollInterval = pollInterval
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
2020-03-01 16:06:34 +00:00
|
|
|
//WaitUntilReady repeatedly tries to run "SELECT 1" query on the given port using sql and driver.
|
2020-09-06 12:31:23 +00:00
|
|
|
// If the it doesn't succeed until the timeout value which defaults to 60 seconds, it will return an error
|
2020-03-01 16:06:34 +00:00
|
|
|
func (w *waitForSql) WaitUntilReady(ctx context.Context, target StrategyTarget) (err error) {
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, w.startupTimeout)
|
|
|
|
defer cancel()
|
|
|
|
|
2021-01-17 18:00:46 +00:00
|
|
|
ticker := time.NewTicker(w.PollInterval)
|
2020-03-01 16:06:34 +00:00
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
port, err := target.MappedPort(ctx, w.Port)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("target.MappedPort: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
db, err := sql.Open(w.Driver, w.URL(port))
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("sql.Open: %v", err)
|
|
|
|
}
|
2021-01-17 18:00:46 +00:00
|
|
|
defer db.Close()
|
2020-03-01 16:06:34 +00:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
case <-ticker.C:
|
|
|
|
|
|
|
|
if _, err := db.ExecContext(ctx, "SELECT 1"); err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|