@@ -88,6 +88,7 @@ import (
88
88
"github.com/coder/coder/provisionersdk"
89
89
sdkproto "github.com/coder/coder/provisionersdk/proto"
90
90
"github.com/coder/coder/tailnet"
91
+ "github.com/coder/retry"
91
92
"github.com/coder/wgtunnel/tunnelsdk"
92
93
)
93
94
@@ -1733,26 +1734,45 @@ func BuildLogger(inv *clibase.Invocation, cfg *codersdk.DeploymentValues) (slog.
1733
1734
1734
1735
func connectToPostgres (ctx context.Context , logger slog.Logger , driver string , dbURL string ) (* sql.DB , error ) {
1735
1736
logger .Debug (ctx , "connecting to postgresql" )
1736
- sqlDB , err := sql .Open (driver , dbURL )
1737
+
1738
+ // Try to connect for 30 seconds.
1739
+ ctx , cancel := context .WithTimeout (ctx , 30 * time .Second )
1740
+ defer cancel ()
1741
+
1742
+ var (
1743
+ sqlDB * sql.DB
1744
+ err error
1745
+ ok = false
1746
+ tries int
1747
+ )
1748
+ for r := retry .New (time .Second , 3 * time .Second ); r .Wait (ctx ); {
1749
+ tries ++
1750
+
1751
+ sqlDB , err = sql .Open (driver , dbURL )
1752
+ if err != nil {
1753
+ continue
1754
+ }
1755
+
1756
+ pingCtx , pingCancel := context .WithTimeout (ctx , 5 * time .Second )
1757
+ err = sqlDB .PingContext (pingCtx )
1758
+ if err != nil {
1759
+ pingCancel ()
1760
+ continue
1761
+ }
1762
+ pingCancel ()
1763
+
1764
+ err = nil
1765
+ }
1737
1766
if err != nil {
1738
- return nil , xerrors .Errorf ("dial postgres: %w" , err )
1767
+ return nil , xerrors .Errorf ("connect to postgres; tries %d; last error : %w" , tries , err )
1739
1768
}
1740
1769
1741
- ok := false
1742
1770
defer func () {
1743
- if ! ok {
1771
+ if ! ok && sqlDB != nil {
1744
1772
_ = sqlDB .Close ()
1745
1773
}
1746
1774
}()
1747
1775
1748
- pingCtx , pingCancel := context .WithTimeout (ctx , 15 * time .Second )
1749
- defer pingCancel ()
1750
-
1751
- err = sqlDB .PingContext (pingCtx )
1752
- if err != nil {
1753
- return nil , xerrors .Errorf ("ping postgres: %w" , err )
1754
- }
1755
-
1756
1776
// Ensure the PostgreSQL version is >=13.0.0!
1757
1777
version , err := sqlDB .QueryContext (ctx , "SHOW server_version_num;" )
1758
1778
if err != nil {
0 commit comments