Skip to content

FELIX-6515 Fix race condition when rewriting config files in ConfigInstaller - #233

Merged
paulrutter merged 6 commits into
apache:masterfrom
instana:FELIX-6515
Nov 16, 2026
Merged

paulrutter merged 6 commits into
apache:masterfrom
instana:FELIX-6515

Conversation

@FelixMarxIBM

@FelixMarxIBM FelixMarxIBM commented Aug 30, 2023 •

Copy link
Copy Markdown
Contributor

Summary

This PR fixes a race condition (FELIX-6515) in ConfigInstaller where rewriting a configuration file could expose a truncated (empty) file to the DirectoryWatcher. Previously, the file was opened with FileOutputStream (which truncates it immediately) before the new content was fully written. A DirectoryWatcher holding the read lock could observe this empty file and write it back to ConfigurationAdmin, effectively wiping the configuration.

The fix wraps the entire load-merge-compare-write sequence in a write lock, preventing DirectoryWatcher from observing a partially written file. Additional safeguards handle the case where the current thread already holds the read lock (which cannot be upgraded to a write lock with ReentrantReadWriteLock) and when the lock acquisition is interrupted. As a bonus optimization, the file is no longer written at all if the content has not changed, avoiding unnecessary lastModified timestamp updates.

Files Changed

📄 fileinstall/src/main/java/org/apache/felix/fileinstall/internal/ConfigInstaller.java

Refactored the configuration file write-back logic in doConfigurationEvent to eliminate a race condition. Key changes:

  • Added a guard that skips the save if the current thread already holds the read lock (which cannot be upgraded, and would deadlock).
  • Wrapped the entire load → merge → compare → write sequence inside fileInstall.lock.writeLock().lockInterruptibly(), making it an atomic critical section with respect to the DirectoryWatcher.
  • File content is now first written to a ByteArrayOutputStream and compared against the current file content; the file is only overwritten (and its checksum updated) if the content has actually changed.
  • Added proper handling for InterruptedException, restoring the interrupt flag and logging the error.

📄 fileinstall/src/main/java/org/apache/felix/fileinstall/internal/FileInstall.java

Changed the type of the lock field from the interface ReadWriteLock to the concrete type ReentrantReadWriteLock. This is required so that ConfigInstaller can call ReentrantReadWriteLock-specific methods such as getReadHoldCount() and isWriteLockedByCurrentThread() needed for the deadlock-prevention guard.

📄 fileinstall/src/test/java/org/apache/felix/fileinstall/internal/ConfigInstallerTest.java

Added four new test cases covering the scenarios introduced by the fix:

  • testDoConfigurationEventRewritesFileUnderWriteLock – Verifies that the write-back is performed while holding the write lock and that the file is correctly updated.
  • testDoConfigurationEventDoesNotRewriteUnchangedFile – Verifies that a configuration file whose content would not change is not touched (timestamp and checksum remain unchanged).
  • testDoConfigurationEventSkipsSaveWhenReadLockHeldByCurrentThread – Verifies that when the current thread already holds the read lock, the write-back is skipped gracefully without deadlocking.
  • testDoConfigurationEventRestoresInterruptFlagWhenInterrupted – Verifies that if the thread is interrupted while waiting to acquire the write lock, the interrupt flag is properly restored.

* Writing a file is a 2 step process where the file is created empty and then filled
* There is a race-condition, where the DirectoryWatcher might pick up the creation of the
* empty file. This empty file will be written back to disk on a follow-up CM_UPDATED event.
* Using the global write lock will block the DirectoryWatcher to wait for the write to finish
* and therefore never to read an empty file.
@FelixMarxIBM

Copy link
Copy Markdown
Contributor Author

I'll try to create a test for this race-condition but doing that might be hard to accomplish.

FelixMarxIBM and others added 4 commits November 24, 2025 10:56
…ite lock

ConfigInstaller truncates a .cfg/.config file before filling it when writing a
configuration back to disk. The fix for FELIX-6515 guards that rewrite, and the
following checksum update, with the global FileInstall write lock so that a
DirectoryWatcher, which processes files under the read lock, can never pick up
the empty file and write it back on a follow-up CM_UPDATED event.

Add ConfigInstallerTest.testDoConfigurationEventRewritesFileUnderWriteLock to
cover that. The test is deterministic and does not rely on threads or sleeping:
it runs doConfigurationEvent on the test thread and records whether the current
thread holds the write lock when the encoding is looked up for loading the file
(not held) and for writing it (held), and when the checksum is updated (held).
It also checks the rewritten content and that the lock is released afterwards.
Without the fix it fails with expected:<[false, true]> but was:<[false, false]>.
…te lock

When ConfigInstaller writes a configuration back to its .cfg/.config file
after a CM_UPDATED event, it used to truncate and rewrite the file every time,
even if the content produced from ConfigAdmin was identical to what is already
on disk. Besides needless I/O, this bumps lastModified, which forces a
checksum update and gives the DirectoryWatcher a reason to look at the file
again.

Changes:
- Serialize the properties into a byte array (using the same configured
  encoding() as is used for loading the file) before taking the lock, and
  compare it with the current file content. Only if the bytes differ the file
  is written and the checksum updated. If nothing would change, the file is not
  touched, so lastModified stays the same and no checksum update is needed, as
  the scanner's checksum (name, lastModified, length, writeable flag) remains
  valid.
- Restrict the FileInstall write lock to the part that needs it: comparing,
  writing the file and updating the checksum. Building the byte array does not
  touch the file and is done outside the lock. The lock still guarantees that
  a DirectoryWatcher, which processes files under the read lock, cannot
  observe the truncated, empty file.

Notes:
- The comparison is byte exact. A file that does not round-trip through
  TypedProperties load/save (e.g. CRLF line endings, missing trailing newline)
  is rewritten once and is stable afterwards. Files that cannot be decoded with
  the configured encoding are rewritten as before.
- If the file disappears before it is compared, reading it now fails and is
  logged as "Unable to save configuration" instead of silently recreating it.

Tests:
- Add testDoConfigurationEventDoesNotRewriteUnchangedFile, which verifies that
  lastModified is unchanged and updateChecksum is not called for an unchanged
  file.
- Simplify testDoConfigurationEventRewritesFileUnderWriteLock: the encoding is
  now read outside of the lock, so drop the encoding lookup assertion and keep
  the checks that the checksum update happens under the write lock and that the
  lock is released afterwards.
@FelixMarxIBM FelixMarxIBM changed the title FELIX-6515: Add global write lock to write back cfg files FELIX-6515 Fix race condition when rewriting config files in ConfigInstaller Nov 12, 2026
@paulrutter

Copy link
Copy Markdown
Contributor

Thanks for the fix, the approach (serialize first, compare, write under the write lock) looks right and the two tests cover the new behaviour well. A few findings, roughly by importance:

  1. Read-modify-write is still partly outside the lock. file is read and merged into props (the props.load(r) / "removed properties" logic) before writeLock().lockInterruptibly(). If DirectoryWatcher processes a user edit of the file between that read and the lock acquisition, the content computed from the stale read is compared against and then written over the newer file. Consider taking the write lock before loading the file, so load, merge, compare and write are one critical section (the serialization is cheap).

  2. Possible self-deadlock if the event is delivered on a watcher thread. DirectoryWatcher holds lock.readLock() while it installs/updates configs, and a ReentrantReadWriteLock cannot upgrade read to write. Felix ConfigAdmin delivers ConfigurationEvents asynchronously so this is fine there, but a ConfigAdmin implementation that dispatches synchronously on the calling thread would hang here instead of just logging. Worth a comment, or tryLock with a timeout.

  3. Interrupt is swallowed. lockInterruptibly() throws InterruptedException, which is caught by the generic catch (Exception e) and logged as "Unable to save configuration" without restoring the interrupt flag. Please add Thread.currentThread().interrupt() for that case.

  4. Files.readAllBytes can now fail where the old code did not. If the file is deleted between the file.isFile() check and the read, this throws NoSuchFileException (logged as an error), whereas the old code would have recreated it via FileOutputStream. Treating a missing file as "changed" would keep the old behaviour.

  5. The truncate-then-write window still exists for readers outside fileInstall.lock (other processes, editors, backup tools). Writing to a temp file in the same directory and Files.move(..., ATOMIC_MOVE, REPLACE_EXISTING) would remove the empty-file state entirely, and would make the lock less critical. Not a blocker for this PR.

  6. Nit: the test file adds two trailing blank lines before testSetConfiguration.

@FelixMarxIBM

Copy link
Copy Markdown
Contributor Author

Hello Paul and thank you very much for your feedback. I'll go through all or your findings and will get back to you when a new version is available.
I'll update this comment with the changed details.

- Move load-merge-compare-write entirely under the write lock
  (single Files.readAllBytes under the lock, parsed via ByteArrayInputStream;
  eliminates the read-modify-write window where DirectoryWatcher could
  observe a stale read between the file load and lock acquisition)

- Guard against read-lock upgrade deadlock: when the calling thread already
  holds the read lock (e.g. a synchronous ConfigurationEvent dispatch on a
  DirectoryWatcher thread), log a warning and skip the write-back instead of
  blocking forever (ReentrantReadWriteLock cannot upgrade read to write)

- Restore interrupt flag on InterruptedException from lockInterruptibly()

- Change FileInstall.lock field type from ReadWriteLock to ReentrantReadWriteLock
  to expose getReadHoldCount(); remove unused ReadWriteLock import

- Tests: add read-lock skip test, add interrupt-flag restore test, assert
  that both encoding lookups (load and write) happen under the write lock,
  remove redundant cast of fileInstall.lock, remove two trailing blank lines
  before testSetConfiguration
@FelixMarxIBM

Copy link
Copy Markdown
Contributor Author

Thanks for all your concerns @paulrutter .
I'm not sure we do need the Files.move(..., ATOMIC_MOVE, REPLACE_EXISTING) approach. I would only consider this if there is a known safe way to create such temp files that do not conflict with any actual config file.
If that is not possible, I'd prefer the current approach.

I've worked on the reaming requests and also added a test for the deadlock situation that is only possible in a non-compliant setup.

@paulrutter

Copy link
Copy Markdown
Contributor

Looks good to me as is, i will go ahead and merge it in.

@paulrutter
paulrutter merged commit c9e909e into apache:master Nov 16, 2026
4 checks passed
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.

2 participants