You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Fail instead of appending when the copy destination already exists - #145
Adds an If destination exists setting to the file copier (ifexists, or the node attribute winrm-copy-if-exists) with three values:
overwrite: delete the existing file, then write.
fail: raise RemoteFileExistsError and leave the existing file untouched.
append: add to the end of the existing file.
When it isn't set, nothing changes: "Override?" on overwrites and off appends, as before. In that implicit append case the copier checks whether the file exists and logs a warning pointing at the new setting. If that check itself fails, the copy still goes ahead. An explicit value takes precedence over "Override?", and an unknown value fails before anything is sent to the node.
In fail mode the copier claims the destination before writing, with one PowerShell call that opens the file with FileMode.CreateNew. The existence check and the create are one filesystem operation. If two copies to the same new path overlap, only one creates the file. The other fails before writing anything, so they can't both append to it. A missing folder or any other error raises WinRmError instead of being reported as an existing file.
Why
Chunks are written with add-content, so uploading over an existing file appended to it. Copying the same file twice gave a doubled or corrupted file, and the step still reported success.
Behaviour change
None unless the new setting is used. Jobs that rely on appending keep working, and they now log a warning when they append to an existing file. There is one extra WinRM PowerShell call per copy in implicit append and fail modes.
Verification
tests/test_winrm_filecopier.py loads only the exception classes and CopyFiles from the script via ast, because the script parses argv and connects at import time. It runs them against a fake session. The tests cover the default with and without "Override?", each explicit value, precedence over "Override?", an invalid value, and failed checks. For fail mode they also cover another writer creating the file just before the claim, and a second copy starting while the first is writing. Both of those fail against a check-then-write version.
I ran the claim's PowerShell through pwsh on macOS: a new file is created, an existing file is reported as existing, a missing folder errors, and a path with a ' works. With 12 copies racing for the same path, exactly one created the file in each of three runs.
python3 -m unittest discover -s tests: all copier tests pass. The 2 test_kerberosauth tests error without pexpect, the same as on main.
Not verified on a live Windows node. An earlier end-to-end run on a local Rundeck server, against a stub WinRM endpoint, covered the first version of this change (fail whenever "Override?" was off), not the current setting.
winrm_upload() writes the file in base64 chunks with add-content, and
only removed an existing destination when the "Override?" option was
enabled. With override off (the default), copying to a path that
already held a file appended every chunk to it, so running the same
Copy File step twice left a file with doubled or corrupted contents
while the step still reported success.
With override off, the copier now checks whether the destination
exists as a file (checking the command's exit code and output) and
fails with a message telling the user to enable "Override?", leaving
the existing file untouched. With override on, the existing
delete-then-write behaviour is unchanged.
Script dispatch is not affected: Rundeck copies scripts to unique
temporary file names, so the destination does not already exist.
Adds unit tests for CopyFiles.winrm_upload() using a fake session.
Thanks for this. The fix is correct, and the append bug is real. Before we merge, we'd like to reduce the risk of breaking existing jobs.
The append behaviour has shipped since "Override?" was added in 2021 (82a3897). The option has no default and can only be set at project or framework level, so most installs run with it off. With this change:
Jobs that copy to a fixed path more than once with "Override?" off go from green to failing on every run after the first.
Anyone using the copier on purpose to add to a file (a log or CSV, for example) breaks without warning.
Copying an empty file to an existing path used to do no harm. Now it fails.
Could you look at some ways to soften this and tell us which you'd recommend? For example:
Make the behaviour explicit. Replace or extend "Override?" with a setting like "If destination exists: overwrite / fail / append". Keeping append as a choice gives anyone who relies on it a one-setting way back.
Warn first, fail later. In this release, log a clear warning when the destination exists and override is off, then switch to failing in a later release.
Keep the fail, but document it. Add a note to the README and the option description explaining the new behaviour and how to get the old one back.
We're open to other ideas too. Whichever way you go, a short note in the README would help users who hit it after upgrading.
The previous commit made the copier fail whenever the destination file
already existed and "Override?" was off. Appending has been the
shipped behaviour since "Override?" was added, and most installs run
with it off, so that would turn repeated copies to a fixed path, and
deliberate appends, into failures after upgrading.
Add an explicit "If destination exists" setting (ifexists, node
attribute winrm-copy-if-exists) with the values overwrite, fail and
append. When it is not set, "Override?" decides as before: on
overwrites, off appends. In that implicit append case the copier now
checks whether the file exists and prints a warning pointing at the
new setting; a failed check never fails the copy. fail is opt-in and
leaves the existing file untouched. An explicit value takes precedence
over "Override?", and an unknown value fails before anything is sent
to the node.
Document the setting in the README and cover the default, override,
and each explicit value in the copier tests.
Thanks for the careful review, that's a fair concern. We went with option 1: there's a new "If destination exists" setting (ifexists, or the node attribute winrm-copy-if-exists) with overwrite, fail and append.
When it isn't set, nothing changes: "Override?" off still appends and on still overwrites. The copier now also logs a warning when it appends to an existing file, so people can find the setting. fail is opt-in through the new setting, and an explicit value takes precedence over "Override?".
The README has a short section on the setting, the default, and how to switch to fail, and the tests cover each case.
Thanks for the explicit "If destination exists" setting, this resolves the backward-compatibility concern well.
Before merging, could you address Copilot's finding on the new fail mode? The existence check (Test-Path) and the chunk-write loop are two separate remote calls, so two overlapping copies targeting the same not-yet-existing destination can both see "doesn't exist" and then both append their chunks into it, corrupting the file despite fail being selected. That's the same class of bug this PR fixes, just triggered by concurrent runs instead of a stale pre-existing file.
Copilot's suggested direction looks right: claim the destination atomically in fail mode (e.g. opening the file with a create-if-not-exists-else-fail disposition in PowerShell) instead of check-then-write, so the OS itself closes the race rather than two separate round-trips. A regression test simulating "another writer created it between the check and the write" would help confirm the fix.
fail mode checked for the file with Test-Path and then wrote the chunks
in separate WinRM calls. Two overlapping copies to the same new path
could both see no file and both append, corrupting it while reporting
success.
Create the destination with FileMode.CreateNew before writing instead.
The check and the create are one filesystem operation, so only one copy
can create the file; the other gets RemoteFileExistsError before it
writes anything. A missing folder or any other failure still raises
WinRmError rather than being reported as an existing file. The path is
passed as a quoted PowerShell string so quotes in it are handled.
Tests cover a writer that creates the file just before the claim and a
second copy that starts while the first is writing; both fail against
the previous check-then-write code. The README notes the overlap
behaviour and that a partial file left by a failed copy blocks later
fail-mode copies until it is removed.
fail mode no longer checks first and then writes. It now claims the destination with one PowerShell call that opens the file with FileMode.CreateNew. Windows creates the file only if it isn't already there, and does both in one step. If two copies to the same new path overlap, only one creates the file. The other gets RemoteFileExistsError before it writes anything. If the claim fails for any other reason (for example a missing folder), it raises WinRmError rather than being reported as an existing file.
I added two regression tests. In one, another writer creates the file just before the claim. In the other, a second copy starts while the first is writing its chunks. Both fail against the old check-then-write code. I also ran the claim through pwsh with 12 copies racing for one path, and exactly one created the file each time.
Two notes:
The README now says that if a copy fails partway through, the partial file stays, and later fail-mode copies fail until it is removed.
overwrite has a similar window: it removes the file and then appends, so two overlapping overwrites can still double the content. That behaviour predates this PR, so I've left it alone here. I'm happy to follow up separately if you'd like.
I also updated the PR description to match the current design.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Wildcard expansion in chunk writes can modify the wrong file while reporting success, and uncaught existence-probe exceptions can abort best-effort copies.
Catch probe exceptions to preserve best-effort implicit appends
contents/winrm-filecopier.py:290
The warning-only existence probe can raise a session/transport exception rather than WinRmError: winrm_session.run_cmd() raises a plain Exception when opening the shell fails, and other WinRM calls can also raise directly. These escape this handler and abort legacy implicit-append copies before any chunks are written, contrary to the best-effort behavior. Treat exceptions from this probe as a failed check too; keep upload errors outside this handler.
Chunks were written with Add-Content -Path, which expands wildcards. With
C:\tmp\file1.txt present and a new destination C:\tmp\file[1].txt, fail
mode claimed the bracketed file but then appended the data to file1.txt,
leaving the claimed file empty and reporting success. The overwrite step
had the same problem with Test-Path/rm and could delete file1.txt, and
the implicit-append probe could warn about the wrong file.
Pass the destination as a quoted PowerShell string to -LiteralPath in
the chunk writes, the overwrite step and the existence probe, sharing
the quoting the fail-mode claim already used, so every command acts on
the same file.
The implicit-append existence probe only caught WinRmError, but opening
the shell can raise a plain Exception, which aborted copies that the
probe is meant never to fail. Treat any exception from the probe as an
unknown result; errors from the upload itself still fail the copy.
Tests add a fake session with several files and -Path wildcard
expansion, covering a bracketed name in fail, overwrite and unset modes
and a quote in the name, plus a probe that raises a plain Exception and
an upload error that must still raise. The new cases fail against the
previous code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Change
Adds an If destination exists setting to the file copier (
ifexists, or the node attributewinrm-copy-if-exists) with three values:overwrite: delete the existing file, then write.fail: raiseRemoteFileExistsErrorand leave the existing file untouched.append: add to the end of the existing file.When it isn't set, nothing changes: "Override?" on overwrites and off appends, as before. In that implicit append case the copier checks whether the file exists and logs a warning pointing at the new setting. If that check itself fails, the copy still goes ahead. An explicit value takes precedence over "Override?", and an unknown value fails before anything is sent to the node.
In
failmode the copier claims the destination before writing, with one PowerShell call that opens the file withFileMode.CreateNew. The existence check and the create are one filesystem operation. If two copies to the same new path overlap, only one creates the file. The other fails before writing anything, so they can't both append to it. A missing folder or any other error raisesWinRmErrorinstead of being reported as an existing file.Why
Chunks are written with
add-content, so uploading over an existing file appended to it. Copying the same file twice gave a doubled or corrupted file, and the step still reported success.Behaviour change
None unless the new setting is used. Jobs that rely on appending keep working, and they now log a warning when they append to an existing file. There is one extra WinRM PowerShell call per copy in implicit append and
failmodes.Verification
tests/test_winrm_filecopier.pyloads only the exception classes andCopyFilesfrom the script viaast, because the script parses argv and connects at import time. It runs them against a fake session. The tests cover the default with and without "Override?", each explicit value, precedence over "Override?", an invalid value, and failed checks. Forfailmode they also cover another writer creating the file just before the claim, and a second copy starting while the first is writing. Both of those fail against a check-then-write version.pwshon macOS: a new file is created, an existing file is reported as existing, a missing folder errors, and a path with a'works. With 12 copies racing for the same path, exactly one created the file in each of three runs.python3 -m unittest discover -s tests: all copier tests pass. The 2test_kerberosauthtests error withoutpexpect, the same as onmain.Fixes #144