Repository navigation
return an error when the server reuses an open handle - #672
Conversation
| defer c.handlesMu.Unlock() | ||
|
|
||
| if _, ok := c.handles[handle]; ok { | ||
| return fmt.Errorf("sftp: server returned handle %q which is already open", handle) |
There was a problem hiding this comment.
The problem I see here is that we’re returning an error to the Open of the new file, but that’s not what I expect the behavior is on the problematic server. It has likely replaced the previous open file to the new file! We need to force an error condition out into the open File.
This is why I proposed the ForceSerialization. In this mode, an Opendir and Open would return some sort of error, indicating that a file is already open, and that the server doesn’t support opening more than one file at a time.
Checking the handles would be good to spot a need for this mode, but the error needs to basically shutdown the whole client and make it very loud that the server doesn’t support multiple files, and they need to use the forced serialization mode.
There was a problem hiding this comment.
That makes sense. By the time the duplicate handle comes back, the server has already replaced the first file, so failing the new Open doesn't help the File that's still open.
How about this:
- When
openoropendirgets a handle back that is already open, the client shuts down the connection with an error likesftp: server returned a handle that is already open; it does not support more than one open file at a time, use ForceSerialization. Requests in flight and any later ones, including on the oldFile, get that error wrapped withErrSSHFxConnectionLost, so existingerrors.Ischecks still work.Wait()returns it too. - A new
ForceSerialization()client option. With it,openandopendirreturn an error without sending the request if a handle is already open.
A few questions before I change the PR:
- In
ForceSerializationmode, should a second open return an error, or wait until the first file is closed? - Should
ForceSerializationalso send requests one at a time (no concurrent reads or writes,maxConcurrentRequestsof 1)? That would also cover the short-read servers in Incomplete downloads #424. - Do you want this in v1 in this PR, or only in v2?
There was a problem hiding this comment.
First, I’m thinking against the name ForceSerialization as this sort of sounds like it has to do with ordering of packets only (as demonstrated by your question 2), not necessarily one-file-at-a-time. I’m having trouble thinking of a better term though.
- waiting until the first file is closed could potentially lead to deadlocks. e.g. if a client opens a file to write, and file to read in separate threads, and expects writes to depend on the reads. There’s no good option here rather than to abort everything that is outstanding. (Even returning
SSH_FXP_DATApackets can no longer be relied on. Instead, it should return an syntheticSSH_FXP_STATUSwith codeSSH_FX_FAILUREand some sort of message about how the one-file-at-a-time mode prevents opening more than one file at a time. - The force one-file-at-a-time shouldn’t need to force serialization of reads and writes. As far as I know, the server for which this is a problem shouldn’t have any trouble handling multiple inflight packets.
- Since the server could be connected to by any client, we’ll want the functionality available in both. (And since a future
v1client will just wrapv2’s client, it will need the support anyways.)
There was a problem hiding this comment.
Addressed both parts: a duplicate handle now causes the connection to fail and broadcasts the duplicate-handle cause to in-flight operations, including the already-open File. With ForceSingleFile enabled, Open and Opendir reject a second handle locally with SSH_FX_FAILURE.
There was a problem hiding this comment.
This now follows the three points you outlined: a second open gets an immediate synthetic SSH_FX_FAILURE rather than waiting, reads and writes remain concurrent, and ForceSingleFile is available on this v1 client.
|
Addressed the duplicate-handle review feedback. A duplicate server handle now fails the existing file’s pending operations with a clear connection-lost error and closes its writer; |
|
Fixed the disconnect regression behind the failing integration checks. Ordinary server disconnects now return |
| // ForceSerialization restricts the client to one open file or directory at a time. | ||
| // A second open returns an SSH_FX_FAILURE status until the current handle is closed. | ||
| // This can be used with servers that cannot safely keep more than one handle open. | ||
| func ForceSerialization() ClientOption { |
There was a problem hiding this comment.
As I already brought up, I have soured on this name. I want something that is immediately clear that we’re forcing a mode that allows a single file open at a time, and ForceSerialization is too broad.
Maybe something like ForceSingleFile or ForceExclusivelyOneFile … I would hope for some help in creativity here.
There was a problem hiding this comment.
Renamed the public option to ForceSingleFile(). It describes the one-open-file-or-directory mode directly.
| // This can be used with servers that cannot safely keep more than one handle open. | ||
| func ForceSerialization() ClientOption { | ||
| return func(c *Client) error { | ||
| c.forceSerialization = true |
There was a problem hiding this comment.
I think internally, using forceSerialization isn’t too bad, but maybe forceFileSerialization instead?
This is an interesting situation where we can be more concise internally, while the external API should make its use much more unambiguous and apparent.
There was a problem hiding this comment.
The internal reservation is represented by singleFileOpen, an atomic.Bool, while the option is forceSingleFile. There is no internal forceSerialization name.
|
|
||
| handlesMu sync.Mutex | ||
| handles map[string]struct{} // Handles of open files and directories. | ||
| openMu sync.Mutex |
There was a problem hiding this comment.
If openMu isn’t a second acquired mutex while holding handlesMu, then it should not be in the same paragraph.
I’m wondering if we need a full mutex anyways. An atomic.Bool should probably be sufficient for coördinating single-file-at-a-time exclusion.
There was a problem hiding this comment.
Removed openMu. The single-file reservation now uses CompareAndSwap on atomic.Bool, so no second mutex is needed.
| if c.forceSerialization && err == nil { | ||
| c.removeHandle(handle) | ||
| } |
There was a problem hiding this comment.
I’m not sure we want to only remove the handle if err is nil… in most cases, even if a close returns an error, then the handle is unspecified… at the very least, it’s improper to attempt even the Close again. As well, if the handle was closed on the server side, then it might reissue this handle again, while if it were not closed on the server side, then it will avoid reissuing that handle to us again anyways. So, if the server reissues a handle, we’ve now crashed the client and reported that they need to restart with the single-file-at-a-time mode, which would be a Bad Thing™.
There was a problem hiding this comment.
close(handle) now removes the local handle before sending CLOSE and releases the single-file reservation after every close attempt, including errors. The client will not retry an indeterminate handle.
| c.handlesMu.Lock() | ||
|
|
||
| if _, ok := c.handles[handle]; ok { | ||
| c.handlesMu.Unlock() |
There was a problem hiding this comment.
Why do we need to unlock this mutex now?
Consider that opening multiple files all together could see them stampeding into this section if we unlock before issuing the error. I’m pretty sure we want to continue blocking all opens while we’re issuing this error.
So, we should be able to just defer c.handlesMu.Unlock()
There was a problem hiding this comment.
addHandle now defers handlesMu.Unlock(), keeping the handle lock held while it broadcasts the duplicate-handle failure and closes the connection.
| c.openMu.Lock() | ||
| c.handlesMu.Lock() |
There was a problem hiding this comment.
The order of these locks is a violation of the expected order they are in in the object. Mutexes should be acquired from top-down. By following this convention, we don’t have the chance where we have two threads attempting to lock them in a different order leading to a deadlock.
There was a problem hiding this comment.
Removed openMu, which removes the competing lock order from the single-file path. handlesMu only protects the handle map; the reservation itself is atomic.
| return fmt.Sprintf("sftp: server returned handle %q which is already open; the server may not support multiple open files, use ForceSerialization", e.handle) | ||
| } | ||
|
|
||
| func (c *Client) lockOpenSlot() (func(), error) { |
There was a problem hiding this comment.
This code blocks an open on a second thread while the first file is open. I already explained in the issue, that this is undesired behavior, because code may build a dependency on the second file being opened before handling the first file.
Instead, we should be returning an error of the sort “client is in ForceSerialization mode that allows only one file open at a time” to the caller, and they can handle how they want to proceed from there.
The worst thing we could do is change some code that works fine without file serialization to a deadlock when file serialization is on. Better to announce back that it’s not allowed. (Hilariously, this is a reasonable SSH_FX_OP_UNSUPPORTED situation.)
There was a problem hiding this comment.
A second Open or Opendir now returns a synthetic SSH_FX_FAILURE immediately when the ForceSingleFile reservation is already held. It does not wait for the first file to close.
| if _, ok := err.(*duplicateHandleError); ok { | ||
| return fmt.Errorf("%w: %w", ErrSSHFxConnectionLost, err) | ||
| } |
There was a problem hiding this comment.
Prefer a type switch here:
switch err := err.(type) {
case *duplicateHandleError:
return fmt.Errorf("%w: %w", ErrSSHFxConnectionLost, err)
default:
return ErrSSHFxConnectionLost
}🤔 Actually:
if err == nil {
return ErrSSHFxConnectionLost
}
return fmt.Errorf("%w: %w", ErrSSHFxConnectionLost, err)After all, why throw away any non-nil error for ErrSSHFxConnectionLost? 🤔
There was a problem hiding this comment.
connectionLostError now returns ErrSSHFxConnectionLost for a nil cause and wraps every non-nil cause with it. That preserves the duplicate-handle detail and other connection-loss causes.
|
Applied the review feedback on the one-file-at-a-time mode. The public option is now |
|
The pipeline failed because the new immediate-open regression test calls |
|
The next CI run also exposed failures hidden behind the original compile error. |
| // ForceSerialization restricts the client to one open file or directory at a time. | ||
| // ForceSingleFile restricts the client to one open file or directory at a time. | ||
| // A second open returns an SSH_FX_FAILURE status until the current handle is closed. | ||
| // This can be used with servers that cannot safely keep more than one handle open. |
There was a problem hiding this comment.
Looking at this, I think I would word this differently. The servers certainly could handle more than one open file safely, they just don’t.
We would want to highlight what the behavior of the server is doing. So, at least “…that do not safely keep…”, but probably reword the whole this to something along the lines of: that use one handle for all open files and directories. And then a the next line a comment of something like: so clients cannot safely open two handles at the same time.
There was a problem hiding this comment.
Reworded the option docs to describe the server behavior directly: these servers return the same handle for multiple opens, so a client cannot safely keep two files or directories open at once.
| keepSlot := false | ||
| defer func() { | ||
| if !keepSlot { | ||
| releaseSlot() | ||
| } | ||
| }() |
There was a problem hiding this comment.
I think there’s something we can do different here. Looking at the logical code paths, we can call c.singleFileOpen.Store(false) all we want on a client that is not in force single-file mode.
That removes the need to return an anonymous function that either no-ops or stores the false flag, we can just do it directly here in a defer. And it makes no difference if we leave the c.singleFileOpen set to true when not in force single-file mode as well. So we can just name the return values, and then use if err != nil { c.releaseSlot() }
The lockOpenSlot also now becomes easy: if force single-file mode, return nil; if not cmpxchg false for true, then return error, otherwise return nil.
There was a problem hiding this comment.
Removed the release-function closure. lockOpenSlot now directly reserves the atomic flag, and open/opendir use named errors to release it only when opening fails. On successful opens, close releases the reservation.
| // unspecified after a close error, and the server may already have reused it. | ||
| c.removeHandle(handle) | ||
| if c.forceSingleFile { | ||
| defer c.singleFileOpen.Store(false) |
There was a problem hiding this comment.
This defer can be run unconditionally. If the service isn’t in force single-file mode, then it will never try the cmpxchg that this depends on anyways.
There was a problem hiding this comment.
Made the close defer unconditional: singleFileOpen.Store(false) is harmless when the option is disabled, and this avoids a separate mode check in the close path.
|
Merged the latest |
|
This PR needs to be rebased to remove the commits that are not a part of this PR. |
d27a0a8 to
b4b481f
Compare
|
Rebased onto the current Testing exposed an interaction with preserving connection-loss causes: a disconnect wrapping Validation passed: |
Track open file and directory handles and fail the connection when the server returns a handle that is already in use. Preserve the failure cause for pending and subsequent operations. Add ForceSingleFile to reject a second open immediately without serializing reads or writes. Release the reservation after every close attempt and retain connection-lost errors wrapping EOF during ReadFrom. Cover duplicate handles, single-file reservations, and connection loss during full and short writes with regression tests. Updates pkg#424.
b4b481f to
1e57484
Compare
| if err == nil { | ||
| return ErrSSHFxConnectionLost | ||
| } | ||
| return fmt.Errorf("%w: %w", ErrSSHFxConnectionLost, err) |
There was a problem hiding this comment.
[no change required] 🤔 I would probably prefer we returned a status packet with the code and message set… but, that’s probably better for the v2 implementation… as I think this v1 implementation API wasn’t designed knowing that errors was going to have the Is and As functionality…
There was a problem hiding this comment.
alright, I'll leave this as it is
Updates #424.
Some servers return a handle that is still open, replacing the file behind the existing client handle. The client now detects duplicate handles from
OPENandOPENDIR, shuts down the connection, and reports the cause to pending and subsequent operations, including the existingFile.Wait()returns the cause, and connection errors retainErrSSHFxConnectionLostforerrors.Ischecks.ForceSingleFile()restricts the client to one open file or directory at a time. A second open returnsSSH_FX_FAILUREimmediately without sending a request. Reads and writes can still run concurrently.Handles are forgotten before
CLOSEis sent, and the single-file reservation is released after every close attempt, including errors. Connection-loss errors wrappingio.EOFremain errors when copying into a file withReadFrom.Regression tests cover duplicate handles, immediate rejection of a second open, reuse after close, and connection loss during full and short writes.
Validation:
go test ./...andmake integration integration_w_racepassed, including all server and allocator combinations.