Repository navigation
Primary/Secondary aware connection handling #2778
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
Changes from all commits
d463e28
8064de0
0b3b66f
79d5277
a428148
233daae
3271e1e
27b6752
8827342
5047f89
526f727
11c78fd
f5da5ae
a054aa6
de01db4
8455778
099f840
5da8185
2636377
a29b547
d49d62c
1177f4a
b259dbc
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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)) | ||
| 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(); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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, | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -248,6 +248,7 @@ internal NpgsqlConnector(NpgsqlConnection connection) | |
| ProvideClientCertificatesCallback = connector.ProvideClientCertificatesCallback; | ||
| UserCertificateValidationCallback = connector.UserCertificateValidationCallback; | ||
| ProvidePasswordCallback = connector.ProvidePasswordCallback; | ||
| ConnectedHost = connector.ConnectedHost; | ||
| } | ||
|
|
||
| /// <summary> | ||
|
|
@@ -349,6 +350,9 @@ bool IsConnected | |
|
|
||
| bool _isConnecting; | ||
|
|
||
| string? ConnectedHost; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should just reuse the existing |
||
| ServerType ConnectedServerType; | ||
|
|
||
| #endregion | ||
|
|
||
| #region Open | ||
|
|
@@ -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); | ||
|
|
@@ -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 | ||
| { | ||
|
|
@@ -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> | ||
|
|
@@ -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 | ||
|
|
@@ -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 | ||
| { | ||
|
|
@@ -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(); | ||
| } | ||
|
|
||
|
|
@@ -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(); | ||
| } | ||
|
|
||
|
|
@@ -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(); | ||
| } | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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;"); | ||
|
|
@@ -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) | ||
| { | ||
|
|
@@ -2042,5 +2130,16 @@ internal enum DataRowLoadingMode | |
| Skip | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Represents what state the connected server is in | ||
| /// </summary> | ||
| internal enum ServerType | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sure |
||
| { | ||
| Unknown, | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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, | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
| } | ||
There was a problem hiding this comment.
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.