Skip to content

fix(cli): prevent sqlDB leaks in ConnectToPostgres #10072

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 1 commit into from
Oct 5, 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
39 changes: 21 additions & 18 deletions cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -1875,45 +1875,49 @@ func BuildLogger(inv *clibase.Invocation, cfg *codersdk.DeploymentValues) (slog.
}, nil
}

func ConnectToPostgres(ctx context.Context, logger slog.Logger, driver string, dbURL string) (*sql.DB, error) {
func ConnectToPostgres(ctx context.Context, logger slog.Logger, driver string, dbURL string) (sqlDB *sql.DB, err error) {
logger.Debug(ctx, "connecting to postgresql")

// 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
)
defer func() {
if err == nil {
return
}
if sqlDB != nil {
_ = sqlDB.Close()
sqlDB = nil
}
logger.Error(ctx, "connect to postgres failed", slog.Error(err))
}()

var 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))
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))
logger.Warn(ctx, "ping postgres: retrying", slog.Error(err), slog.F("try", tries))
_ = sqlDB.Close()
sqlDB = nil
continue
}

break
}
// Make sure we close the DB in case it opened but the ping failed for some
// reason.
defer func() {
if !ok && sqlDB != nil {
_ = sqlDB.Close()
}
}()
if err == nil {
err = ctx.Err()
}
if err != nil {
return nil, xerrors.Errorf("connect to postgres; tries %d; last error: %w", tries, err)
return nil, xerrors.Errorf("unable to connect after %d tries; last error: %w", tries, err)
}

// Ensure the PostgreSQL version is >=13.0.0!
Expand Down Expand Up @@ -1958,7 +1962,6 @@ func ConnectToPostgres(ctx context.Context, logger slog.Logger, driver string, d
// of connection churn.
sqlDB.SetMaxIdleConns(3)

ok = true
return sqlDB, nil
}

Expand Down