Skip to content

Primary/Secondary aware connection handling - #2778

Closed
mintsoft wants to merge 23 commits into
npgsql:devfrom
mintsoft:failover-advanced
Closed

mintsoft wants to merge 23 commits into
npgsql:devfrom
mintsoft:failover-advanced

Conversation

@mintsoft

@mintsoft mintsoft commented Jan 5, 2020 •

Copy link
Copy Markdown
Contributor

@roji As I just mentioned, working towards: #732

The core functionality I'm aiming for here is:

  • Application should be able to give a Host=a,b,c connection string and the driver will connect to each of them in-turn and use the first server that works
  • Application should be able to set ServerType=Primary to guarantee that a connection to a writable server will be handed out if one is available and error otherwise
  • Application should be able to set ServerType=Secondary to guarantee (as close as possible) that a connection to a readonly server will be handed out (whether this is a actually a guarantee, or a preferSecondary concept, I'm not sure yet)
  • Application with connectionstring of Host=PG1,PG2;ServerType=master in the event of PG1 going down, and PG2 becoming primary should be able to continue working without requiring a hard recycle/restart.
  • ConnectionPool (min, max, pruning etc) should be as close to the current behaviour as possible

I've given this a test in a few simple failover scenarios and it seems to reconnect etc, however I've not done any "to destruction" testing yet.

I've ripped out the global state cache ideal that we were discussing in favour of each NpgsqlConnector knowing what type of server it's connected to. When NpgsqConnection pulls the connector out of the pool, it checks it against whether it's what it "wants" and reconnects if it isn't which is much simpler.

I do have an unsolved problem with this however, if a user has connectionpool enabled, but not keepalives; there will be no point for each connector to have its connected state updated if the server changes from secondary to primary (for example) and I can't see any mechanism for it to ever be updated unless the connection itself gets reset at some point. I guess https://www.postgresql.org/message-id/flat/[email protected] might fix that?

@mintsoft mintsoft changed the title WIP: Primary/Secondary aware connection handling Primary/Secondary aware connection handling Jan 5, 2020
@flyingpie

flyingpie commented Jan 14, 2020 •

Copy link
Copy Markdown

@mintsoft Great work so far, it's working like a charm, for at least a large part of the scenarios :)

A problem I'm having though.

When a connection to a host fails, a call to Break() is made, to basically undo the current connection attempt:
https://github.com/mintsoft/npgsql/blob/failover-advanced/src/Npgsql/NpgsqlConnector.cs#L436
https://github.com/mintsoft/npgsql/blob/failover-advanced/src/Npgsql/NpgsqlConnector.cs#L442

Within the Break() method, the "Connection"-property is set to "null", which causes problems later on, within "LoadDatabaseInfo()":
https://github.com/mintsoft/npgsql/blob/failover-advanced/src/Npgsql/NpgsqlConnector.cs#L1442

This is problematic for when a host is not reachable at all (eg. machine not reachable or Postgres server crashed entirely).

Since the exception gets thrown within a catch-block, it kills the entire connection process.

For my local tests, I commented out the calls to Break(), though this is probably not the greatest solution.

Not entirely sure what the correct way of doing this would be, but feel free to let me know if I can help out.

@mintsoft

Copy link
Copy Markdown
Contributor Author

Hiya @flyingpie

Thanks for testing that! That's really useful information, I'll address that shortly. I had a feeling there might end up being a problem with that reset mechanism, glad you found it :)

@mintsoft

Copy link
Copy Markdown
Contributor Author

@flyingpie Actually I've just tried that in my little test program, connecting to a non existant host like:

using(var con = new NpgsqlConnection("Host=172.30.0.24;username=robtest_login;password=robtest_password;Database=robtest;TargetServerType=Primary;Pooling=true;KeepAlive=5;Enlist=false;Minimum Pool Size=4;");
con.Open();

and I get a TimeoutException as I'd expect:

Npgsql.NpgsqlException (0x80004005): Exception while connecting ---> System.TimeoutException: Timeout during connection attempt
   at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout) in C:\Users\Rob\source\repos\npgsql\src\Npgsql\NpgsqlConnector.cs:line 739
   at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout) in C:\Users\Rob\source\repos\npgsql\src\Npgsql\NpgsqlConnector.cs:line 756
   at Npgsql.NpgsqlConnector.<RawOpen>d__155.MoveNext() in C:\Users\Rob\source\repos\npgsql\src\Npgsql\NpgsqlConnector.cs:line 681

Is there something different/significant about my connection string vs the one you were testing with?

@flyingpie

flyingpie commented Jan 15, 2020 •

Copy link
Copy Markdown

@mintsoft Thank you!

2 things:

  • There is a difference in "the server does not exist" (which usually causes a timeout-exception) and "server is not hosting on this port" (which usually causes a socket-exception. That mostly means that I'm getting an exception immediately, while your test causes an exception after a delay.

  • The exception is thrown just fine, but it breaks the "let's try the next host"-mechanism. Since the Connection-property is set to "null", whenever the connection ultimately succeeds, it still fails with the above problem.

You should be able to get the same results if you use 2 hosts, both of which exist, but one of which doesn't actually host a Postgres instance.

Does that clear stuff up?

@mintsoft

Copy link
Copy Markdown
Contributor Author

@flyingpie Thats perfect, I've got that reproduced now. Thanks

@hkheireddine

Copy link
Copy Markdown

Hey guys, we have implemented PAF for our project and could not found any.Net library that supports master and secondary servers. Any idea when this will be finalized?

@mintsoft

Copy link
Copy Markdown
Contributor Author

@hkheireddine I'm hoping to get this in pretty quickly, however it's not entirely dependant on me :) There's the bug raised by @flyingpie that needs fixing and there's a problem (possibly the same, possibly different) that's causing some of the tests to hang/break. Once that's done I think functionally it's ready for prime-time however I'm sure there will be some changes in the review etc.

It's difficult to say when it'll be released. If you wanted to help out either with coding or testing though configurations, that would be much appreciated! The more environments it's been thrown at, the better it will be when it's ready

@mintsoft

Copy link
Copy Markdown
Contributor Author

@flyingpie I think I've just pushed a fix for that situation in 2a8b998 essentially not calling Break in that situation should be fine as the state will get replaced in the next connect attempt anyway, but we might need to cleanup some connection that's the same as if the driver connects to the wrong type of server. I'm not 100% that covers all the possibilities but I think they'll come out of the woodwork.

Thanks for the feedback, much appreciated!

@flyingpie

Copy link
Copy Markdown

@mintsoft That's nice! The socket is the only (unmanaged) thing that gets set up during the connection, right? Cause in that case, the SoftCleanup should be fine.

Just a thought, but maybe this is indicative of the need for a layer of abstraction between the actual connection and the fact that we're switching between multiple hosts. In the same way that there already is an abstraction between a connection and a pool of connections. Just a thought though.

Nice work, I'll get the latest bits and try time out.

@mintsoft

Copy link
Copy Markdown
Contributor Author

@flyingpie

Just a thought, but maybe this is indicative of the need for a layer of abstraction between the actual connection and the fact that we're switching between multiple hosts. In the same way that there already is an abstraction between a connection and a pool of connections. Just a thought though.

Yeah I've had similiar thoughts myself. I've deliberately tried to keep this light-touch at the moment as I don't really want to mess with the ConnectionPool implementation as it's being heavily worked-on elsewhere. That said, once it's all together I'm pretty sure a much cleaner implementation will come out of the woodwork.

If you find any other issues, let me know and I'll patch them up!

@mintsoft

Copy link
Copy Markdown
Contributor Author

@roji @YohDeadfall @austindrenski I think this is in a "done" state now. I've fixed up the tests and added some explicit tests for Secondary failover (these require another PG cluster which is in recovery to pass, which I've added as the environmental variable NPGSQL_SECONDARY_HOST).

I think (despite the number of commits), it's actually reasonably simple overall. Although I'm a little concerned about the change I had to make here to get the tests to pass: 4abc059 I think that could be a breaking change if some client code is hard-coupled to the events being fired?

Anyway, welcome any feedback you guys have got.

@emz00 emz00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for doing this! (Just adding a comment on potentially confusing behaviour, as a user of Npgsql interested in this feature.)

Comment thread src/Npgsql/NpgsqlConnector.cs Resolved
@mintsoft

Copy link
Copy Markdown
Contributor Author

@loop-evgeny should be resolved in 6a5cecd

@YohDeadfall YohDeadfall left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thank you for the work! Here are some comment.

Comment thread src/Npgsql/NpgsqlConnector.cs Resolved
Comment thread src/Npgsql/NpgsqlConnector.cs Resolved
Comment thread src/Npgsql/NpgsqlServerStatus.cs Resolved
Comment thread src/Npgsql/PregeneratedMessages.cs Resolved
…ve this can be a universal truth as an entire pg cluster is either primary or not.
…g requires the connector.connection to be non-null and Close()/Break() were nulling it out through cleanup
…nnection for the keepalives; reading the data using any mechanism here so far results in NREs
…r; we need some sort of softer cleanup for the connection etc.
…n't in the right state and we're probably better off forcing reconnection in that state (definitely true for "Down")
…n the connection string has had to fail over
…ts in a null reference

see: #2778 (comment)

for an example, however I think I can share the cleanup between the incorrect-type-of-server and that situation because we will either replace the state in the next connection attempt, or throw on the next attempt anyway and invalidate the whole NpgsqlConnector instance
…ctedHost when attempting to cancel, so we need to clone the value when creating the terminating connection
… the reads as part of the keepalive. We don't need to do that kind of keepalive here, we really only want the background thread to do it
…n timeout duration per host but attempt to keep an overall "connectionTime" contract with the client code. An alternative would be to have a configurable PerHostTimeout (probably my actual preference as it puts control back in the hands of the client application)
…ative would be to make this a preference, i.e. permit a connection to a primary if there are no secondaries available
…icit as they require yet another PG cluster configured for testing
…m like: "A,B,C,D,A" we shouldn't give up after the first host.
@mintsoft

mintsoft commented Feb 2, 2020

Copy link
Copy Markdown
Contributor Author

Just resolved some merge issues so should still be ready to go

@mintsoft

Copy link
Copy Markdown
Contributor Author

@roji appreciate that you're busy, but any chance of some initial feedback on this?

@roji

roji commented Feb 25, 2020

Copy link
Copy Markdown
Member

@mintsoft sorry for the long silence - I really try my best to respond to PRs quickly, but at the moment am deep into the multiplexing work (#2852, which incidentally will need to be resolved with this at some point) as well as some vacation time. I'll do my best to give this a proper review in the coming days.

@roji roji left a comment

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 started reviewing the PR, but at some point realized there's a fundamental issue. The separate review comments are partial (I didn't finish the review), but the thing to be worked out is the general approach and how it tackles the problems I discuss below.

The current open behavior seems to attempt to get an idle connector from the pool. If that connector happens to correspond to the type the user requested (primary, secondary), it's returned immediately - all good. However, if it isn't, that connector is returned back to the pool, and you then proceed to call OpenLong, which will open a new connection - and then you return that. First, there's no reason to expect this new connection to be of the type the user requested - we should be remembering, for each host in the connection string, what its last-known status was and establish connections accordingly (at the moment you track server type on each connector, rather than on hosts in general). Another problem is that there may already be idle connectors in the pool, of the right type - but they just happened not to be the first returned when you called TryAllocateFast. That's not good - as long as there are idle connectors (of the desired type), we should not be opening new physical connections.

In addition, if we happen to be at Max Pool Size, OpenLong will try getting an idle connector from the pool again (since it sees there are idle connectors), which may again be of the wrong type - that's not being checked right now in any way. Even it were checked, it's not clear what you'd do at that point: call OpenLong again? If the pool happens to be full of the wrong type of connectors, you'd just loop forever.

Another issue is that the new connection logic in NpgsqlConnector.Open simply tries to connect to the hosts given in the connection string, one-by-one, without taking primary/secondary into account. I'd expect us to track, per-host, what its last known type is (primary or secondary), and this way if we need to establish a new primary connection (because there are zero idle ones in the pool), we know to try to connect to a last-known primary host, rather than any host.

What I'm trying to say, is that the advanced version of this feature - primary/secondary connection management - is quite complex, and I don't think it's possible to do it without going into the pool and making it aware of the whole business. That would most probably mean maintaining two different idle lists (primary and secondary) inside the pool, and going to the right list based on what the user is asking for. As discussed in the issue comments, we'd also have to tackle issues such killing idle secondary connections if a primary one is requested but the pool is full and no idle primaries are available.

However, we should definitely not do any large-scale work on the pool at this point, since I'm working in parallel on rewriting it for multiplexing support (see an early draft in #2852). The pool already looks very different than it does today (and is in fact considerably simpler in many respects), so I'd recommend holding off on this work until that is done. A good spec of the behavior and/or architecture could be done before jumping into implementation.

internal enum ServerType
{
Unknown,
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?)

/// </summary>
internal enum ServerType
{
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

/// <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.

// 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.


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.

/// <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

// 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

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.

@mintsoft

mintsoft commented Mar 4, 2020

Copy link
Copy Markdown
Contributor Author

The current open behavior seems to attempt to get an idle connector from the pool. If that connector happens to correspond to the type the user requested (primary, secondary), it's returned immediately - all good. However, if it isn't, that connector is returned back to the pool, and you then proceed to call OpenLong, which will open a new connection - and then you return that. First, there's no reason to expect this new connection to be of the type the user requested - we should be remembering, for each host in the connection string, what its last-known status was and establish connections accordingly (at the moment you track server type on each connector, rather than on hosts in general). Another problem is that there may already be idle connectors in the pool, of the right type - but they just happened not to be the first returned when you called TryAllocateFast. That's not good - as long as there are idle connectors (of the desired type), we should not be opening new physical connections.

Yeah, totally agree. We discussed it previously and I got the impression that you would prefer to not maintain a global Host state concept anywhere in the driver; but totally happy to revisit that.

In addition, if we happen to be at Max Pool Size, OpenLong will try getting an idle connector from the pool again (since it sees there are idle connectors), which may again be of the wrong type - that's not being checked right now in any way. Even it were checked, it's not clear what you'd do at that point: call OpenLong again? If the pool happens to be full of the wrong type of connectors, you'd just loop forever.

True, I was basically relying on the idle pruning to fix that; however no guarantee that users have it enabled!

What I'm trying to say, is that the advanced version of this feature - primary/secondary connection management - is quite complex, and I don't think it's possible to do it without going into the pool and making it aware of the whole business. That would most probably mean maintaining two different idle lists (primary and secondary) inside the pool, and going to the right list based on what the user is asking for. As discussed in the issue comments, we'd also have to tackle issues such killing idle secondary connections if a primary one is requested but the pool is full and no idle primaries are available.
However, we should definitely not do any large-scale work on the pool at this point, since I'm working in parallel on rewriting it for multiplexing support (see an early draft in #2852). The pool already looks very different than it does today (and is in fact considerably simpler in many respects), so I'd recommend holding off on this work until that is done. A good spec of the behavior and/or architecture could be done before jumping into implementation.

Cool, I agree. It seems like the best option is to extend the ConnectionPool to include host state information or similiar so we can basically have our cake and eat it.

Do you think it's likely that the work in #2852 is going to end up drastically different to where it is now? Basically I'd like to rebase this from there and start to flesh it out and see if I can provide any feedback against it that would make this feature easier to handle etc before it's merged if possible.

@roji

roji commented Mar 4, 2020

Copy link
Copy Markdown
Member

Do you think it's likely that the work in #2852 is going to end up drastically different to where it is now? Basically I'd like to rebase this from there and start to flesh it out and see if I can provide any feedback against it that would make this feature easier to handle etc before it's merged if possible.

I'd definitely hold off on any pooling-related changes before #2852 is merged. On a positive note, it's the most high-priority thing on my plate and it's getting close to done (I have some more unpushed work), so it shouldn't take very long to complete.

@mintsoft

Copy link
Copy Markdown
Contributor Author

@roji I can see the first version of multiplexing in now (4bd4115). Are you expecting any fundamental changes to the pooling implementation or am I good to have a stab at reimplementing this?

@roji

roji commented Jun 20, 2020

Copy link
Copy Markdown
Member

@mintsoft yes, now would be a good time to work on anything touching the pool - I anticipate doing some minor fixes, but nothing far-reaching.

Some thoughts... I'd love to be able to ship this with 5.0, but it is obviously not a trivial feature. To make sure we go in the right direction, I'd advise putting together a quick spec of how you intend to tackle things; it doesn't have to be formal or anything - just something we can discuss together before too much code gets written. It's also a good idea to submit early draft versions and iterate, rather than working a lot and submitting one big PR in the end. I'd also be fine with not implementing this for multiplexing, for now - that should simplify the design process etc. (though we should be careful not to do anything that's fundamentally incompatible with it).

Does the above sound reasonable?

@mintsoft

mintsoft commented Jun 27, 2020 •

Copy link
Copy Markdown
Contributor Author

Some thoughts... I'd love to be able to ship this with 5.0, but it is obviously not a trivial feature.

Yeah absolutely, I'm not too fussed on when it gets folded into a release.

To make sure we go in the right direction, I'd advise putting together a quick spec of how you intend to tackle things; it doesn't have to be formal or anything - just something we can discuss together before too much code gets written. It's also a good idea to submit early draft versions and iterate, rather than working a lot and submitting one big PR in the end. I'd also be fine with not implementing this for multiplexing, for now - that should simplify the design process etc. (though we should be careful not to do anything that's fundamentally incompatible with it).

Does the above sound reasonable?

That sounds fine in concept, however the biggest issue with producing a specification or similiar (from my perspective) is that I'm not remotely familiar with the actual architecture of the code; I can put some thoughts together but there's no guarantee that they'll make any sense relative to the implementation. In order for me to be able to see and describe how I want to implement it, I basically have to implement it anyway and then de-C# the code back into words and discuss. The way I tend to work, I'm happier throwing away/reimplementing 10+ versions of the code as I find it an easier way to express what I'm thinking vs an abstract conversation. That said, if it's the way you prefer to work I'll endeavour to oblige!

@roji

roji commented Jun 27, 2020

Copy link
Copy Markdown
Member

@mintsoft no problem, definitely don't want to get hung up on process here. If you prefer just coding it up and are willing to accept that some work will be lost, we can do it that way. I'd still recommend iteratively submitting early drafts rather than developing the whole thing though.

@mintsoft

mintsoft commented Aug 9, 2020

Copy link
Copy Markdown
Contributor Author

Closing this in favour of #3098 as it's almost at the same point now anyway

@mintsoft mintsoft closed this Aug 9, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants