Skip to content

fix(server): retry initial connection to postgres #7325

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

Merged
merged 2 commits into from
Apr 28, 2023
Merged
Changes from all 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
50 changes: 38 additions & 12 deletions cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ import (
"github.com/coder/coder/provisionersdk"
sdkproto "github.com/coder/coder/provisionersdk/proto"
"github.com/coder/coder/tailnet"
"github.com/coder/retry"
"github.com/coder/wgtunnel/tunnelsdk"
)

Expand Down Expand Up @@ -1733,24 +1734,43 @@ func BuildLogger(inv *clibase.Invocation, cfg *codersdk.DeploymentValues) (slog.

func connectToPostgres(ctx context.Context, logger slog.Logger, driver string, dbURL string) (*sql.DB, error) {
logger.Debug(ctx, "connecting to postgresql")
sqlDB, err := sql.Open(driver, dbURL)
if err != nil {
return nil, xerrors.Errorf("dial postgres: %w", err)
}

ok := false
// Try to connect for 30 seconds.
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()

var (
sqlDB *sql.DB
err error
ok = false
tries int
)
for r := retry.New(time.Second, 3*time.Second); r.Wait(ctx); {
tries++

sqlDB, err = sql.Open(driver, dbURL)
if err != nil {
logger.Warn(ctx, "connect to postgres; retrying", slog.Error(err), slog.F("try", tries))
continue
}

err = pingPostgres(ctx, sqlDB)
if err != nil {
logger.Warn(ctx, "ping postgres; retrying", slog.Error(err), slog.F("try", tries))
continue
}

break
}
// Make sure we close the DB in case it opened but the ping failed for some
// reason.
defer func() {
if !ok {
if !ok && sqlDB != nil {
_ = sqlDB.Close()
}
}()

pingCtx, pingCancel := context.WithTimeout(ctx, 15*time.Second)
defer pingCancel()

err = sqlDB.PingContext(pingCtx)
if err != nil {
return nil, xerrors.Errorf("ping postgres: %w", err)
return nil, xerrors.Errorf("connect to postgres; tries %d; last error: %w", tries, err)
}

// Ensure the PostgreSQL version is >=13.0.0!
Expand Down Expand Up @@ -1799,6 +1819,12 @@ func connectToPostgres(ctx context.Context, logger slog.Logger, driver string, d
return sqlDB, nil
}

func pingPostgres(ctx context.Context, db *sql.DB) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
return db.PingContext(ctx)
}

type HTTPServers struct {
HTTPUrl *url.URL
HTTPListener net.Listener
Expand Down