package postgres import ( "database/sql" "github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql" "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/util/pgxutil" ) // Connection is how a postgres filer store reaches its database. type Connection struct { pgxutil.DSNOptions MaxIdle, MaxOpen, MaxLifetimeSeconds int } func ReadConnection(configuration util.Configuration, prefix string) Connection { // Fewer idle slots than concurrent operations means a fresh connection per // operation, until the filer runs out of ephemeral ports. connection_max_open // stays unset: a listing runs a second query from its own callback, so a // bounded pool deadlocks once the concurrency reaches it. configuration.SetDefault(prefix+"connection_max_idle", 50) configuration.SetDefault(prefix+"connection_max_lifetime_seconds", 300) return Connection{ DSNOptions: pgxutil.DSNOptions{ Hostname: configuration.GetString(prefix + "hostname"), Port: configuration.GetInt(prefix + "port"), User: configuration.GetString(prefix + "username"), Password: configuration.GetString(prefix + "password"), Database: configuration.GetString(prefix + "database"), Schema: configuration.GetString(prefix + "schema"), SSLMode: configuration.GetString(prefix + "sslmode"), SSLCert: configuration.GetString(prefix + "sslcert"), SSLKey: configuration.GetString(prefix + "sslkey"), SSLRootCert: configuration.GetString(prefix + "sslrootcert"), SSLCRL: configuration.GetString(prefix + "sslcrl"), PgBouncerCompatible: configuration.GetBool(prefix + "pgbouncer_compatible"), }, MaxIdle: configuration.GetInt(prefix + "connection_max_idle"), MaxOpen: configuration.GetInt(prefix + "connection_max_open"), MaxLifetimeSeconds: configuration.GetInt(prefix + "connection_max_lifetime_seconds"), } } // Open opens the store's connection pools. func (c Connection) Open(store *abstract_sql.AbstractSqlStore) error { dsn, adaptedDSN := pgxutil.BuildDSN(c.DSNOptions) open := func() (*sql.DB, error) { return pgxutil.OpenDB(dsn, adaptedDSN, c.PgBouncerCompatible, c.MaxIdle, c.MaxOpen, c.MaxLifetimeSeconds) } db, err := open() if err != nil { return err } return store.UseConnectionPools(db, open, c.MaxIdle, c.MaxOpen, c.MaxLifetimeSeconds) }