Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
d463e28
Maintaining a view of which hosts are primary vs secondaries. I belie…
mintsoft Dec 30, 2019
8064de0
This is working for the first server, however in a failover condition…
mintsoft Dec 30, 2019
0b3b66f
This was throwing a null ref, it looks like the LoadDatabaseInfo thin…
mintsoft Dec 30, 2019
79d5277
I'm going to need to be able to query on a connector rather than a co…
mintsoft Dec 31, 2019
a428148
According to https://www.postgresql.org/docs/9.3/protocol-message-for…
mintsoft Dec 31, 2019
233daae
It looks like Close() bombs out the userAgent underneath the Connecto…
mintsoft Dec 31, 2019
3271e1e
When getting from the pool; we need to throwaway connections that are…
mintsoft Dec 31, 2019
27b6752
We want to force reconnection in the scenario that the connection isn…
mintsoft Dec 31, 2019
8827342
Following the example of keepalives, we might as well have this gener…
mintsoft Dec 31, 2019
5047f89
Previously the connection to the first server was being kept open whe…
mintsoft Jan 2, 2020
526f727
We need to close the connection entirely if we're going to reopen aga…
mintsoft Jan 5, 2020
11c78fd
Trying to make this a little clearer about what 'f' is etc
mintsoft Jan 8, 2020
f5da5ae
In the situation where a connection is refused, calling Break() resul…
mintsoft Jan 18, 2020
a054aa6
Now that connector has to run a query to confirm the type of server, …
mintsoft Jan 19, 2020
de01db4
CommandTests.Cancel exposes that we need to connect to the same Conne…
mintsoft Jan 19, 2020
8455778
WaitAsyncCancellation was hanging forever, I think this is because of…
mintsoft Jan 21, 2020
099f840
Adding very basic tests. I've decided to divide the overall connectio…
mintsoft Jan 22, 2020
5da8185
When asking for an unfulfillable contract, we should throw. An altern…
mintsoft Jan 22, 2020
2636377
This should allow connection to any server type
mintsoft Jan 22, 2020
a29b547
Explicit tests for the failover behaviour; I've marked these are Expl…
mintsoft Jan 22, 2020
d49d62c
If the client application wants to explicitly loop the retry mechanis…
mintsoft Jan 25, 2020
1177f4a
Feedback From @YohDeadfall
mintsoft Jan 27, 2020
b259dbc
Merge branch 'dev' into failover-advanced
mintsoft Feb 20, 2020
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
13 changes: 12 additions & 1 deletion src/Npgsql/NpgsqlConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,19 @@ Task Open(bool async, CancellationToken cancellationToken)

Log.Trace("Opening connection...");

if (_pool == null || Settings.Enlist || !_pool.TryAllocateFast(this, out Connector))
if (_pool == null || Settings.Enlist)
return OpenLong();
if (!_pool.TryAllocateFast(this, out Connector))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See general comment about this in the review.

return OpenLong();
else if (Connector.IsAppropriateFor(Settings.TargetServerType) == false)
{
// in the event that the underlying PG server has changed type (i.e. promoted to be a primary)
// we can get a connection to the wrong type of server from the pool and need to use the reconnect
// logic to attempt to get back to the right type

Close();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Closing and reopening isn't a good way to go here: among other things it would generate duplicate log messages, emit duplicate OnStateChange events... I'd prefer if the whole thing were self-contained in the pool, without NpgsqlConnection needing to be aware of it.

return OpenLong();
}

_userFacingConnectionString = _pool.UserFacingConnectionString;

Expand Down
39 changes: 39 additions & 0 deletions src/Npgsql/NpgsqlConnectionStringBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,25 @@ public string? Timezone
}
string? _timezone;

/// <summary>
/// Gets or sets the PostgreSQL target server.
/// </summary>
[Category("Connection")]
[Description("Gets or sets the PostgreSQL target server.")]
[DisplayName("TargetServerType")]
[DefaultValue(TargetServerType.Any)]
[NpgsqlConnectionStringProperty]
public TargetServerType TargetServerType
{
get => _targetservertype;
set
{
_targetservertype = value;
SetValue(nameof(TargetServerType), value);
}
}
TargetServerType _targetservertype;

#endregion

#region Properties - Security
Expand Down Expand Up @@ -1436,5 +1455,25 @@ public enum SslMode
Require,
}

/// <summary>
/// Specifies server type preference.
/// </summary>
public enum TargetServerType
{
/// <summary>
/// Try to connect every server in order.
/// </summary>
Any,
/// <summary>
/// Primary (writable) server is selected for the connection.
/// </summary>
Primary,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand that at this point you're not doing PreferPrimary/Secondary? Is it simply out of scope for the moment, or some other reason?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's basically difficult to do preference with the connect/disconnect model I've got here as you'd need to have information about the preferred connections in the pool before attempting to get one.

/// <summary>
/// Secondary (readonly) server is selected for the connection.
/// </summary>
Secondary,
}


#endregion
}
6 changes: 3 additions & 3 deletions src/Npgsql/NpgsqlConnector.Auth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ async Task AuthenticateGSS(bool async)
{
try
{
var targetName = $"{KerberosServiceName}/{Host}";
var targetName = $"{KerberosServiceName}/{ConnectedHost}";
if (async)
await negotiateStream.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName);
else
Expand Down Expand Up @@ -371,7 +371,7 @@ class AuthenticationCompleteException : Exception { }
if (passFilePath != null && File.Exists(passFilePath))
{
var matchingEntry = new PgPassFile(passFilePath)
.GetFirstMatchingEntry(Host, Port, Settings.Database!, username);
.GetFirstMatchingEntry(ConnectedHost, Port, Settings.Database!, username);
if (matchingEntry != null)
{
Log.Trace("Taking password from pgpass file");
Expand All @@ -385,7 +385,7 @@ class AuthenticationCompleteException : Exception { }
Log.Trace($"Taking password from {nameof(ProvidePasswordCallback)} delegate");
try
{
return ProvidePasswordCallback(Host, Port, Settings.Database!, username);
return ProvidePasswordCallback(ConnectedHost!, Port, Settings.Database!, username);
}
catch (Exception e)
{
Expand Down
191 changes: 145 additions & 46 deletions src/Npgsql/NpgsqlConnector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ internal NpgsqlConnector(NpgsqlConnection connection)
ProvideClientCertificatesCallback = connector.ProvideClientCertificatesCallback;
UserCertificateValidationCallback = connector.UserCertificateValidationCallback;
ProvidePasswordCallback = connector.ProvidePasswordCallback;
ConnectedHost = connector.ConnectedHost;
}

/// <summary>
Expand Down Expand Up @@ -349,6 +350,9 @@ bool IsConnected

bool _isConnecting;

string? ConnectedHost;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should just reuse the existing Host member to hold the actual host the connector is connected to, rather than introducing this new member. A connector is a physical connection, always to a specific host.

ServerType ConnectedServerType;

#endregion

#region Open
Expand All @@ -358,7 +362,7 @@ bool IsConnected
/// </summary>
/// <remarks>Usually called by the RequestConnector
/// Method of the connection pool manager.</remarks>
internal async Task Open(NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken)
internal async Task Open(NpgsqlTimeout connectTimeout, bool async, CancellationToken cancellationToken)
{
Debug.Assert(Connection != null && Connection.Connector == this);
Debug.Assert(State == ConnectorState.Closed);
Expand All @@ -369,45 +373,78 @@ internal async Task Open(NpgsqlTimeout timeout, bool async, CancellationToken ca
_isConnecting = true;
State = ConnectorState.Connecting;

try {
await RawOpen(timeout, async, cancellationToken);
var username = GetUsername();
if (Settings.Database == null)
Settings.Database = username;
WriteStartupMessage(username);
await Flush(async);
timeout.Check();
try
{
var hosts = Host.Split(',');
for (var hostIndex = 0 ; hostIndex < hosts.Length ; hostIndex++)
{
var host = hosts[hostIndex];
try
{
var secondsPerHost = connectTimeout.Duration.TotalSeconds / hosts.Length;
var timeout = new NpgsqlTimeout(TimeSpan.FromSeconds(secondsPerHost));
ConnectedHost = host;
await RawOpen(timeout, async, cancellationToken);
var username = GetUsername();
if (Settings.Database == null)
Settings.Database = username;
WriteStartupMessage(username);
await Flush(async);
timeout.Check();
connectTimeout.Check();

await Authenticate(username, timeout, async);
await Authenticate(username, timeout, async);

// We treat BackendKeyData as optional because some PostgreSQL-like database
// don't send it (CockroachDB, CrateDB)
var msg = await ReadMessage(async);
if (msg.Code == BackendMessageCode.BackendKeyData)
{
var keyDataMsg = (BackendKeyDataMessage)msg;
BackendProcessId = keyDataMsg.BackendProcessId;
_backendSecretKey = keyDataMsg.BackendSecretKey;
msg = await ReadMessage(async);
}
if (msg.Code != BackendMessageCode.ReadyForQuery)
throw new NpgsqlException($"Received backend message {msg.Code} while expecting ReadyForQuery. Please file a bug.");
// We treat BackendKeyData as optional because some PostgreSQL-like database
// don't send it (CockroachDB, CrateDB)
var msg = await ReadMessage(async);
if (msg.Code == BackendMessageCode.BackendKeyData)
{
var keyDataMsg = (BackendKeyDataMessage)msg;
BackendProcessId = keyDataMsg.BackendProcessId;
_backendSecretKey = keyDataMsg.BackendSecretKey;
msg = await ReadMessage(async);
}
if (msg.Code != BackendMessageCode.ReadyForQuery)
throw new NpgsqlException($"Received backend message {msg.Code} while expecting ReadyForQuery. Please file a bug.");

State = ConnectorState.Ready;
State = ConnectorState.Ready;

await LoadDatabaseInfo(timeout, async);
await LoadDatabaseInfo(timeout, async);
UpdateServerPrimaryStatus();

if (Settings.Pooling && DatabaseInfo.SupportsDiscard)
GenerateResetMessage();
Counters.NumberOfNonPooledConnections.Increment();
Counters.HardConnectsPerSecond.Increment();
Log.Trace($"Opened connection to {Host}:{Port}");
if (IsAppropriateFor(Settings.TargetServerType) == false)
{
SoftCleanup();
throw new NpgsqlException($"Host {ConnectedHost} was not of compatible type. Got: {ConnectedServerType} Expected: {Settings.TargetServerType}");
}

// If an exception occurs during open, Break() below shouldn't close the connection, which would also
// update pool state. Instead we let the exception propagate and get handled by the calling pool code.
// We use an extra state flag because the connector's State varies during the type loading query
// above (Executing, Fetching...). Note also that Break() gets called from ReadMessageLong().
_isConnecting = false;
if (Settings.Pooling && DatabaseInfo.SupportsDiscard)
GenerateResetMessage();
Counters.NumberOfNonPooledConnections.Increment();
Counters.HardConnectsPerSecond.Increment();
Log.Trace($"Opened connection to {ConnectedHost}:{Port}");

// If an exception occurs during open, Break() below shouldn't close the connection, which would also
// update pool state. Instead we let the exception propagate and get handled by the calling pool code.
// We use an extra state flag because the connector's State varies during the type loading query
// above (Executing, Fetching...). Note also that Break() gets called from ReadMessageLong().
_isConnecting = false;
break;
}
catch (SocketException)
{
if (hostIndex == hosts.Length - 1)
throw;
SoftCleanup();
}
catch (NpgsqlException)
{
if (hostIndex == hosts.Length - 1)
throw;
SoftCleanup();
}
}
}
catch
{
Expand All @@ -429,6 +466,52 @@ internal async Task LoadDatabaseInfo(NpgsqlTimeout timeout, bool async)
TypeMapper.Bind(DatabaseInfo);
}

internal void UpdateServerPrimaryStatus()
{
try
{
StartUserAction();
WritePregenerated(PregeneratedMessages.ServerIsSecondary);
Flush();

var columnsMsg = ReadMessage();
var rowMsg = Expect<DataRowMessage>(ReadMessage(), this);

var columnCount = ReadBuffer.ReadInt16();
var lengthOfBooleanColumn = ReadBuffer.ReadInt32();
var resultSetBuffer = new byte[lengthOfBooleanColumn];
ReadBuffer.ReadBytes(resultSetBuffer, 0, lengthOfBooleanColumn);

var serverIsPrimary = resultSetBuffer[0] == 'f';
ConnectedServerType = serverIsPrimary ? ServerType.Primary : ServerType.Secondary;

SkipUntil(BackendMessageCode.ReadyForQuery);
EndUserAction();
}
catch (SocketException)
{
ConnectedServerType = ServerType.Down;
}
catch (NpgsqlException)
{
ConnectedServerType = ServerType.Down;
}
}

internal bool IsAppropriateFor(TargetServerType targetServerType)
{
if (ConnectedServerType == ServerType.Down)
return false;
if (targetServerType == TargetServerType.Any)
return true;
if (ConnectedServerType == ServerType.Primary && targetServerType == TargetServerType.Primary)
return true;
if (ConnectedServerType == ServerType.Secondary && targetServerType == TargetServerType.Secondary)
return true;

return false;
}

void WriteStartupMessage(string username)
{
var startupParams = new Dictionary<string, string>
Expand Down Expand Up @@ -557,9 +640,9 @@ async Task RawOpen(NpgsqlTimeout timeout, bool async, CancellationToken cancella

var sslStream = new SslStream(_stream, leaveInnerStreamOpen: false, certificateValidationCallback);
if (async)
await sslStream.AuthenticateAsClientAsync(Host, clientCertificates, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, Settings.CheckCertificateRevocation);
await sslStream.AuthenticateAsClientAsync(ConnectedHost, clientCertificates, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, Settings.CheckCertificateRevocation);
else
sslStream.AuthenticateAsClient(Host, clientCertificates, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, Settings.CheckCertificateRevocation);
sslStream.AuthenticateAsClient(ConnectedHost, clientCertificates, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, Settings.CheckCertificateRevocation);
_stream = sslStream;
timeout.Check();
ReadBuffer.Clear(); // Reset to empty after reading single SSL char
Expand All @@ -571,7 +654,7 @@ async Task RawOpen(NpgsqlTimeout timeout, bool async, CancellationToken cancella
}
}

Log.Trace($"Socket connected to {Host}:{Port}");
Log.Trace($"Socket connected to {ConnectedHost}:{Port}");
}
catch
{
Expand Down Expand Up @@ -600,15 +683,15 @@ async Task RawOpen(NpgsqlTimeout timeout, bool async, CancellationToken cancella
void Connect(NpgsqlTimeout timeout)
{
EndPoint[] endpoints;
if (!string.IsNullOrEmpty(Host) && Host[0] == '/')
if (!string.IsNullOrEmpty(ConnectedHost) && ConnectedHost![0] == '/')
{
endpoints = new EndPoint[] { new UnixEndPoint(Path.Combine(Host, $".s.PGSQL.{Port}")) };
endpoints = new EndPoint[] { new UnixEndPoint(Path.Combine(ConnectedHost, $".s.PGSQL.{Port}")) };
}
else
{
// Note that there aren't any timeout-able DNS methods, and we want to use sync-only
// methods (not to rely on any TP threads etc.)
endpoints = Dns.GetHostAddresses(Host).Select(a => new IPEndPoint(a, Port)).ToArray();
endpoints = Dns.GetHostAddresses(ConnectedHost).Select(a => new IPEndPoint(a, Port)).ToArray();
timeout.Check();
}

Expand Down Expand Up @@ -675,14 +758,14 @@ void Connect(NpgsqlTimeout timeout)
async Task ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
{
EndPoint[] endpoints;
if (!string.IsNullOrEmpty(Host) && Host[0] == '/')
if (!string.IsNullOrEmpty(ConnectedHost) && ConnectedHost![0] == '/')
{
endpoints = new EndPoint[] { new UnixEndPoint(Path.Combine(Host, $".s.PGSQL.{Port}")) };
endpoints = new EndPoint[] { new UnixEndPoint(Path.Combine(ConnectedHost, $".s.PGSQL.{Port}")) };
}
else
{
// Note that there aren't any timeoutable or cancellable DNS methods
endpoints = (await Dns.GetHostAddressesAsync(Host).WithCancellation(cancellationToken))
endpoints = (await Dns.GetHostAddressesAsync(ConnectedHost).WithCancellation(cancellationToken))
.Select(a => new IPEndPoint(a, Port)).ToArray();
}

Expand Down Expand Up @@ -1367,6 +1450,13 @@ void Cleanup()
#pragma warning restore CS8625
}

private void SoftCleanup()
{
// TODO: There needs to be some sort of soft cleanup here, this.Close() is too much and this.Break() is too little.
// I think just closing the socket is enough as all the buffers etc aren't used until a connection is allocated?
if(_socket != null && _socket.Connected)
_socket.Close();
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: missing empty line

void GenerateResetMessage()
{
var sb = new StringBuilder("SET SESSION AUTHORIZATION DEFAULT;RESET ALL;");
Expand Down Expand Up @@ -1629,9 +1719,7 @@ void PerformKeepAlive(object? state)
return;

Log.Trace("Performed keepalive", Id);
WritePregenerated(PregeneratedMessages.KeepAlive);
Flush();
SkipUntil(BackendMessageCode.ReadyForQuery);
UpdateServerPrimaryStatus();
}
catch (Exception e)
{
Expand Down Expand Up @@ -2042,5 +2130,16 @@ internal enum DataRowLoadingMode
Skip
}

/// <summary>
/// Represents what state the connected server is in
/// </summary>
internal enum ServerType

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ServerType is an overly generic name which could mean many things - I'd prefer if we used a more specific name such as PrimarySecondaryServerType (even if the user-facing connection string parameter can stay TargetServerType to promote consistency with JDBC, libpq).

nit: omit the internal keyword as it's the default.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure

{
Unknown,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't seem to be used anywhere, what is the intended meaning/usage here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was going to be used for the scenario where it wasn't known yet before I put the querying logic to get the type into the actual connector itself

Down,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already have ConnectorState for checking whether we're connected or not (which seems the same as Down?)

Primary,
Secondary
}

#endregion
}
Loading