Repository navigation
FELIX-6515 Fix race condition when rewriting config files in ConfigInstaller - #233
Conversation
* 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.
|
I'll try to create a test for this race-condition but doing that might be hard to accomplish. |
…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.
|
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:
|
|
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. |
- 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
|
Thanks for all your concerns @paulrutter . 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. |
|
Looks good to me as is, i will go ahead and merge it in. |
Summary
This PR fixes a race condition (FELIX-6515) in
ConfigInstallerwhere rewriting a configuration file could expose a truncated (empty) file to theDirectoryWatcher. Previously, the file was opened withFileOutputStream(which truncates it immediately) before the new content was fully written. ADirectoryWatcherholding the read lock could observe this empty file and write it back toConfigurationAdmin, effectively wiping the configuration.The fix wraps the entire load-merge-compare-write sequence in a write lock, preventing
DirectoryWatcherfrom 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 withReentrantReadWriteLock) 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 unnecessarylastModifiedtimestamp updates.Files Changed
📄
fileinstall/src/main/java/org/apache/felix/fileinstall/internal/ConfigInstaller.javaRefactored the configuration file write-back logic in
doConfigurationEventto eliminate a race condition. Key changes:fileInstall.lock.writeLock().lockInterruptibly(), making it an atomic critical section with respect to theDirectoryWatcher.ByteArrayOutputStreamand compared against the current file content; the file is only overwritten (and its checksum updated) if the content has actually changed.InterruptedException, restoring the interrupt flag and logging the error.📄
fileinstall/src/main/java/org/apache/felix/fileinstall/internal/FileInstall.javaChanged the type of the
lockfield from the interfaceReadWriteLockto the concrete typeReentrantReadWriteLock. This is required so thatConfigInstallercan callReentrantReadWriteLock-specific methods such asgetReadHoldCount()andisWriteLockedByCurrentThread()needed for the deadlock-prevention guard.📄
fileinstall/src/test/java/org/apache/felix/fileinstall/internal/ConfigInstallerTest.javaAdded 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.