Worker function for connection initialization. This function does not check if the connection is already open, if it is then it will be overwritten. Callers need to make sure no connection is open, otherwise we could leak connections
(dbname string)
| 130 | // Callers need to make sure no connection is open, otherwise we could leak |
| 131 | // connections |
| 132 | func (c *Cluster) initDbConnWithName(dbname string) error { |
| 133 | c.setProcessName("initializing db connection") |
| 134 | |
| 135 | var conn *sql.DB |
| 136 | connstring := c.pgConnectionString(dbname) |
| 137 | |
| 138 | finalerr := retryutil.Retry(constants.PostgresConnectTimeout, constants.PostgresConnectRetryTimeout, |
| 139 | func() (bool, error) { |
| 140 | var err error |
| 141 | conn, err = sql.Open("postgres", connstring) |
| 142 | if err == nil { |
| 143 | err = conn.Ping() |
| 144 | } |
| 145 | |
| 146 | if err == nil { |
| 147 | return true, nil |
| 148 | } |
| 149 | |
| 150 | if _, ok := err.(*net.OpError); ok { |
| 151 | c.logger.Warningf("could not connect to Postgres database: %v", err) |
| 152 | return false, nil |
| 153 | } |
| 154 | |
| 155 | if err2 := conn.Close(); err2 != nil { |
| 156 | c.logger.Errorf("error when closing Postgres connection after another error: %v", err) |
| 157 | return false, err2 |
| 158 | } |
| 159 | |
| 160 | // Retry open connection until succeeded. |
| 161 | c.logger.Warningf("could not connect to Postgres database: %v", err) |
| 162 | return false, nil |
| 163 | }) |
| 164 | |
| 165 | if finalerr != nil { |
| 166 | return fmt.Errorf("could not init db connection: %v", finalerr) |
| 167 | } |
| 168 | // Limit ourselves to a single connection and allow no idle connections. |
| 169 | conn.SetMaxOpenConns(1) |
| 170 | conn.SetMaxIdleConns(-1) |
| 171 | |
| 172 | if c.pgDb != nil { |
| 173 | msg := "closing an existing connection before opening a new one to %s" |
| 174 | c.logger.Warningf(msg, dbname) |
| 175 | c.closeDbConn() |
| 176 | } |
| 177 | |
| 178 | c.pgDb = conn |
| 179 | |
| 180 | return nil |
| 181 | } |
| 182 | |
| 183 | func (c *Cluster) connectionIsClosed() bool { |
| 184 | return c.pgDb == nil |
no test coverage detected