You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by ag...@apache.org on 2018/12/24 10:14:15 UTC

ignite git commit: IGNITE-10671 Fixed double initialization of FileArchiver leading to broken WAL file compression - Fixes #5665.

Repository: ignite
Updated Branches:
  refs/heads/master 7d933e8e1 -> e87aa510a


IGNITE-10671 Fixed double initialization of FileArchiver leading to broken WAL file compression - Fixes #5665.

Signed-off-by: Alexey Goncharuk <al...@gmail.com>


Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/e87aa510
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/e87aa510
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/e87aa510

Branch: refs/heads/master
Commit: e87aa510a74e4a6efb4dd72544a6419799307f9a
Parents: 7d933e8
Author: Pavel Voronkin <pv...@gridgain.com>
Authored: Mon Dec 24 12:49:58 2018 +0300
Committer: Alexey Goncharuk <al...@gmail.com>
Committed: Mon Dec 24 13:07:23 2018 +0300

----------------------------------------------------------------------
 .../wal/FileWriteAheadLogManager.java           | 203 ++++++++++---------
 .../wal/aware/SegmentArchivedStorage.java       |   7 +
 .../persistence/wal/aware/SegmentAware.java     |  11 +
 .../wal/aware/SegmentCompressStorage.java       |   7 +
 .../wal/aware/SegmentCurrentStateStorage.java   |   9 +
 .../wal/filehandle/FileHandleManager.java       |  10 -
 .../wal/filehandle/FileHandleManagerImpl.java   |  95 +++++----
 .../filehandle/FsyncFileHandleManagerImpl.java  |  10 -
 .../db/wal/WalCompactionSwitchOnTest.java       | 142 +++++++++++++
 .../testsuites/IgnitePdsMvccTestSuite2.java     |   2 +
 .../ignite/testsuites/IgnitePdsTestSuite2.java  |   2 +
 11 files changed, 352 insertions(+), 146 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/e87aa510/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/FileWriteAheadLogManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/FileWriteAheadLogManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/FileWriteAheadLogManager.java
index 70abed8..dbd2f14 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/FileWriteAheadLogManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/FileWriteAheadLogManager.java
@@ -233,7 +233,7 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
      * Maximum number of allowed segments without checkpoint. If we have their more checkpoint should be triggered.
      * It is simple way to calculate WAL size without checkpoint instead fair WAL size calculating.
      */
-    private long maxSegCountWithoutCheckpoint;
+    private final long maxSegCountWithoutCheckpoint;
 
     /** Size of wal archive since which removing of old archive should be started */
     private final long allowedThresholdWalArchiveSize;
@@ -304,7 +304,7 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
     private volatile FileWriteHandle currHnd;
 
     /** File handle manager. */
-    private FileHandleManager fileHandleManager;
+    private volatile FileHandleManager fileHandleManager;
 
     /** */
     private volatile WALDisableContext walDisableContext;
@@ -320,7 +320,7 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
      * segment, skip possible archiving for this case<br> Value is filled only for case {@link
      * #walAutoArchiveAfterInactivity} > 0<br>
      */
-    private AtomicLong lastRecordLoggedMs = new AtomicLong();
+    private final AtomicLong lastRecordLoggedMs = new AtomicLong();
 
     /**
      * Cancellable task for {@link WALMode#BACKGROUND}, should be cancelled at shutdown.
@@ -345,9 +345,10 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
     private SegmentRouter segmentRouter;
 
     /** Segment factory with ability locked segment during reading. */
-    private SegmentFileInputFactory lockedSegmentFileInputFactory;
+    private volatile SegmentFileInputFactory lockedSegmentFileInputFactory;
 
-    private FileHandleManagerFactory fileHandleManagerFactory;
+    /** FileHandleManagerFactory. */
+    private final FileHandleManagerFactory fileHandleManagerFactory;
 
     /**
      * @param ctx Kernal context.
@@ -375,6 +376,10 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
         failureProcessor = ctx.failure();
 
         fileHandleManagerFactory = new FileHandleManagerFactory(dsCfg);
+
+        maxSegCountWithoutCheckpoint =
+                (long)((U.adjustedWalHistorySize(dsCfg, log) * CHECKPOINT_TRIGGER_ARCHIVE_SIZE_PERCENTAGE)
+                        / dsCfg.getWalSegmentSize());
     }
 
     /**
@@ -388,111 +393,106 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
 
     /** {@inheritDoc} */
     @Override public void start0() throws IgniteCheckedException {
-        if (!cctx.kernalContext().clientNode()) {
-            maxSegCountWithoutCheckpoint =
-                (long)((U.adjustedWalHistorySize(dsCfg, log) * CHECKPOINT_TRIGGER_ARCHIVE_SIZE_PERCENTAGE)
-                    / dsCfg.getWalSegmentSize());
+        if(cctx.kernalContext().clientNode())
+            return;
 
-            final PdsFolderSettings resolveFolders = cctx.kernalContext().pdsFolderResolver().resolveFolders();
+        final PdsFolderSettings resolveFolders = cctx.kernalContext().pdsFolderResolver().resolveFolders();
 
-            checkWalConfiguration();
+        checkWalConfiguration();
 
-            final File walWorkDir0 = walWorkDir = initDirectory(
+        final File walWorkDir0 = walWorkDir = initDirectory(
                 dsCfg.getWalPath(),
                 DataStorageConfiguration.DFLT_WAL_PATH,
                 resolveFolders.folderName(),
                 "write ahead log work directory"
-            );
+        );
 
-            final File walArchiveDir0 = walArchiveDir = initDirectory(
+        final File walArchiveDir0 = walArchiveDir = initDirectory(
                 dsCfg.getWalArchivePath(),
                 DataStorageConfiguration.DFLT_WAL_ARCHIVE_PATH,
                 resolveFolders.folderName(),
                 "write ahead log archive directory"
-            );
+        );
 
-            serializer = new RecordSerializerFactoryImpl(cctx).createSerializer(serializerVer);
+        serializer = new RecordSerializerFactoryImpl(cctx).createSerializer(serializerVer);
 
-            GridCacheDatabaseSharedManager dbMgr = (GridCacheDatabaseSharedManager)cctx.database();
+        GridCacheDatabaseSharedManager dbMgr = (GridCacheDatabaseSharedManager)cctx.database();
 
-            metrics = dbMgr.persistentStoreMetricsImpl();
+        metrics = dbMgr.persistentStoreMetricsImpl();
 
-            checkOrPrepareFiles();
+        checkOrPrepareFiles();
 
-            if (metrics != null)
-                metrics.setWalSizeProvider(new CO<Long>() {
-                    @Override public Long apply() {
-                        long size = 0;
+        if (metrics != null)
+            metrics.setWalSizeProvider(new CO<Long>() {
+                @Override public Long apply() {
+                    long size = 0;
 
-                        for (File f : walWorkDir0.listFiles())
-                            size += f.length();
+                    for (File f : walWorkDir0.listFiles())
+                        size += f.length();
 
-                        for (File f : walArchiveDir0.listFiles())
-                            size += f.length();
-
-                        return size;
-                    }
-                });
+                    for (File f : walArchiveDir0.listFiles())
+                        size += f.length();
 
-            IgniteBiTuple<Long, Long> tup = scanMinMaxArchiveIndices();
+                    return size;
+                }
+            });
 
-            segmentAware = new SegmentAware(dsCfg.getWalSegments(), dsCfg.isWalCompactionEnabled());
+        IgniteBiTuple<Long, Long> tup = scanMinMaxArchiveIndices();
 
-            segmentAware.lastTruncatedArchiveIdx(tup == null ? -1 : tup.get1() - 1);
+        segmentAware = new SegmentAware(dsCfg.getWalSegments(), dsCfg.isWalCompactionEnabled());
 
-            long lastAbsArchivedIdx = tup == null ? -1 : tup.get2();
+        segmentAware.lastTruncatedArchiveIdx(tup == null ? -1 : tup.get1() - 1);
 
-            if (isArchiverEnabled())
-                archiver = new FileArchiver(lastAbsArchivedIdx, log);
-            else
-                archiver = null;
+        long lastAbsArchivedIdx = tup == null ? -1 : tup.get2();
 
-            if (lastAbsArchivedIdx > 0)
-                segmentAware.setLastArchivedAbsoluteIndex(lastAbsArchivedIdx);
+        if (isArchiverEnabled())
+            archiver = new FileArchiver(lastAbsArchivedIdx, log);
+        else
+            archiver = null;
 
-            if (dsCfg.isWalCompactionEnabled()) {
-                if (compressor == null)
-                    compressor = new FileCompressor(log);
+        if (lastAbsArchivedIdx > 0)
+            segmentAware.setLastArchivedAbsoluteIndex(lastAbsArchivedIdx);
 
-                if (decompressor == null) {  // Preventing of two file-decompressor thread instantiations.
-                    decompressor = new FileDecompressor(log);
+        if (dsCfg.isWalCompactionEnabled()) {
+            compressor = new FileCompressor(log);
 
-                    new IgniteThread(decompressor).start();
-                }
-            }
-
-            segmentRouter = new SegmentRouter(walWorkDir, walArchiveDir, segmentAware, dsCfg);
+            decompressor = new FileDecompressor(log);
+        }
 
-            walDisableContext = cctx.walState().walDisableContext();
+        segmentRouter = new SegmentRouter(walWorkDir, walArchiveDir, segmentAware, dsCfg);
 
-            fileHandleManager = fileHandleManagerFactory.build(
+        fileHandleManager = fileHandleManagerFactory.build(
                 cctx, metrics, mmap, lastWALPtr::get, serializer, this::currentHandle
-            );
-
-            fileHandleManager.start();
+        );
 
-            lockedSegmentFileInputFactory = new LockedSegmentFileInputFactory(
+        lockedSegmentFileInputFactory = new LockedSegmentFileInputFactory(
                 segmentAware,
                 segmentRouter,
                 ioFactory
-            );
-        }
+        );
     }
 
     /**
      *
      */
     private void startArchiverAndCompressor() {
+        segmentAware.reset();
+
         if (isArchiverEnabled()) {
-            assert archiver != null;
+            assert archiver != null : "FileArchiver should be initialized.";
 
-            new IgniteThread(archiver).start();
+            archiver.restart();
         }
 
-        fileHandleManager.onActivate();
+        if (dsCfg.isWalCompactionEnabled()) {
+            assert compressor != null : "Compressor should be initialized.";
 
-        if (compressor != null)
-            compressor.start();
+            compressor.restart();
+
+            assert decompressor != null : "Compressor should be initialized.";
+
+            decompressor.restart();
+        }
     }
 
     /**
@@ -560,7 +560,10 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
         }
     }
 
-    /** {@inheritDoc} */
+    /**
+     * Method is called twice on deactivate and stop.
+     * It shutdown workers but do not deallocate them to avoid duplication.
+     * */
     @Override protected void stop0(boolean cancel) {
         final GridTimeoutProcessor.CancelableTask schedule = backgroundFlushSchedule;
 
@@ -580,17 +583,11 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
             if (archiver != null)
                 archiver.shutdown();
 
-            if (compressor != null) {
+            if (compressor != null)
                 compressor.shutdown();
 
-                compressor = null;
-            }
-
-            if (decompressor != null) {
+            if (decompressor != null)
                 decompressor.shutdown();
-
-                decompressor = null;
-            }
         }
         catch (Exception e) {
             U.error(log, "Failed to gracefully close WAL segment: " + this.currHnd, e);
@@ -602,8 +599,7 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
         if (log.isDebugEnabled())
             log.debug("Activated file write ahead log manager [nodeId=" + cctx.localNodeId() +
                 " topVer=" + cctx.discovery().topologyVersionEx() + " ]");
-
-        start0();
+        //NOOP implementation, we need to override it.
     }
 
     /** {@inheritDoc} */
@@ -629,6 +625,15 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
 
     /** {@inheritDoc} */
     @Override public void resumeLogging(WALPointer lastPtr) throws IgniteCheckedException {
+        if (log.isDebugEnabled())
+            log.debug("File write ahead log manager resuming logging [nodeId=" + cctx.localNodeId() +
+                " topVer=" + cctx.discovery().topologyVersionEx() + " ]");
+
+        /*
+            walDisableContext is started after FileWriteAheadLogManager, so we obtain actual walDisableContext ref here.
+         */
+        walDisableContext = cctx.walState().walDisableContext();
+
         assert currHnd == null;
         assert lastPtr == null || lastPtr instanceof FileWALPointer;
 
@@ -658,13 +663,8 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
 
         currHnd.finishResumeLogging();
 
-        if (mode == WALMode.BACKGROUND) {
-            backgroundFlushSchedule = cctx.time().schedule(new Runnable() {
-                @Override public void run() {
-                    doFlush();
-                }
-            }, flushFreq, flushFreq);
-        }
+        if (mode == WALMode.BACKGROUND)
+            backgroundFlushSchedule = cctx.time().schedule(this::doFlush, flushFreq, flushFreq);
 
         if (walAutoArchiveAfterInactivity > 0)
             scheduleNextInactivityPeriodElapsedCheck();
@@ -1842,6 +1842,17 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
                 }
             );
         }
+
+        /**
+         * Restart worker in IgniteThread.
+         */
+        public void restart() {
+            assert runner() == null : "FileArchiver is still running";
+
+            isCancelled = false;
+
+            new IgniteThread(archiver).start();
+        }
     }
 
     /**
@@ -1850,7 +1861,7 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
      */
     private class FileCompressor extends FileCompressorWorker {
         /** Workers queue. */
-        List<FileCompressorWorker> workers = new ArrayList<>();
+        private final List<FileCompressorWorker> workers = new ArrayList<>();
 
         /** */
         FileCompressor(IgniteLogger log) {
@@ -1876,9 +1887,11 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
             for (int i = 1; i < calculateThreadCount(); i++) {
                 FileCompressorWorker worker = new FileCompressorWorker(i, log);
 
-                worker.start();
+                worker.restart();
 
-                workers.add(worker);
+                synchronized (this) {
+                    workers.add(worker);
+                }
             }
         }
 
@@ -1930,18 +1943,17 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
     /** */
     private class FileCompressorWorker extends GridWorker {
         /** */
-        private Thread thread;
-
-        /** */
         FileCompressorWorker(int idx,  IgniteLogger log) {
             super(cctx.igniteInstanceName(), "wal-file-compressor-%" + cctx.igniteInstanceName() + "%-" + idx, log);
         }
 
         /** */
-        void start() {
-            thread = new IgniteThread(this);
+        void restart() {
+            assert runner() == null : "FileCompressorWorker is still running.";
 
-            thread.start();
+            isCancelled = false;
+
+            new IgniteThread(this).start();
         }
 
         /**
@@ -2261,6 +2273,15 @@ public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter impl
 
             U.join(this, log);
         }
+
+        /** Restart worker. */
+        void restart() {
+            assert runner() == null : "FileDecompressor is still running.";
+
+            isCancelled = false;
+
+            new IgniteThread(this).start();
+        }
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/e87aa510/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentArchivedStorage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentArchivedStorage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentArchivedStorage.java
index e31628f..57ac848 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentArchivedStorage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentArchivedStorage.java
@@ -125,6 +125,13 @@ class SegmentArchivedStorage extends SegmentObservable {
     }
 
     /**
+     * Resets interrupted flag.
+     */
+    void reset() {
+        interrupted = false;
+    }
+
+    /**
      * Check for interrupt flag was set.
      */
     private void checkInterrupted() throws IgniteInterruptedCheckedException {

http://git-wip-us.apache.org/repos/asf/ignite/blob/e87aa510/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentAware.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentAware.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentAware.java
index a14f0ca..b564aec 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentAware.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentAware.java
@@ -239,6 +239,17 @@ public class SegmentAware {
     }
 
     /**
+     * Reset interrupted flag.
+     */
+    public void reset() {
+        segmentArchivedStorage.reset();
+
+        segmentCompressStorage.reset();
+
+        segmentCurrStateStorage.reset();
+    }
+
+    /**
      * Interrupt waiting on related objects.
      */
     public void interrupt() {

http://git-wip-us.apache.org/repos/asf/ignite/blob/e87aa510/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentCompressStorage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentCompressStorage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentCompressStorage.java
index 95d4f4a..d93bb84 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentCompressStorage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentCompressStorage.java
@@ -170,4 +170,11 @@ public class SegmentCompressStorage {
     long keepUncompressedIdxFrom() {
         return minUncompressedIdxToKeep;
     }
+
+    /**
+     * Reset interrupted flag.
+     */
+    public void reset() {
+        interrupted = false;
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e87aa510/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentCurrentStateStorage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentCurrentStateStorage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentCurrentStateStorage.java
index 5761ef9..d08a9b8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentCurrentStateStorage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/aware/SegmentCurrentStateStorage.java
@@ -168,4 +168,13 @@ class SegmentCurrentStateStorage {
         if (interrupted)
             throw new IgniteInterruptedCheckedException("Interrupt waiting of change current idx");
     }
+
+    /**
+     * Reset interrupted flag.
+     */
+    public void reset() {
+        interrupted = false;
+
+        forceInterrupted = false;
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e87aa510/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FileHandleManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FileHandleManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FileHandleManager.java
index 6597e46..72e53ad 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FileHandleManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FileHandleManager.java
@@ -50,16 +50,6 @@ public interface FileHandleManager {
     FileWriteHandle nextHandle(SegmentIO fileIO, RecordSerializer serializer) throws IOException;
 
     /**
-     * Start manager.
-     */
-    void start();
-
-    /**
-     * On activate.
-     */
-    void onActivate();
-
-    /**
      * On deactivate.
      *
      * @throws IgniteCheckedException if fail.

http://git-wip-us.apache.org/repos/asf/ignite/blob/e87aa510/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FileHandleManagerImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FileHandleManagerImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FileHandleManagerImpl.java
index 1daac31..66e8425 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FileHandleManagerImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FileHandleManagerImpl.java
@@ -59,9 +59,9 @@ public class FileHandleManagerImpl implements FileHandleManager {
     private static final long DFLT_WAL_SEGMENT_SYNC_TIMEOUT = 500L;
 
     /** WAL writer worker. */
-    private WALWriter walWriter;
+    private final WALWriter walWriter;
     /** Wal segment sync worker. */
-    private WalSegmentSyncer walSegmentSyncWorker;
+    private final WalSegmentSyncer walSegmentSyncWorker;
     /** Context. */
     protected final GridCacheSharedContext cctx;
     /** Logger. */
@@ -109,7 +109,7 @@ public class FileHandleManagerImpl implements FileHandleManager {
         long maxWalSegmentSize,
         long fsyncDelay) {
         this.cctx = cctx;
-        this.log = cctx.logger(FileHandleManagerImpl.class);
+        log = cctx.logger(FileHandleManagerImpl.class);
         this.mode = mode;
         this.metrics = metrics;
         this.mmap = mmap;
@@ -119,6 +119,23 @@ public class FileHandleManagerImpl implements FileHandleManager {
         this.walBufferSize = walBufferSize;
         this.maxWalSegmentSize = maxWalSegmentSize;
         this.fsyncDelay = fsyncDelay;
+        walWriter = new WALWriter(log);
+
+        if (mode != WALMode.NONE && mode != WALMode.FSYNC) {
+            walSegmentSyncWorker = new WalSegmentSyncer(
+                cctx.igniteInstanceName(),
+                cctx.kernalContext().log(WalSegmentSyncer.class)
+            );
+
+            if (log.isInfoEnabled())
+                log.info("Initialized write-ahead log manager [mode=" + mode + ']');
+        }
+        else {
+            U.quietAndWarn(log, "Initialized write-ahead log manager in NONE mode, persisted data may be lost in " +
+                "a case of unexpected node failure. Make sure to deactivate the cluster before shutdown.");
+
+            walSegmentSyncWorker = null;
+        }
     }
 
     /** {@inheritDoc} */
@@ -179,29 +196,6 @@ public class FileHandleManagerImpl implements FileHandleManager {
     }
 
     /** {@inheritDoc} */
-    @Override public void start() {
-        if (mode != WALMode.NONE && mode != WALMode.FSYNC) {
-            walSegmentSyncWorker = new WalSegmentSyncer(cctx.igniteInstanceName(),
-                cctx.kernalContext().log(WalSegmentSyncer.class));
-
-            if (log.isInfoEnabled())
-                log.info("Started write-ahead log manager [mode=" + mode + ']');
-        }
-        else
-            U.quietAndWarn(log, "Started write-ahead log manager in NONE mode, persisted data may be lost in " +
-                "a case of unexpected node failure. Make sure to deactivate the cluster before shutdown.");
-
-    }
-
-    /** {@inheritDoc} */
-    @Override public void onActivate() {
-        if (!cctx.kernalContext().clientNode()) {
-            if (walSegmentSyncWorker != null)
-                new IgniteThread(walSegmentSyncWorker).start();
-        }
-    }
-
-    /** {@inheritDoc} */
     @Override public void onDeactivate() throws IgniteCheckedException {
         FileWriteHandleImpl currHnd = currentHandle();
 
@@ -216,16 +210,19 @@ public class FileHandleManagerImpl implements FileHandleManager {
         if (walSegmentSyncWorker != null)
             walSegmentSyncWorker.shutdown();
 
-        if (walWriter != null)
-            walWriter.shutdown();
+        walWriter.shutdown();
     }
 
     /** {@inheritDoc} */
     @Override public void resumeLogging() {
-        walWriter = new WALWriter(log);
-
         if (!mmap)
-            new IgniteThread(walWriter).start();
+            walWriter.restart();
+
+        if (cctx.kernalContext().clientNode())
+            return;
+
+        if (walSegmentSyncWorker != null)
+            walSegmentSyncWorker.restart();
     }
 
     /** {@inheritDoc} */
@@ -407,9 +404,15 @@ public class FileHandleManagerImpl implements FileHandleManager {
         private void shutdown() throws IgniteInterruptedCheckedException {
             U.cancel(this);
 
-            LockSupport.unpark(runner());
+            Thread runner = runner();
+
+            if (runner != null) {
+                LockSupport.unpark(runner);
 
-            U.join(runner());
+                U.join(runner);
+            }
+
+            assert walWriter.runner() == null : "WALWriter should be stopped.";
         }
 
         /**
@@ -556,14 +559,25 @@ public class FileHandleManagerImpl implements FileHandleManager {
                 throw se;
             }
         }
+
+        /**
+         * Restart worker in IgniteThread.
+         */
+        public void restart() {
+            assert runner() == null : "WALWriter is still running.";
+
+            isCancelled = false;
+
+            new IgniteThread(this).start();
+        }
     }
 
     /**
      * Syncs WAL segment file.
      */
-    public class WalSegmentSyncer extends GridWorker {
+    private class WalSegmentSyncer extends GridWorker {
         /** Sync timeout. */
-        long syncTimeout;
+        private final long syncTimeout;
 
         /**
          * @param igniteInstanceName Ignite instance name.
@@ -598,6 +612,17 @@ public class FileHandleManagerImpl implements FileHandleManager {
 
             U.join(this, log);
         }
+
+        /**
+         * Restart worker in IgniteThread.
+         */
+        public void restart() {
+            assert runner() == null : "WalSegmentSyncer is running.";
+
+            isCancelled = false;
+
+            new IgniteThread(walSegmentSyncWorker).start();
+        }
     }
 
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e87aa510/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FsyncFileHandleManagerImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FsyncFileHandleManagerImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FsyncFileHandleManagerImpl.java
index e456f04..9b219b7e 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FsyncFileHandleManagerImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/filehandle/FsyncFileHandleManagerImpl.java
@@ -108,16 +108,6 @@ public class FsyncFileHandleManagerImpl implements FileHandleManager {
     }
 
     /** {@inheritDoc} */
-    @Override public void start() {
-        //NOOP.
-    }
-
-    /** {@inheritDoc} */
-    @Override public void onActivate() {
-        //NOOP.
-    }
-
-    /** {@inheritDoc} */
     @Override public void onDeactivate() throws IgniteCheckedException {
         FsyncFileWriteHandle currHnd = currentHandle();
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e87aa510/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/db/wal/WalCompactionSwitchOnTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/db/wal/WalCompactionSwitchOnTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/db/wal/WalCompactionSwitchOnTest.java
new file mode 100644
index 0000000..64a937c
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/persistence/db/wal/WalCompactionSwitchOnTest.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ignite.internal.processors.cache.persistence.db.wal;
+
+import java.io.File;
+import java.io.FileFilter;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.cache.CacheMode;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.DataRegionConfiguration;
+import org.apache.ignite.configuration.DataStorageConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager;
+import org.apache.ignite.internal.util.lang.GridAbsPredicate;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+/**
+ * Load without compaction -> Stop -> Enable WAL Compaction -> Start.
+ */
+public class WalCompactionSwitchOnTest extends GridCommonAbstractTest {
+    /** Compaction enabled. */
+    private boolean compactionEnabled;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
+
+        cfg.setDataStorageConfiguration(new DataStorageConfiguration()
+                .setDefaultDataRegionConfiguration(
+                        new DataRegionConfiguration()
+                            .setPersistenceEnabled(true)
+                            .setMaxSize(256 * 1024 * 1024))
+                .setWalSegmentSize(512 * 1024)
+                .setWalSegments(100)
+                .setWalCompactionEnabled(compactionEnabled));
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTest() throws Exception {
+        cleanPersistenceDir();
+    }
+
+    /**
+     * Load without compaction -> Stop -> Enable WAL Compaction -> Start.
+     *
+     * @throws Exception On exception.
+     */
+    public void testWalCompactionSwitch() throws Exception {
+        IgniteEx ex = startGrid(0);
+
+        ex.cluster().active(true);
+
+        IgniteCache<Integer, Integer> cache = ex.getOrCreateCache(
+            new CacheConfiguration<Integer, Integer>()
+                    .setName("c1")
+                    .setGroupName("g1")
+                    .setCacheMode(CacheMode.PARTITIONED)
+        );
+
+        for (int i = 0; i < 500; i++)
+            cache.put(i, i);
+
+        File walDir = U.resolveWorkDirectory(
+                ex.configuration().getWorkDirectory(),
+                "db/wal/node00-" + ex.localNode().consistentId(),
+                false
+        );
+
+        forceCheckpoint();
+
+        GridTestUtils.waitForCondition(new GridAbsPredicate() {
+            @Override public boolean apply() {
+                File[] archivedFiles = walDir.listFiles(new FileFilter() {
+                    @Override public boolean accept(File pathname) {
+                        return pathname.getName().endsWith(".wal");
+                    }
+                });
+
+                return archivedFiles.length == 39;
+            }
+        }, 5000);
+
+        stopGrid(0);
+
+        compactionEnabled = true;
+
+        ex = startGrid(0);
+
+        ex.cluster().active(true);
+
+        File archiveDir = U.resolveWorkDirectory(
+                ex.configuration().getWorkDirectory(),
+                "db/wal/archive/node00-" + ex.localNode().consistentId(),
+                false
+        );
+
+        GridTestUtils.waitForCondition(new GridAbsPredicate() {
+            @Override public boolean apply() {
+                File[] archivedFiles = archiveDir.listFiles(new FileFilter() {
+                    @Override public boolean accept(File pathname) {
+                        return pathname.getName().endsWith(FilePageStoreManager.ZIP_SUFFIX);
+                    }
+                });
+
+                return archivedFiles.length == 20;
+            }
+        }, 5000);
+
+        File[] tmpFiles = archiveDir.listFiles(new FileFilter() {
+            @Override public boolean accept(File pathname) {
+                return pathname.getName().endsWith(FilePageStoreManager.TMP_SUFFIX);
+            }
+        });
+
+        assertEquals(0, tmpFiles.length);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopAllGrids();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/e87aa510/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsMvccTestSuite2.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsMvccTestSuite2.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsMvccTestSuite2.java
index 69718a5..429bd0f 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsMvccTestSuite2.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsMvccTestSuite2.java
@@ -36,6 +36,7 @@ import org.apache.ignite.internal.processors.cache.persistence.db.wal.IgniteWalF
 import org.apache.ignite.internal.processors.cache.persistence.db.wal.IgniteWalIteratorExceptionDuringReadTest;
 import org.apache.ignite.internal.processors.cache.persistence.db.wal.IgniteWalIteratorSwitchSegmentTest;
 import org.apache.ignite.internal.processors.cache.persistence.db.wal.IgniteWalSerializerVersionTest;
+import org.apache.ignite.internal.processors.cache.persistence.db.wal.WalCompactionSwitchOnTest;
 import org.apache.ignite.internal.processors.cache.persistence.db.wal.WalCompactionTest;
 import org.apache.ignite.internal.processors.cache.persistence.db.wal.WalRolloverTypesTest;
 import org.apache.ignite.internal.processors.cache.persistence.db.wal.crc.IgniteDataIntegrityTests;
@@ -86,6 +87,7 @@ public class IgnitePdsMvccTestSuite2 {
         ignoredTests.add(IgniteUidAsConsistentIdMigrationTest.class);
         ignoredTests.add(IgniteWalSerializerVersionTest.class);
         ignoredTests.add(WalCompactionTest.class);
+        ignoredTests.add(WalCompactionSwitchOnTest.class);
         ignoredTests.add(IgniteWalIteratorSwitchSegmentTest.class);
         ignoredTests.add(IgniteWalIteratorExceptionDuringReadTest.class);
         ignoredTests.add(StandaloneWalRecordsIteratorTest.class);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e87aa510/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsTestSuite2.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsTestSuite2.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsTestSuite2.java
index 99179ca..0ff700c 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsTestSuite2.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgnitePdsTestSuite2.java
@@ -58,6 +58,7 @@ import org.apache.ignite.internal.processors.cache.persistence.db.wal.IgniteWalH
 import org.apache.ignite.internal.processors.cache.persistence.db.wal.IgniteWalIteratorExceptionDuringReadTest;
 import org.apache.ignite.internal.processors.cache.persistence.db.wal.IgniteWalIteratorSwitchSegmentTest;
 import org.apache.ignite.internal.processors.cache.persistence.db.wal.IgniteWalSerializerVersionTest;
+import org.apache.ignite.internal.processors.cache.persistence.db.wal.WalCompactionSwitchOnTest;
 import org.apache.ignite.internal.processors.cache.persistence.db.wal.WalCompactionTest;
 import org.apache.ignite.internal.processors.cache.persistence.db.wal.WalDeletionArchiveFsyncTest;
 import org.apache.ignite.internal.processors.cache.persistence.db.wal.WalDeletionArchiveLogOnlyTest;
@@ -188,6 +189,7 @@ public class IgnitePdsTestSuite2 {
         GridTestUtils.addTestIfNeeded(suite, IgniteWalSerializerVersionTest.class, ignoredTests);
 
         GridTestUtils.addTestIfNeeded(suite, WalCompactionTest.class, ignoredTests);
+        GridTestUtils.addTestIfNeeded(suite, WalCompactionSwitchOnTest.class, ignoredTests);
 
         GridTestUtils.addTestIfNeeded(suite, WalDeletionArchiveFsyncTest.class, ignoredTests);
         GridTestUtils.addTestIfNeeded(suite, WalDeletionArchiveLogOnlyTest.class, ignoredTests);