You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by vo...@apache.org on 2016/09/06 14:39:23 UTC

[01/50] [abbrv] ignite git commit: IGNITE-2949 - Replaced JCache dependency with Geronimo

Repository: ignite
Updated Branches:
  refs/heads/ignite-1.5.31-1 [created] 0d7049c6a


IGNITE-2949 - Replaced JCache dependency with Geronimo


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

Branch: refs/heads/ignite-1.5.31-1
Commit: bebf3f07afd4f163919de4ac55c42312abaeae2f
Parents: 093924b
Author: Valentin Kulichenko <va...@gmail.com>
Authored: Tue Jul 5 18:09:10 2016 -0700
Committer: Valentin Kulichenko <va...@gmail.com>
Committed: Tue Jul 5 18:09:10 2016 -0700

----------------------------------------------------------------------
 assembly/LICENSE_FABRIC                   | 8 +-------
 assembly/LICENSE_HADOOP                   | 6 ------
 examples/pom-standalone-lgpl.xml          | 6 +++---
 examples/pom-standalone.xml               | 6 +++---
 examples/pom.xml                          | 6 +++---
 examples/schema-import/pom-standalone.xml | 6 +++---
 examples/schema-import/pom.xml            | 6 +++---
 modules/cassandra/pom.xml                 | 4 ++--
 modules/core/pom.xml                      | 6 +++---
 modules/flume/README.txt                  | 2 +-
 parent/pom.xml                            | 1 -
 11 files changed, 22 insertions(+), 35 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/bebf3f07/assembly/LICENSE_FABRIC
----------------------------------------------------------------------
diff --git a/assembly/LICENSE_FABRIC b/assembly/LICENSE_FABRIC
index 3f92502..8cb5730 100644
--- a/assembly/LICENSE_FABRIC
+++ b/assembly/LICENSE_FABRIC
@@ -227,12 +227,6 @@ For details, see CC0 1.0 Universal (1.0), Public Domain Dedication,
 http://creativecommons.org/publicdomain/zero/1.0/
 
 ==============================================================================
-For JSR107 API and SPI (https://github.com/jsr107/jsr107spec) javax.cache:cache-api:jar:1.0.0
-==============================================================================
-This product bundles JSR107 API and SPI which is available under a:
-JSR-000107 JCACHE 2.9 Public Review - Updated Specification License. For details, see https://raw.github.com/jsr107/jsr107spec/master/LICENSE.txt.
-
-==============================================================================
 For JSch (http://www.jcraft.com/jsch/) com.jcraft:jsch:jar:0.1.50
 ==============================================================================
 This product bundles JSch which is available under a:
@@ -303,4 +297,4 @@ Eclipse Public License - Version 1.0. For details, see http://www.eclipse.org/or
 For SLF4J API Module (http://www.slf4j.org) org.slf4j:slf4j-api:jar:1.6.4
 ==============================================================================
 This product bundles SLF4J API Module which is available under a:
-MIT License. For details, see http://www.opensource.org/licenses/mit-license.php.
\ No newline at end of file
+MIT License. For details, see http://www.opensource.org/licenses/mit-license.php.

http://git-wip-us.apache.org/repos/asf/ignite/blob/bebf3f07/assembly/LICENSE_HADOOP
----------------------------------------------------------------------
diff --git a/assembly/LICENSE_HADOOP b/assembly/LICENSE_HADOOP
index 8d4cc62..0d05d52 100644
--- a/assembly/LICENSE_HADOOP
+++ b/assembly/LICENSE_HADOOP
@@ -227,12 +227,6 @@ For details, see CC0 1.0 Universal (1.0), Public Domain Dedication,
 http://creativecommons.org/publicdomain/zero/1.0/
 
 ==============================================================================
-For JSR107 API and SPI (https://github.com/jsr107/jsr107spec) javax.cache:cache-api:jar:1.0.0
-==============================================================================
-This product bundles JSR107 API and SPI which is available under a:
-JSR-000107 JCACHE 2.9 Public Review - Updated Specification License. For details, see https://raw.github.com/jsr107/jsr107spec/master/LICENSE.txt.
-
-==============================================================================
 For JSch (http://www.jcraft.com/jsch/) com.jcraft:jsch:jar:0.1.50
 ==============================================================================
 This product bundles JSch which is available under a:

http://git-wip-us.apache.org/repos/asf/ignite/blob/bebf3f07/examples/pom-standalone-lgpl.xml
----------------------------------------------------------------------
diff --git a/examples/pom-standalone-lgpl.xml b/examples/pom-standalone-lgpl.xml
index 7e7ccc2..951fab6 100644
--- a/examples/pom-standalone-lgpl.xml
+++ b/examples/pom-standalone-lgpl.xml
@@ -41,9 +41,9 @@
 
     <dependencies>
         <dependency>
-            <groupId>javax.cache</groupId>
-            <artifactId>cache-api</artifactId>
-            <version>1.0.0</version>
+            <groupId>org.apache.geronimo.specs</groupId>
+            <artifactId>geronimo-jcache_1.0_spec</artifactId>
+            <version>1.0-alpha-1</version>
         </dependency>
 
         <dependency>

http://git-wip-us.apache.org/repos/asf/ignite/blob/bebf3f07/examples/pom-standalone.xml
----------------------------------------------------------------------
diff --git a/examples/pom-standalone.xml b/examples/pom-standalone.xml
index 6247ced..20399ee 100644
--- a/examples/pom-standalone.xml
+++ b/examples/pom-standalone.xml
@@ -41,9 +41,9 @@
 
     <dependencies>
         <dependency>
-            <groupId>javax.cache</groupId>
-            <artifactId>cache-api</artifactId>
-            <version>1.0.0</version>
+            <groupId>org.apache.geronimo.specs</groupId>
+            <artifactId>geronimo-jcache_1.0_spec</artifactId>
+            <version>1.0-alpha-1</version>
         </dependency>
 
         <dependency>

http://git-wip-us.apache.org/repos/asf/ignite/blob/bebf3f07/examples/pom.xml
----------------------------------------------------------------------
diff --git a/examples/pom.xml b/examples/pom.xml
index d8a38d8..1c03a24 100644
--- a/examples/pom.xml
+++ b/examples/pom.xml
@@ -32,9 +32,9 @@
 
     <dependencies>
         <dependency>
-            <groupId>javax.cache</groupId>
-            <artifactId>cache-api</artifactId>
-            <version>${javax.cache.version}</version>
+            <groupId>org.apache.geronimo.specs</groupId>
+            <artifactId>geronimo-jcache_1.0_spec</artifactId>
+            <version>1.0-alpha-1</version>
         </dependency>
 
         <dependency>

http://git-wip-us.apache.org/repos/asf/ignite/blob/bebf3f07/examples/schema-import/pom-standalone.xml
----------------------------------------------------------------------
diff --git a/examples/schema-import/pom-standalone.xml b/examples/schema-import/pom-standalone.xml
index e443728..43b76d8 100644
--- a/examples/schema-import/pom-standalone.xml
+++ b/examples/schema-import/pom-standalone.xml
@@ -36,9 +36,9 @@
 
     <dependencies>
         <dependency>
-            <groupId>javax.cache</groupId>
-            <artifactId>cache-api</artifactId>
-            <version>1.0.0</version>
+            <groupId>org.apache.geronimo.specs</groupId>
+            <artifactId>geronimo-jcache_1.0_spec</artifactId>
+            <version>1.0-alpha-1</version>
         </dependency>
 
         <dependency>

http://git-wip-us.apache.org/repos/asf/ignite/blob/bebf3f07/examples/schema-import/pom.xml
----------------------------------------------------------------------
diff --git a/examples/schema-import/pom.xml b/examples/schema-import/pom.xml
index 62bb773..eb1236d 100644
--- a/examples/schema-import/pom.xml
+++ b/examples/schema-import/pom.xml
@@ -39,9 +39,9 @@
 
     <dependencies>
         <dependency>
-            <groupId>javax.cache</groupId>
-            <artifactId>cache-api</artifactId>
-            <version>${javax.cache.version}</version>
+            <groupId>org.apache.geronimo.specs</groupId>
+            <artifactId>geronimo-jcache_1.0_spec</artifactId>
+            <version>1.0-alpha-1</version>
         </dependency>
 
         <dependency>

http://git-wip-us.apache.org/repos/asf/ignite/blob/bebf3f07/modules/cassandra/pom.xml
----------------------------------------------------------------------
diff --git a/modules/cassandra/pom.xml b/modules/cassandra/pom.xml
index 4a1469a..2eff19e 100644
--- a/modules/cassandra/pom.xml
+++ b/modules/cassandra/pom.xml
@@ -237,7 +237,7 @@
                                 org.apache.ignite,org.springframework,org.gridgain
                             </excludeGroupIds>
                             <excludeArtifactIds>
-                                commons-logging,slf4j-api,cache-api,slf4j-api,aopalliance
+                                commons-logging,slf4j-api,geronimo-jcache_1.0_spec,slf4j-api,aopalliance
                             </excludeArtifactIds>
                             <includeScope>runtime</includeScope>
                         </configuration>
@@ -337,4 +337,4 @@
 
         </plugins>
     </build>
-</project>
\ No newline at end of file
+</project>

http://git-wip-us.apache.org/repos/asf/ignite/blob/bebf3f07/modules/core/pom.xml
----------------------------------------------------------------------
diff --git a/modules/core/pom.xml b/modules/core/pom.xml
index b80a924..fe3a477 100644
--- a/modules/core/pom.xml
+++ b/modules/core/pom.xml
@@ -63,9 +63,9 @@
 
     <dependencies>
         <dependency>
-            <groupId>javax.cache</groupId>
-            <artifactId>cache-api</artifactId>
-            <version>${javax.cache.version}</version>
+            <groupId>org.apache.geronimo.specs</groupId>
+            <artifactId>geronimo-jcache_1.0_spec</artifactId>
+            <version>1.0-alpha-1</version>
         </dependency>
 
         <dependency>

http://git-wip-us.apache.org/repos/asf/ignite/blob/bebf3f07/modules/flume/README.txt
----------------------------------------------------------------------
diff --git a/modules/flume/README.txt b/modules/flume/README.txt
index bf7e0ff..97d8cac 100644
--- a/modules/flume/README.txt
+++ b/modules/flume/README.txt
@@ -20,7 +20,7 @@ plugins.d/
     |-- lib
     |   `-- ignite-flume-transformer-x.x.x.jar <-- your jar
     `-- libext
-        |-- cache-api-1.0.0.jar
+        |-- geronimo-jcache_1.0_spec-1.0-alpha-1.jar
         |-- ignite-core-x.x.x.jar
         |-- ignite-flume-x.x.x.jar <-- IgniteSink
         |-- ignite-spring-x.x.x.jar

http://git-wip-us.apache.org/repos/asf/ignite/blob/bebf3f07/parent/pom.xml
----------------------------------------------------------------------
diff --git a/parent/pom.xml b/parent/pom.xml
index 1553612..6600542 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -75,7 +75,6 @@
         <jackson.version>1.9.13</jackson.version>
         <jackson2.version>2.7.5</jackson2.version>
         <javax.cache.bundle.version>1.0.0_1</javax.cache.bundle.version>
-        <javax.cache.version>1.0.0</javax.cache.version>
         <jetty.version>9.2.11.v20150529</jetty.version>
         <jms.spec.version>1.1.1</jms.spec.version>
         <jsch.bundle.version>0.1.53_1</jsch.bundle.version>


[28/50] [abbrv] ignite git commit: Merge branch 'gridgain-7.5.30' of https://github.com/gridgain/apache-ignite into gridgain-7.5.30

Posted by vo...@apache.org.
Merge branch 'gridgain-7.5.30' of https://github.com/gridgain/apache-ignite into gridgain-7.5.30


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 6389400a91f1fc95c9b55e78ab8eef55f99b1093
Parents: 2537e0f 27f6c58
Author: Denis Magda <dm...@gridgain.com>
Authored: Fri Jul 15 09:35:57 2016 +0300
Committer: Denis Magda <dm...@gridgain.com>
Committed: Fri Jul 15 09:35:57 2016 +0300

----------------------------------------------------------------------
 .../examples/IndexingBridgeMethodTest.java      |  93 ++++++++++++
 .../IgniteExamplesJ8SelfTestSuite.java          |   2 +
 .../configuration/CacheConfiguration.java       |   3 +
 .../OptimizedObjectStreamRegistry.java          | 145 +++++++++++--------
 .../OptimizedMarshallerPooledSelfTest.java      |  44 ++++++
 .../testsuites/IgniteBinaryBasicTestSuite.java  |   2 +
 .../IgniteMarshallerSelfTestSuite.java          |   2 +
 7 files changed, 228 insertions(+), 63 deletions(-)
----------------------------------------------------------------------



[14/50] [abbrv] ignite git commit: Backported test fixes.

Posted by vo...@apache.org.
Backported test fixes.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: f045558c6152de274f6c9a7539d69b0645fe3526
Parents: e2ec9fe
Author: sboikov <sb...@gridgain.com>
Authored: Mon Jul 4 21:08:24 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Thu Jul 7 12:38:04 2016 +0300

----------------------------------------------------------------------
 .../cache/GridCacheAbstractFullApiSelfTest.java | 322 ++++++++++---------
 ...idCacheNearOnlyMultiNodeFullApiSelfTest.java | 170 ++++------
 .../junits/common/GridCommonAbstractTest.java   |  12 +-
 .../multijvm/IgniteCacheProcessProxy.java       | 107 +++---
 4 files changed, 301 insertions(+), 310 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/f045558c/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractFullApiSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractFullApiSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractFullApiSelfTest.java
index 41d93b1..179e601 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractFullApiSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractFullApiSelfTest.java
@@ -70,6 +70,7 @@ import org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager;
 import org.apache.ignite.internal.processors.resource.GridSpringResourceContext;
 import org.apache.ignite.internal.util.lang.GridAbsPredicate;
 import org.apache.ignite.internal.util.lang.GridAbsPredicateX;
+import org.apache.ignite.internal.util.lang.IgnitePair;
 import org.apache.ignite.internal.util.typedef.CIX1;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.PA;
@@ -219,6 +220,8 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
     /** {@inheritDoc} */
     @Override protected void beforeTestsStarted() throws Exception {
+        initStoreStrategy();
+
         if (cacheStartType() == CacheStartMode.STATIC)
             super.beforeTestsStarted();
         else {
@@ -262,17 +265,12 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
     }
 
     /**
-     * Checks that skipStore flag gets overriden inside a transaction.
-     *
-     * @throws Exception if failed.
+     * Checks that skipStore flag gets overridden inside a transaction.
      */
     public void testWriteThroughTx() {
-        if(isMultiJvm())
-            fail("https://issues.apache.org/jira/browse/IGNITE-1088");
-
         String key = "writeThroughKey";
 
-        map.remove(key);
+        storeStgy.removeFromStore(key);
 
         try (final Transaction transaction = grid(0).transactions().txStart()) {
             IgniteCache<String, Integer> cache = jcache(0);
@@ -289,27 +287,22 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
             transaction.commit();
         }
 
-        assertEquals(2, map.get(key));
+        assertEquals(2, storeStgy.getFromStore(key));
     }
 
     /**
-     * Checks that skipStore flag gets overriden inside a transaction.
-     *
-     * @throws Exception if failed.
+     * Checks that skipStore flag gets overridden inside a transaction.
      */
     public void testNoReadThroughTx() {
-        if(isMultiJvm())
-            fail("https://issues.apache.org/jira/browse/IGNITE-1088");
-
         String key = "writeThroughKey";
 
         IgniteCache<String, Integer> cache = jcache(0);
 
-        resetStore();
+        storeStgy.resetStore();
 
         cache.put(key, 1);
 
-        putToStore(key, 2);
+        storeStgy.putToStore(key, 2);
 
         try (final Transaction transaction = grid(0).transactions().txStart()) {
             Integer old = cache.get(key);
@@ -323,7 +316,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
             transaction.commit();
         }
 
-        assertEquals(0, reads.get());
+        assertEquals(0, storeStgy.getReads());
     }
 
     /** {@inheritDoc} */
@@ -559,9 +552,6 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
      * @throws Exception If failed.
      */
     public void testRemoveAllSkipStore() throws Exception {
-        if (isMultiJvm())
-            fail("https://issues.apache.org/jira/browse/IGNITE-1088");
-
         IgniteCache<String, Integer> jcache = jcache();
 
         jcache.putAll(F.asMap("1", 1, "2", 2, "3", 3));
@@ -2063,7 +2053,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         // Check db.
         if (!isMultiJvm()) {
-            putToStore("key3", 3);
+            storeStgy.putToStore("key3", 3);
 
             assertEquals((Integer)3, cache.getAndPutIfAbsent("key3", 4));
 
@@ -2135,7 +2125,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         // Check db.
         if (!isMultiJvm()) {
-            putToStore("key3", 3);
+            storeStgy.putToStore("key3", 3);
 
             cacheAsync.getAndPutIfAbsent("key3", 4);
 
@@ -2184,7 +2174,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         // Check db.
         if (!isMultiJvm()) {
-            putToStore("key3", 3);
+            storeStgy.putToStore("key3", 3);
 
             assertFalse(cache.putIfAbsent("key3", 4));
         }
@@ -2257,7 +2247,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         // Check db.
         if (!isMultiJvm()) {
-            putToStore("key3", 3);
+            storeStgy.putToStore("key3", 3);
 
             cacheAsync.putIfAbsent("key3", 4);
 
@@ -2361,7 +2351,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         assert cache.get("key") == 4;
 
         if (!isMultiJvm()) {
-            putToStore("key2", 5);
+            storeStgy.putToStore("key2", 5);
 
             info("key2 5 -> 6");
 
@@ -2420,7 +2410,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         assert cache.get("key") == 4;
 
         if (!isMultiJvm()) {
-            putToStore("key2", 5);
+            storeStgy.putToStore("key2", 5);
 
             assert cache.replace("key2", 6);
 
@@ -2496,7 +2486,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         assert cache.get("key") == 4;
 
         if (!isMultiJvm()) {
-            putToStore("key2", 5);
+            storeStgy.putToStore("key2", 5);
 
             cacheAsync.replace("key2", 5, 6);
 
@@ -2558,7 +2548,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         assert cache.get("key") == 4;
 
         if (!isMultiJvm()) {
-            putToStore("key2", 5);
+            storeStgy.putToStore("key2", 5);
 
             cacheAsync.replace("key2", 6);
 
@@ -2683,9 +2673,6 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
      * @throws Exception If failed.
      */
     public void testRemoveLoad() throws Exception {
-        if (isMultiJvm())
-            fail("https://issues.apache.org/jira/browse/IGNITE-1088");
-
         int cnt = 10;
 
         Set<String> keys = new HashSet<>();
@@ -2696,7 +2683,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         jcache().removeAll(keys);
 
         for (String key : keys)
-            putToStore(key, Integer.parseInt(key));
+            storeStgy.putToStore(key, Integer.parseInt(key));
 
         for (int g = 0; g < gridCount(); g++)
             grid(g).cache(null).localLoadCache(null);
@@ -3572,9 +3559,6 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
      * @throws Exception If failed.
      */
     private void checkTtl(boolean inTx, boolean oldEntry) throws Exception {
-        if (isMultiJvm())
-            fail("https://issues.apache.org/jira/browse/IGNITE-1089");
-
         if (memoryMode() == OFFHEAP_TIERED)
             return;
 
@@ -3586,22 +3570,17 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         final String key = primaryKeysForCache(jcache(), 1).get(0);
 
-        GridCacheAdapter<String, Integer> internalCache = internalCache(fullCache());
-
-        if (internalCache.isNear())
-            internalCache = internalCache.context().near().dht();
-
-        GridCacheEntryEx entry;
+        IgnitePair<Long> entryTtl;
 
         if (oldEntry) {
             c.put(key, 1);
 
-            entry = internalCache.peekEx(key);
+            entryTtl = entryTtl(fullCache(), key);
 
-            assert entry != null;
-
-            assertEquals(0, entry.ttl());
-            assertEquals(0, entry.expireTime());
+            assertNotNull(entryTtl.get1());
+            assertNotNull(entryTtl.get2());
+            assertEquals((Long)0L, entryTtl.get1());
+            assertEquals((Long)0L, entryTtl.get2());
         }
 
         long startTime = System.currentTimeMillis();
@@ -3618,10 +3597,10 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
             }
 
             if (oldEntry) {
-                entry = internalCache.peekEx(key);
+                entryTtl = entryTtl(fullCache(), key);
 
-                assertEquals(0, entry.ttl());
-                assertEquals(0, entry.expireTime());
+                assertEquals((Long)0L, entryTtl.get1());
+                assertEquals((Long)0L, entryTtl.get2());
             }
         }
 
@@ -3643,18 +3622,14 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         for (int i = 0; i < gridCount(); i++) {
             if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key)) {
-                GridCacheAdapter<String, Integer> cache = internalCache(jcache(i));
-
-                if (cache.context().isNear())
-                    cache = cache.context().near().dht();
-
-                GridCacheEntryEx curEntry = cache.peekEx(key);
+                IgnitePair<Long> curEntryTtl = entryTtl(jcache(i), key);
 
-                assertEquals(ttl, curEntry.ttl());
+                assertNotNull(curEntryTtl.get1());
+                assertNotNull(curEntryTtl.get2());
+                assertEquals(ttl, (long) curEntryTtl.get1());
+                assertTrue(curEntryTtl.get2() > startTime);
 
-                assert curEntry.expireTime() > startTime;
-
-                expireTimes[i] = curEntry.expireTime();
+                expireTimes[i] = curEntryTtl.get2();
             }
         }
 
@@ -3676,18 +3651,14 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         for (int i = 0; i < gridCount(); i++) {
             if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key)) {
-                GridCacheAdapter<String, Integer> cache = internalCache(jcache(i));
-
-                if (cache.context().isNear())
-                    cache = cache.context().near().dht();
-
-                GridCacheEntryEx curEntry = cache.peekEx(key);
+                IgnitePair<Long> curEntryTtl = entryTtl(jcache(i), key);
 
-                assertEquals(ttl, curEntry.ttl());
+                assertNotNull(curEntryTtl.get1());
+                assertNotNull(curEntryTtl.get2());
+                assertEquals(ttl, (long) curEntryTtl.get1());
+                assertTrue(curEntryTtl.get2() > startTime);
 
-                assert curEntry.expireTime() > startTime;
-
-                expireTimes[i] = curEntry.expireTime();
+                expireTimes[i] = curEntryTtl.get2();
             }
         }
 
@@ -3709,18 +3680,14 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         for (int i = 0; i < gridCount(); i++) {
             if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key)) {
-                GridCacheAdapter<String, Integer> cache = internalCache(jcache(i));
-
-                if (cache.context().isNear())
-                    cache = cache.context().near().dht();
-
-                GridCacheEntryEx curEntry = cache.peekEx(key);
+                IgnitePair<Long> curEntryTtl = entryTtl(jcache(i), key);
 
-                assertEquals(ttl, curEntry.ttl());
+                assertNotNull(curEntryTtl.get1());
+                assertNotNull(curEntryTtl.get2());
+                assertEquals(ttl, (long) curEntryTtl.get1());
+                assertTrue(curEntryTtl.get2() > startTime);
 
-                assert curEntry.expireTime() > startTime;
-
-                expireTimes[i] = curEntry.expireTime();
+                expireTimes[i] = curEntryTtl.get2();
             }
         }
 
@@ -3746,20 +3713,17 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         for (int i = 0; i < gridCount(); i++) {
             if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key)) {
-                GridCacheAdapter<String, Integer> cache = internalCache(jcache(i));
-
-                if (cache.context().isNear())
-                    cache = cache.context().near().dht();
-
-                GridCacheEntryEx curEntry = cache.peekEx(key);
+                IgnitePair<Long> curEntryTtl = entryTtl(jcache(i), key);
 
-                assertEquals(ttl, curEntry.ttl());
-                assertEquals(expireTimes[i], curEntry.expireTime());
+                assertNotNull(curEntryTtl.get1());
+                assertNotNull(curEntryTtl.get2());
+                assertEquals(ttl, (long)curEntryTtl.get1());
+                assertEquals(expireTimes[i], (long)curEntryTtl.get2());
             }
         }
 
         // Avoid reloading from store.
-        map.remove(key);
+        storeStgy.removeFromStore(key);
 
         assertTrue(GridTestUtils.waitForCondition(new GridAbsPredicateX() {
             @SuppressWarnings("unchecked")
@@ -3790,21 +3754,24 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
             }
         }, Math.min(ttl * 10, getTestTimeout())));
 
-        if (internalCache.isLocal())
-            return;
+        IgniteCache fullCache = fullCache();
 
-        assert c.get(key) == null;
+        if (!isMultiJvmObject(fullCache)) {
+            GridCacheAdapter internalCache = internalCache(fullCache);
 
-        internalCache = internalCache(fullCache());
+            if (internalCache.isLocal())
+                return;
+        }
 
-        if (internalCache.isNear())
-            internalCache = internalCache.context().near().dht();
+        assert c.get(key) == null;
 
         // Ensure that old TTL and expire time are not longer "visible".
-        entry = internalCache.peekEx(key);
+        entryTtl = entryTtl(fullCache(), key);
 
-        assertEquals(0, entry.ttl());
-        assertEquals(0, entry.expireTime());
+        assertNotNull(entryTtl.get1());
+        assertNotNull(entryTtl.get2());
+        assertEquals(0, (long)entryTtl.get1());
+        assertEquals(0, (long)entryTtl.get2());
 
         // Ensure that next update will not pick old expire time.
 
@@ -3823,12 +3790,14 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         U.sleep(2000);
 
-        entry = internalCache.peekEx(key);
+        entryTtl = entryTtl(fullCache(), key);
 
         assertEquals((Integer)10, c.get(key));
 
-        assertEquals(0, entry.ttl());
-        assertEquals(0, entry.expireTime());
+        assertNotNull(entryTtl.get1());
+        assertNotNull(entryTtl.get2());
+        assertEquals(0, (long)entryTtl.get1());
+        assertEquals(0, (long)entryTtl.get2());
     }
 
     /**
@@ -4332,6 +4301,15 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
     }
 
     /**
+     * @param cache Cache.
+     * @param key Entry key.
+     * @return Pair [ttl, expireTime]; both values null if entry not found
+     */
+    protected IgnitePair<Long> entryTtl(IgniteCache cache, String key) {
+        return executeOnLocalOrRemoteJvm(cache, new EntryTtlTask(key, true));
+    }
+
+    /**
      * @throws Exception If failed.
      */
     public void testIterator() throws Exception {
@@ -4752,9 +4730,6 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
      * @throws Exception If failed.
      */
     public void testWithSkipStore() throws Exception {
-        if(isMultiJvm())
-            fail("https://issues.apache.org/jira/browse/IGNITE-1088");
-
         IgniteCache<String, Integer> cache = grid(0).cache(null);
 
         IgniteCache<String, Integer> cacheSkipStore = cache.withSkipStore();
@@ -4762,7 +4737,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         List<String> keys = primaryKeysForCache(cache, 10);
 
         for (int i = 0; i < keys.size(); ++i)
-            putToStore(keys.get(i), i);
+            storeStgy.putToStore(keys.get(i), i);
 
         assertFalse(cacheSkipStore.iterator().hasNext());
 
@@ -4800,7 +4775,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
             assertNotNull(cacheSkipStore.get(key));
             assertNotNull(cache.get(key));
-            assertEquals(i, map.get(key));
+            assertEquals(i, storeStgy.getFromStore(key));
         }
 
         for (int i = 0; i < keys.size(); ++i) {
@@ -4809,13 +4784,13 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
             Integer val1 = -1;
 
             cacheSkipStore.put(key, val1);
-            assertEquals(i, map.get(key));
+            assertEquals(i, storeStgy.getFromStore(key));
             assertEquals(val1, cacheSkipStore.get(key));
 
             Integer val2 = -2;
 
             assertEquals(val1, cacheSkipStore.invoke(key, new SetValueProcessor(val2)));
-            assertEquals(i, map.get(key));
+            assertEquals(i, storeStgy.getFromStore(key));
             assertEquals(val2, cacheSkipStore.get(key));
         }
 
@@ -4824,7 +4799,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
             assertNull(cacheSkipStore.get(key));
             assertNotNull(cache.get(key));
-            assertTrue(map.containsKey(key));
+            assertTrue(storeStgy.isInStore(key));
         }
 
         for (String key : keys) {
@@ -4832,37 +4807,37 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
             assertNull(cacheSkipStore.get(key));
             assertNull(cache.get(key));
-            assertFalse(map.containsKey(key));
+            assertFalse(storeStgy.isInStore(key));
 
-            map.put(key, 0);
+            storeStgy.putToStore(key, 0);
 
             Integer val = -1;
 
             assertNull(cacheSkipStore.invoke(key, new SetValueProcessor(val)));
-            assertEquals(0, map.get(key));
+            assertEquals(0, storeStgy.getFromStore(key));
             assertEquals(val, cacheSkipStore.get(key));
 
             cache.remove(key);
 
-            map.put(key, 0);
+            storeStgy.putToStore(key, 0);
 
             assertTrue(cacheSkipStore.putIfAbsent(key, val));
             assertEquals(val, cacheSkipStore.get(key));
-            assertEquals(0, map.get(key));
+            assertEquals(0, storeStgy.getFromStore(key));
 
             cache.remove(key);
 
-            map.put(key, 0);
+            storeStgy.putToStore(key, 0);
 
             assertNull(cacheSkipStore.getAndPut(key, val));
             assertEquals(val, cacheSkipStore.get(key));
-            assertEquals(0, map.get(key));
+            assertEquals(0, storeStgy.getFromStore(key));
 
             cache.remove(key);
         }
 
         assertFalse(cacheSkipStore.iterator().hasNext());
-        assertTrue(map.size() == 0);
+        assertTrue(storeStgy.getStoreSize() == 0);
         assertTrue(cache.size(ALL) == 0);
 
         // putAll/removeAll from multiple nodes.
@@ -4877,7 +4852,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         for (String key : keys) {
             assertNotNull(cacheSkipStore.get(key));
             assertNotNull(cache.get(key));
-            assertFalse(map.containsKey(key));
+            assertFalse(storeStgy.isInStore(key));
         }
 
         cache.putAll(data);
@@ -4885,7 +4860,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         for (String key : keys) {
             assertNotNull(cacheSkipStore.get(key));
             assertNotNull(cache.get(key));
-            assertTrue(map.containsKey(key));
+            assertTrue(storeStgy.isInStore(key));
         }
 
         cacheSkipStore.removeAll(data.keySet());
@@ -4893,7 +4868,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         for (String key : keys) {
             assertNull(cacheSkipStore.get(key));
             assertNotNull(cache.get(key));
-            assertTrue(map.containsKey(key));
+            assertTrue(storeStgy.isInStore(key));
         }
 
         cacheSkipStore.putAll(data);
@@ -4901,7 +4876,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         for (String key : keys) {
             assertNotNull(cacheSkipStore.get(key));
             assertNotNull(cache.get(key));
-            assertTrue(map.containsKey(key));
+            assertTrue(storeStgy.isInStore(key));
         }
 
         cacheSkipStore.removeAll(data.keySet());
@@ -4909,7 +4884,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         for (String key : keys) {
             assertNull(cacheSkipStore.get(key));
             assertNotNull(cache.get(key));
-            assertTrue(map.containsKey(key));
+            assertTrue(storeStgy.isInStore(key));
         }
 
         cache.removeAll(data.keySet());
@@ -4917,24 +4892,24 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         for (String key : keys) {
             assertNull(cacheSkipStore.get(key));
             assertNull(cache.get(key));
-            assertFalse(map.containsKey(key));
+            assertFalse(storeStgy.isInStore(key));
         }
 
-        assertTrue(map.size() == 0);
+        assertTrue(storeStgy.getStoreSize() == 0);
 
         // Miscellaneous checks.
 
         String newKey = "New key";
 
-        assertFalse(map.containsKey(newKey));
+        assertFalse(storeStgy.isInStore(newKey));
 
         cacheSkipStore.put(newKey, 1);
 
-        assertFalse(map.containsKey(newKey));
+        assertFalse(storeStgy.isInStore(newKey));
 
         cache.put(newKey, 1);
 
-        assertTrue(map.containsKey(newKey));
+        assertTrue(storeStgy.isInStore(newKey));
 
         Iterator<Cache.Entry<String, Integer>> it = cacheSkipStore.iterator();
 
@@ -4944,29 +4919,26 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         String rmvKey = entry.getKey();
 
-        assertTrue(map.containsKey(rmvKey));
+        assertTrue(storeStgy.isInStore(rmvKey));
 
         it.remove();
 
         assertNull(cacheSkipStore.get(rmvKey));
 
-        assertTrue(map.containsKey(rmvKey));
+        assertTrue(storeStgy.isInStore(rmvKey));
 
         assertTrue(cache.size(ALL) == 0);
         assertTrue(cacheSkipStore.size(ALL) == 0);
 
         cache.remove(rmvKey);
 
-        assertTrue(map.size() == 0);
+        assertTrue(storeStgy.getStoreSize() == 0);
     }
 
     /**
      * @throws Exception If failed.
      */
     public void testWithSkipStoreRemoveAll() throws Exception {
-        if (isMultiJvm())
-            fail("https://issues.apache.org/jira/browse/IGNITE-1088");
-
         if (atomicityMode() == TRANSACTIONAL || (atomicityMode() == ATOMIC && nearEnabled())) // TODO IGNITE-373.
             return;
 
@@ -4984,7 +4956,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         for (String key : data.keySet()) {
             assertNotNull(cacheSkipStore.get(key));
             assertNotNull(cache.get(key));
-            assertTrue(map.containsKey(key));
+            assertTrue(storeStgy.isInStore(key));
         }
 
         cacheSkipStore.removeAll();
@@ -4992,7 +4964,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         for (String key : data.keySet()) {
             assertNull(cacheSkipStore.get(key));
             assertNotNull(cache.get(key));
-            assertTrue(map.containsKey(key));
+            assertTrue(storeStgy.isInStore(key));
         }
 
         cache.removeAll();
@@ -5000,7 +4972,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         for (String key : data.keySet()) {
             assertNull(cacheSkipStore.get(key));
             assertNull(cache.get(key));
-            assertFalse(map.containsKey(key));
+            assertFalse(storeStgy.isInStore(key));
         }
     }
 
@@ -5076,7 +5048,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
             for (String key: keys) {
                 assertEquals(val, cacheSkipStore.get(key));
                 assertEquals(val, cache.get(key));
-                assertFalse(map.containsKey(key));
+                assertFalse(storeStgy.isInStore(key));
             }
 
             tx.commit();
@@ -5085,10 +5057,10 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         for (String key: keys) {
             assertEquals(val, cacheSkipStore.get(key));
             assertEquals(val, cache.get(key));
-            assertFalse(map.containsKey(key));
+            assertFalse(storeStgy.isInStore(key));
         }
 
-        assertEquals(0, map.size());
+        assertEquals(0, storeStgy.getStoreSize());
 
         // cacheSkipStore putAll(..)/removeAll(..) check.
         try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) {
@@ -5102,10 +5074,10 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
             assertEquals(val, cacheSkipStore.get(key));
             assertEquals(val, cache.get(key));
-            assertFalse(map.containsKey(key));
+            assertFalse(storeStgy.isInStore(key));
         }
 
-        map.putAll(data);
+        storeStgy.putAllToStore(data);
 
         try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) {
             cacheSkipStore.removeAll(data.keySet());
@@ -5116,12 +5088,12 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         for (String key: keys) {
             assertNull(cacheSkipStore.get(key));
             assertNotNull(cache.get(key));
-            assertTrue(map.containsKey(key));
+            assertTrue(storeStgy.isInStore(key));
 
             cache.remove(key);
         }
 
-        assertTrue(map.size() == 0);
+        assertTrue(storeStgy.getStoreSize() == 0);
 
         // cache putAll(..)/removeAll(..) check.
         try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) {
@@ -5130,7 +5102,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
             for (String key: keys) {
                 assertNotNull(cacheSkipStore.get(key));
                 assertNotNull(cache.get(key));
-                assertFalse(map.containsKey(key));
+                assertFalse(storeStgy.isInStore(key));
             }
 
             cache.removeAll(data.keySet());
@@ -5138,13 +5110,13 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
             for (String key: keys) {
                 assertNull(cacheSkipStore.get(key));
                 assertNull(cache.get(key));
-                assertFalse(map.containsKey(key));
+                assertFalse(storeStgy.isInStore(key));
             }
 
             tx.commit();
         }
 
-        assertTrue(map.size() == 0);
+        assertTrue(storeStgy.getStoreSize() == 0);
 
         // putAll(..) from both cacheSkipStore and cache.
         try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) {
@@ -5165,7 +5137,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
             for (String key: keys) {
                 assertNotNull(cacheSkipStore.get(key));
                 assertNotNull(cache.get(key));
-                assertFalse(map.containsKey(key));
+                assertFalse(storeStgy.isInStore(key));
             }
 
             tx.commit();
@@ -5176,7 +5148,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
             assertNotNull(cacheSkipStore.get(key));
             assertNotNull(cache.get(key));
-            assertFalse(map.containsKey(key));
+            assertFalse(storeStgy.isInStore(key));
         }
 
         for (int i = keys.size() / 2; i < keys.size(); i++) {
@@ -5184,7 +5156,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
             assertNotNull(cacheSkipStore.get(key));
             assertNotNull(cache.get(key));
-            assertTrue(map.containsKey(key));
+            assertTrue(storeStgy.isInStore(key));
         }
 
         cache.removeAll(data.keySet());
@@ -5192,16 +5164,16 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         for (String key: keys) {
             assertNull(cacheSkipStore.get(key));
             assertNull(cache.get(key));
-            assertFalse(map.containsKey(key));
+            assertFalse(storeStgy.isInStore(key));
         }
 
         // Check that read-through is disabled when cacheSkipStore is used.
         for (int i = 0; i < keys.size(); i++)
-            putToStore(keys.get(i), i);
+            storeStgy.putToStore(keys.get(i), i);
 
         assertTrue(cacheSkipStore.size(ALL) == 0);
         assertTrue(cache.size(ALL) == 0);
-        assertTrue(map.size() != 0);
+        assertTrue(storeStgy.getStoreSize() != 0);
 
         try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) {
             assertTrue(cacheSkipStore.getAll(data.keySet()).size() == 0);
@@ -5224,7 +5196,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) {
             for (String key : data.keySet()) {
-                map.put(key, 0);
+                storeStgy.putToStore(key, 0);
 
                 assertNull(cacheSkipStore.invoke(key, new SetValueProcessor(val)));
             }
@@ -5233,7 +5205,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         }
 
         for (String key : data.keySet()) {
-            assertEquals(0, map.get(key));
+            assertEquals(0, storeStgy.getFromStore(key));
 
             assertEquals(val, cacheSkipStore.get(key));
             assertEquals(val, cache.get(key));
@@ -5243,7 +5215,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) {
             for (String key : data.keySet()) {
-                map.put(key, 0);
+                storeStgy.putToStore(key, 0);
 
                 assertTrue(cacheSkipStore.putIfAbsent(key, val));
             }
@@ -5252,7 +5224,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         }
 
         for (String key : data.keySet()) {
-            assertEquals(0, map.get(key));
+            assertEquals(0, storeStgy.getFromStore(key));
 
             assertEquals(val, cacheSkipStore.get(key));
             assertEquals(val, cache.get(key));
@@ -5262,7 +5234,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
 
         try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) {
             for (String key : data.keySet()) {
-                map.put(key, 0);
+                storeStgy.putToStore(key, 0);
 
                 assertNull(cacheSkipStore.getAndPut(key, val));
             }
@@ -5271,7 +5243,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         }
 
         for (String key : data.keySet()) {
-            assertEquals(0, map.get(key));
+            assertEquals(0, storeStgy.getFromStore(key));
 
             assertEquals(val, cacheSkipStore.get(key));
             assertEquals(val, cache.get(key));
@@ -5291,7 +5263,7 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
         throws Exception {
         assertTrue(cache.size(ALL) == 0);
         assertTrue(cacheSkipStore.size(ALL) == 0);
-        assertTrue(map.size() == 0);
+        assertTrue(storeStgy.getStoreSize() == 0);
     }
 
     /**
@@ -5631,6 +5603,40 @@ public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstract
     /**
      *
      */
+    public static class EntryTtlTask implements TestCacheCallable<String, Integer, IgnitePair<Long>> {
+        /** Entry key. */
+        private final String key;
+
+        /** Check cache for nearness, use DHT cache if it is near. */
+        private final boolean useDhtForNearCache;
+
+        /**
+         * @param key Entry key.
+         * @param useDhtForNearCache Check cache for nearness, use DHT cache if it is near.
+         */
+        public EntryTtlTask(String key, boolean useDhtForNearCache) {
+            this.key = key;
+            this.useDhtForNearCache = useDhtForNearCache;
+        }
+
+        /** {@inheritDoc} */
+        @Override public IgnitePair<Long> call(Ignite ignite, IgniteCache<String, Integer> cache) throws Exception {
+            GridCacheAdapter<?, ?> internalCache = internalCache0(cache);
+
+            if (useDhtForNearCache && internalCache.context().isNear())
+                internalCache = internalCache.context().near().dht();
+
+            GridCacheEntryEx entry = internalCache.peekEx(key);
+
+            return entry != null ?
+                new IgnitePair<>(entry.ttl(), entry.expireTime()) :
+                new IgnitePair<Long>(null, null);
+        }
+    }
+
+    /**
+     *
+     */
     private static class CheckIteratorTask extends TestIgniteIdxCallable<Void> {
         /**
          * @param idx Index.

http://git-wip-us.apache.org/repos/asf/ignite/blob/f045558c/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCacheNearOnlyMultiNodeFullApiSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCacheNearOnlyMultiNodeFullApiSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCacheNearOnlyMultiNodeFullApiSelfTest.java
index eaab103..5fab800 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCacheNearOnlyMultiNodeFullApiSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCacheNearOnlyMultiNodeFullApiSelfTest.java
@@ -39,10 +39,10 @@ import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.configuration.NearCacheConfiguration;
 import org.apache.ignite.events.Event;
-import org.apache.ignite.internal.processors.cache.GridCacheAdapter;
 import org.apache.ignite.internal.processors.cache.GridCacheEntryEx;
 import org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException;
 import org.apache.ignite.internal.util.lang.GridAbsPredicateX;
+import org.apache.ignite.internal.util.lang.IgnitePair;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.P1;
 import org.apache.ignite.internal.util.typedef.internal.U;
@@ -211,6 +211,10 @@ public class GridCacheNearOnlyMultiNodeFullApiSelfTest extends GridCachePartitio
      * @throws Exception If failed.
      */
     public void testReaderTtlTx() throws Exception {
+        // IgniteProcessProxy#transactions is not implemented.
+        if (isMultiJvm())
+            return;
+
         checkReaderTtl(true);
     }
 
@@ -222,13 +226,19 @@ public class GridCacheNearOnlyMultiNodeFullApiSelfTest extends GridCachePartitio
     }
 
     /**
+     * @param cache Cache.
+     * @param key Entry key.
+     * @return Pair [ttl, expireTime] for near cache entry; both values null if entry not found
+     */
+    protected IgnitePair<Long> nearEntryTtl(IgniteCache cache, String key) {
+        return executeOnLocalOrRemoteJvm(cache, new EntryTtlTask(key, false));
+    }
+
+    /**
      * @param inTx If {@code true} starts explicit transaction.
      * @throws Exception If failed.
      */
     private void checkReaderTtl(boolean inTx) throws Exception {
-        if (isMultiJvm())
-            fail("https://issues.apache.org/jira/browse/IGNITE-1089");
-
         int ttl = 1000;
 
         final ExpiryPolicy expiry = new TouchedExpiryPolicy(new Duration(TimeUnit.MILLISECONDS, ttl));
@@ -242,17 +252,14 @@ public class GridCacheNearOnlyMultiNodeFullApiSelfTest extends GridCachePartitio
         info("Finished first put.");
 
         {
-            GridCacheAdapter<String, Integer> dht = internalCache(fullCache());
-
-            if (dht.context().isNear())
-                dht = dht.context().near().dht();
+            IgnitePair<Long> entryTtl = entryTtl(fullCache(), key);
 
-            GridCacheEntryEx entry = dht.peekEx(key);
+            assertEquals((Integer)1, c.get(key));
 
-            assert entry != null;
-
-            assertEquals(0, entry.ttl());
-            assertEquals(0, entry.expireTime());
+            assertNotNull(entryTtl.get1());
+            assertNotNull(entryTtl.get2());
+            assertEquals(0, (long)entryTtl.get1());
+            assertEquals(0, (long)entryTtl.get2());
         }
 
         long startTime = System.currentTimeMillis();
@@ -278,30 +285,19 @@ public class GridCacheNearOnlyMultiNodeFullApiSelfTest extends GridCachePartitio
         for (int i = 0; i < gridCount(); i++) {
             info("Checking grid: " + grid(i).localNode().id());
 
-            GridCacheEntryEx entry = null;
-
-            if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key)) {
-                GridCacheAdapter<String, Integer> dht = internalCache(jcache(i));
+            IgnitePair<Long> entryTtl = null;
 
-                if (dht.context().isNear())
-                    dht = dht.context().near().dht();
+            if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key))
+                entryTtl = entryTtl(jcache(i), key);
+            else if (i == nearIdx)
+                entryTtl = nearEntryTtl(jcache(i), key);
 
-                entry = dht.peekEx(key);
-
-                assert entry != null;
-            }
-            else if (i == nearIdx) {
-                GridCacheAdapter<String, Integer> near = internalCache(jcache(i));
-
-                entry = near.peekEx(key);
-
-                assert entry != null;
-            }
-
-            if (entry != null) {
-                assertEquals(ttl, entry.ttl());
-                assert entry.expireTime() > startTime;
-                expireTimes[i] = entry.expireTime();
+            if (entryTtl != null) {
+                assertNotNull(entryTtl.get1());
+                assertNotNull(entryTtl.get2());
+                assertEquals(ttl, (long)entryTtl.get1());
+                assertTrue(entryTtl.get2() > startTime);
+                expireTimes[i] = entryTtl.get2();
             }
         }
 
@@ -322,30 +318,19 @@ public class GridCacheNearOnlyMultiNodeFullApiSelfTest extends GridCachePartitio
         }
 
         for (int i = 0; i < gridCount(); i++) {
-            GridCacheEntryEx entry = null;
-
-            if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key)) {
-                GridCacheAdapter<String, Integer> dht = internalCache(jcache(i));
-
-                if (dht.context().isNear())
-                    dht = dht.context().near().dht();
-
-                entry = dht.peekEx(key);
-
-                assert entry != null;
-            }
-            else if (i == nearIdx) {
-                GridCacheAdapter<String, Integer> near = internalCache(jcache(i));
-
-                entry = near.peekEx(key);
-
-                assert entry != null;
-            }
-
-            if (entry != null) {
-                assertEquals(ttl, entry.ttl());
-                assert entry.expireTime() > expireTimes[i];
-                expireTimes[i] = entry.expireTime();
+            IgnitePair<Long> entryTtl = null;
+
+            if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key))
+                entryTtl = entryTtl(jcache(i), key);
+            else if (i == nearIdx)
+                entryTtl = nearEntryTtl(jcache(i), key);
+
+            if (entryTtl != null) {
+                assertNotNull(entryTtl.get1());
+                assertNotNull(entryTtl.get2());
+                assertEquals(ttl, (long)entryTtl.get1());
+                assertTrue(entryTtl.get2() > startTime);
+                expireTimes[i] = entryTtl.get2();
             }
         }
 
@@ -363,34 +348,23 @@ public class GridCacheNearOnlyMultiNodeFullApiSelfTest extends GridCachePartitio
         }
 
         for (int i = 0; i < gridCount(); i++) {
-            GridCacheEntryEx entry = null;
-
-            if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key)) {
-                GridCacheAdapter<String, Integer> dht = internalCache(jcache(i));
-
-                if (dht.context().isNear())
-                    dht = dht.context().near().dht();
-
-                entry = dht.peekEx(key);
-
-                assert entry != null;
-            }
-            else if (i == nearIdx) {
-                GridCacheAdapter<String, Integer> near = internalCache(jcache(i));
-
-                entry = near.peekEx(key);
-
-                assert entry != null;
-            }
-
-            if (entry != null) {
-                assertEquals(ttl, entry.ttl());
-                assertEquals(expireTimes[i], entry.expireTime());
+            IgnitePair<Long> entryTtl = null;
+
+            if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key))
+                entryTtl = entryTtl(jcache(i), key);
+            else if (i == nearIdx)
+                entryTtl = nearEntryTtl(jcache(i), key);
+
+            if (entryTtl != null) {
+                assertNotNull(entryTtl.get1());
+                assertNotNull(entryTtl.get2());
+                assertEquals(ttl, (long)entryTtl.get1());
+                assertEquals(expireTimes[i], (long)entryTtl.get2());
             }
         }
 
         // Avoid reloading from store.
-        map.remove(key);
+        storeStgy.removeFromStore(key);
 
         assertTrue(GridTestUtils.waitForCondition(new GridAbsPredicateX() {
             @SuppressWarnings("unchecked")
@@ -421,17 +395,12 @@ public class GridCacheNearOnlyMultiNodeFullApiSelfTest extends GridCachePartitio
 
         // Ensure that old TTL and expire time are not longer "visible".
         {
-            GridCacheAdapter<String, Integer> dht = internalCache(fullCache());
-
-            if (dht.context().isNear())
-                dht = dht.context().near().dht();
+            IgnitePair<Long> entryTtl = entryTtl(fullCache(), key);
 
-            GridCacheEntryEx entry = dht.peekEx(key);
-
-            assert entry != null;
-
-            assertEquals(0, entry.ttl());
-            assertEquals(0, entry.expireTime());
+            assertNotNull(entryTtl.get1());
+            assertNotNull(entryTtl.get2());
+            assertEquals(0, (long)entryTtl.get1());
+            assertEquals(0, (long)entryTtl.get2());
         }
 
         // Ensure that next update will not pick old expire time.
@@ -451,17 +420,12 @@ public class GridCacheNearOnlyMultiNodeFullApiSelfTest extends GridCachePartitio
         U.sleep(2000);
 
         {
-            GridCacheAdapter<String, Integer> dht = internalCache(fullCache());
-
-            if (dht.context().isNear())
-                dht = dht.context().near().dht();
-
-            GridCacheEntryEx entry = dht.peekEx(key);
-
-            assert entry != null;
+            IgnitePair<Long> entryTtl = entryTtl(fullCache(), key);
 
-            assertEquals(0, entry.ttl());
-            assertEquals(0, entry.expireTime());
+            assertNotNull(entryTtl.get1());
+            assertNotNull(entryTtl.get2());
+            assertEquals(0, (long)entryTtl.get1());
+            assertEquals(0, (long)entryTtl.get2());
         }
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/f045558c/modules/core/src/test/java/org/apache/ignite/testframework/junits/common/GridCommonAbstractTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/junits/common/GridCommonAbstractTest.java b/modules/core/src/test/java/org/apache/ignite/testframework/junits/common/GridCommonAbstractTest.java
index 4d40c68..18a0f6a 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/junits/common/GridCommonAbstractTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/junits/common/GridCommonAbstractTest.java
@@ -159,15 +159,23 @@ public abstract class GridCommonAbstractTest extends GridAbstractTest {
      * @param cache Cache.
      * @return Cache.
      */
-    protected <K, V> GridCacheAdapter<K, V> internalCache(IgniteCache<K, V> cache) {
+    protected static <K, V> GridCacheAdapter<K, V> internalCache0(IgniteCache<K, V> cache) {
         if (isMultiJvmObject(cache))
-            throw new UnsupportedOperationException("Oparetion can't be supported automatically for multi jvm " +
+            throw new UnsupportedOperationException("Operation can't be supported automatically for multi jvm " +
                 "(send closure instead).");
 
         return ((IgniteKernal)cache.unwrap(Ignite.class)).internalCache(cache.getName());
     }
 
     /**
+     * @param cache Cache.
+     * @return Cache.
+     */
+    protected <K, V> GridCacheAdapter<K, V> internalCache(IgniteCache<K, V> cache) {
+        return internalCache0(cache);
+    }
+
+    /**
      * @return Cache.
      */
     protected <K, V> IgniteCache<K, V> jcache() {

http://git-wip-us.apache.org/repos/asf/ignite/blob/f045558c/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java b/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
index 7286fb3..f2f69dd 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
@@ -65,6 +65,9 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
     /** With async. */
     private final boolean isAsync;
 
+    /** Expiry policy. */
+    private final ExpiryPolicy expiryPlc;
+
     /** Ignite proxy. */
     private final transient IgniteProcessProxy igniteProxy;
 
@@ -73,24 +76,26 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
      * @param proxy Ignite Process Proxy.
      */
     public IgniteCacheProcessProxy(String name, IgniteProcessProxy proxy) {
-        this(name, false, proxy);
+        this(name, false, null, proxy);
     }
 
     /**
      * @param name Name.
      * @param async Async flag.
+     * @param plc Expiry policy.
      * @param proxy Ignite Process Proxy.
      */
-    public IgniteCacheProcessProxy(String name, boolean async, IgniteProcessProxy proxy) {
+    private IgniteCacheProcessProxy(String name, boolean async, ExpiryPolicy plc, IgniteProcessProxy proxy) {
         cacheName = name;
         isAsync = async;
+        expiryPlc = plc;
         igniteProxy = proxy;
         compute = proxy.remoteCompute();
     }
 
     /** {@inheritDoc} */
     @Override public IgniteCache<K, V> withAsync() {
-        return new IgniteCacheProcessProxy<>(cacheName, true, igniteProxy);
+        return new IgniteCacheProcessProxy<>(cacheName, true, null, igniteProxy);
     }
 
     /** {@inheritDoc} */
@@ -116,7 +121,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
 
     /** {@inheritDoc} */
     @Override public IgniteCache<K, V> withExpiryPolicy(ExpiryPolicy plc) {
-        throw new UnsupportedOperationException("Method should be supported.");
+        return new IgniteCacheProcessProxy<>(cacheName, isAsync, plc, igniteProxy);
     }
 
     /** {@inheritDoc} */
@@ -261,7 +266,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
 
     /** {@inheritDoc} */
     @Override public void put(K key, V val) {
-        compute.call(new PutTask<>(cacheName, isAsync, key, val));
+        compute.call(new PutTask<>(cacheName, isAsync, expiryPlc, key, val));
     }
 
     /** {@inheritDoc} */
@@ -462,7 +467,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param clazz Clazz.
          */
         public GetConfigurationTask(String cacheName, boolean async, Class<C> clazz) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.clazz = clazz;
         }
 
@@ -489,7 +494,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param args Args.
          */
         public LocalLoadCacheTask(String cacheName, boolean async, IgniteBiPredicate<K, V> p, Object[] args) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.p = p;
             this.args = args;
         }
@@ -519,7 +524,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param val Value.
          */
         public GetAndPutIfAbsentTask(String cacheName, boolean async, K key, V val) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
             this.val = val;
         }
@@ -547,7 +552,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param byCurrThread By current thread.
          */
         public IsLocalLockedTask(String cacheName, boolean async, K key, boolean byCurrThread) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
             this.byCurrThread = byCurrThread;
         }
@@ -571,7 +576,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param peekModes Peek modes.
          */
         public LocalEntriesTask(String cacheName, boolean async, CachePeekMode[] peekModes) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.peekModes = peekModes;
         }
 
@@ -599,7 +604,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param keys Keys.
          */
         public LocalEvictTask(String cacheName, boolean async, Collection<? extends K> keys) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.keys = keys;
         }
 
@@ -628,7 +633,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param peekModes Peek modes.
          */
         public LocalPeekTask(String cacheName, boolean async, K key, CachePeekMode[] peekModes) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
             this.peekModes = peekModes;
         }
@@ -656,7 +661,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param loc Local.
          */
         public SizeTask(String cacheName, boolean async, CachePeekMode[] peekModes, boolean loc) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.loc = loc;
             this.peekModes = peekModes;
         }
@@ -684,7 +689,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param loc Local.
          */
         public SizeLongTask(String cacheName, boolean async, CachePeekMode[] peekModes, boolean loc) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.loc = loc;
             this.peekModes = peekModes;
         }
@@ -708,7 +713,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param key Key.
          */
         public GetTask(String cacheName, boolean async, K key) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
         }
 
@@ -731,7 +736,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param key Key.
          */
         public GetEntryTask(String cacheName, boolean async, K key) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
         }
 
@@ -750,7 +755,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param async Async.
          */
         public RemoveAllTask(String cacheName, boolean async) {
-            super(cacheName, async);
+            super(cacheName, async, null);
         }
 
         /** {@inheritDoc} */
@@ -779,11 +784,12 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
         /**
          * @param cacheName Cache name.
          * @param async Async.
+         * @param expiryPlc Expiry policy.
          * @param key Key.
          * @param val Value.
          */
-        public PutTask(String cacheName, boolean async, K key, V val) {
-            super(cacheName, async);
+        public PutTask(String cacheName, boolean async, ExpiryPolicy expiryPlc, K key, V val) {
+            super(cacheName, async, expiryPlc);
             this.key = key;
             this.val = val;
         }
@@ -809,7 +815,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param key Key.
          */
         public ContainsKeyTask(String cacheName, boolean async, K key) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
         }
 
@@ -828,7 +834,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param async Async.
          */
         public ClearTask(String cacheName, boolean async) {
-            super(cacheName, async);
+            super(cacheName, async, null);
         }
 
         /** {@inheritDoc} */
@@ -848,7 +854,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param async Async.
          */
         public IteratorTask(String cacheName, boolean async) {
-            super(cacheName, async);
+            super(cacheName, async, null);
         }
 
         /** {@inheritDoc} */
@@ -879,7 +885,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param val Value.
          */
         public ReplaceTask(String cacheName, boolean async, K key, V val) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
             this.val = val;
         }
@@ -899,7 +905,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param async Async.
          */
         public GetNameTask(String cacheName, boolean async) {
-            super(cacheName, async);
+            super(cacheName, async, null);
         }
 
         /** {@inheritDoc} */
@@ -921,7 +927,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param key Key.
          */
         public RemoveTask(String cacheName, boolean async, K key) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
         }
 
@@ -944,7 +950,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param map Map.
          */
         public PutAllTask(String cacheName, boolean async, Map<? extends K, ? extends V> map) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.map = map;
         }
 
@@ -969,7 +975,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param keys Keys.
          */
         public RemoveAllKeysTask(String cacheName, boolean async, Set<? extends K> keys) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.keys = keys;
         }
 
@@ -994,7 +1000,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param keys Keys.
          */
         public GetAllTask(String cacheName, boolean async, Set<? extends K> keys) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.keys = keys;
         }
 
@@ -1017,7 +1023,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param keys Keys.
          */
         public GetEntriesTask(String cacheName, boolean async, Set<? extends K> keys) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.keys = keys;
         }
 
@@ -1040,7 +1046,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param keys Keys.
          */
         public GetAllOutTxTask(String cacheName, boolean async, Set<? extends K> keys) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.keys = keys;
         }
 
@@ -1063,7 +1069,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param keys Keys.
          */
         public ContainsKeysTask(String cacheName, boolean async, Set<? extends K> keys) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.keys = keys;
         }
 
@@ -1090,7 +1096,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param val Value.
          */
         public GetAndPutTask(String cacheName, boolean async, K key, V val) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
             this.val = val;
         }
@@ -1118,7 +1124,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param val Value.
          */
         public PutIfAbsentTask(String cacheName, boolean async, K key, V val) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
             this.val = val;
         }
@@ -1146,7 +1152,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param oldVal Old value.
          */
         public RemoveIfExistsTask(String cacheName, boolean async, K key, V oldVal) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
             this.oldVal = oldVal;
         }
@@ -1170,7 +1176,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param key Key.
          */
         public GetAndRemoveTask(String cacheName, boolean async, K key) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
         }
 
@@ -1201,7 +1207,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param newVal New value.
          */
         public ReplaceIfExistsTask(String cacheName, boolean async, K key, V oldVal, V newVal) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
             this.oldVal = oldVal;
             this.newVal = newVal;
@@ -1230,7 +1236,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param val Value.
          */
         public GetAndReplaceTask(String cacheName, boolean async, K key, V val) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
             this.val = val;
         }
@@ -1257,7 +1263,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param key Key.
          */
         public ClearKeyTask(String cacheName, boolean async, boolean loc, K key) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.key = key;
             this.loc = loc;
         }
@@ -1289,7 +1295,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param keys Keys.
          */
         public ClearAllKeys(String cacheName, boolean async, boolean loc, Set<? extends K> keys) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.keys = keys;
             this.loc = loc;
         }
@@ -1327,7 +1333,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          */
         public InvokeTask(String cacheName, boolean async, K key, EntryProcessor<K, V, R> processor,
             Object[] args) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.args = args;
             this.key = key;
             this.processor = processor;
@@ -1361,7 +1367,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          */
         public InvokeAllTask(String cacheName, boolean async, Set<? extends K> keys,
             EntryProcessor<K, V, T> processor, Object[] args) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.args = args;
             this.keys = keys;
             this.processor = processor;
@@ -1382,7 +1388,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param async Async.
          */
         public CloseTask(String cacheName, boolean async) {
-            super(cacheName, async);
+            super(cacheName, async, null);
         }
 
         /** {@inheritDoc} */
@@ -1402,7 +1408,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param async Async.
          */
         public DestroyTask(String cacheName, boolean async) {
-            super(cacheName, async);
+            super(cacheName, async, null);
         }
 
         /** {@inheritDoc} */
@@ -1422,7 +1428,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param async Async.
          */
         public IsClosedTask(String cacheName, boolean async) {
-            super(cacheName, async);
+            super(cacheName, async, null);
         }
 
         /** {@inheritDoc} */
@@ -1444,7 +1450,7 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
          * @param clazz Clazz.
          */
         public UnwrapTask(String cacheName, boolean async, Class<R> clazz) {
-            super(cacheName, async);
+            super(cacheName, async, null);
             this.clazz = clazz;
         }
 
@@ -1468,21 +1474,28 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
         /** Async. */
         protected final boolean async;
 
+        /** Expiry policy. */
+        protected final ExpiryPolicy expiryPlc;
+
         /**
          * @param cacheName Cache name.
          * @param async Async.
+         * @param expiryPlc Optional expiry policy.
          */
-        public CacheTaskAdapter(String cacheName, boolean async) {
+        public CacheTaskAdapter(String cacheName, boolean async, ExpiryPolicy expiryPlc) {
             this.async = async;
             this.cacheName = cacheName;
+            this.expiryPlc = expiryPlc;
         }
 
         /**
-         * Returns cache instance.
+         * @return Cache instance.
          */
         protected IgniteCache<K, V> cache() {
             IgniteCache<K, V> cache = ignite.cache(cacheName);
 
+            cache = expiryPlc != null ? cache.withExpiryPolicy(expiryPlc) : cache;
+
             return async ? cache.withAsync() : cache;
         }
     }


[09/50] [abbrv] ignite git commit: Updated classnames.properties to run Ignite from IDE.

Posted by vo...@apache.org.
Updated classnames.properties to run Ignite from IDE.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 920005d71413e4008ab1842194d2ee35cbeac544
Parents: d2524eb
Author: Alexey Kuznetsov <ak...@apache.org>
Authored: Wed Jul 6 20:08:32 2016 +0700
Committer: Alexey Kuznetsov <ak...@apache.org>
Committed: Wed Jul 6 20:08:32 2016 +0700

----------------------------------------------------------------------
 .../resources/META-INF/classnames.properties    | 78 ++++++++++++++++----
 1 file changed, 64 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/920005d7/modules/core/src/main/resources/META-INF/classnames.properties
----------------------------------------------------------------------
diff --git a/modules/core/src/main/resources/META-INF/classnames.properties b/modules/core/src/main/resources/META-INF/classnames.properties
index 0dd6a59..5a06141 100644
--- a/modules/core/src/main/resources/META-INF/classnames.properties
+++ b/modules/core/src/main/resources/META-INF/classnames.properties
@@ -221,7 +221,7 @@ org.apache.ignite.internal.IgniteFutureTimeoutCheckedException
 org.apache.ignite.internal.IgniteInterruptedCheckedException
 org.apache.ignite.internal.IgniteKernal
 org.apache.ignite.internal.IgniteKernal$1
-org.apache.ignite.internal.IgniteKernal$4
+org.apache.ignite.internal.IgniteKernal$5
 org.apache.ignite.internal.IgniteMessagingImpl
 org.apache.ignite.internal.IgniteSchedulerImpl
 org.apache.ignite.internal.IgniteServicesImpl
@@ -340,7 +340,9 @@ org.apache.ignite.internal.processors.cache.CacheOperationContext
 org.apache.ignite.internal.processors.cache.CachePartialUpdateCheckedException
 org.apache.ignite.internal.processors.cache.CacheStorePartialUpdateException
 org.apache.ignite.internal.processors.cache.CacheType
+org.apache.ignite.internal.processors.cache.CacheWeakQueryIteratorsHolder$WeakQueryCloseableIterator
 org.apache.ignite.internal.processors.cache.CacheWeakQueryIteratorsHolder$WeakQueryFutureIterator
+org.apache.ignite.internal.processors.cache.CacheWeakQueryIteratorsHolder$WeakReferenceCloseableIterator
 org.apache.ignite.internal.processors.cache.DynamicCacheChangeBatch
 org.apache.ignite.internal.processors.cache.DynamicCacheChangeRequest
 org.apache.ignite.internal.processors.cache.GridCacheAdapter
@@ -349,7 +351,7 @@ org.apache.ignite.internal.processors.cache.GridCacheAdapter$11
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$12
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$13
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$14
-`org.apache.ignite.internal.processors.cache.GridCacheAdapter$15$1
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$15$1
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$16
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$17
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$2
@@ -366,11 +368,13 @@ org.apache.ignite.internal.processors.cache.GridCacheAdapter$65
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$66
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$67
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$68
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$69
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$70
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$71
-org.apache.ignite.internal.processors.cache.GridCacheAdapter$71$1
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$72
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$73
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$73$1
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$74
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$75
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$8
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$9
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$AsyncOpRetryFuture$1
@@ -382,7 +386,9 @@ org.apache.ignite.internal.processors.cache.GridCacheAdapter$GlobalClearKeySetJo
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$GlobalClearKeySetNearJob
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$LoadCacheClosure
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$LoadCacheJob
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$LoadCacheJobV2
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$LoadKeysCallable
+org.apache.ignite.internal.processors.cache.GridCacheAdapter$LoadKeysCallableV2
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$SizeJob
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$SizeLongJob
 org.apache.ignite.internal.processors.cache.GridCacheAdapter$SizeLongTask
@@ -457,12 +463,11 @@ org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$6
 org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$7
 org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$ExchangeFutureSet
 org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$MessageHandler
-org.apache.ignite.internal.processors.cache.GridCacheProcessor$1
+org.apache.ignite.internal.processors.cache.GridCacheProcessor$2
 org.apache.ignite.internal.processors.cache.GridCacheProcessor$3
 org.apache.ignite.internal.processors.cache.GridCacheProcessor$4
 org.apache.ignite.internal.processors.cache.GridCacheProcessor$5
-org.apache.ignite.internal.processors.cache.GridCacheProcessor$6
-org.apache.ignite.internal.processors.cache.GridCacheProcessor$8
+org.apache.ignite.internal.processors.cache.GridCacheProcessor$7
 org.apache.ignite.internal.processors.cache.GridCacheProcessor$LocalAffinityFunction
 org.apache.ignite.internal.processors.cache.GridCacheProxyImpl
 org.apache.ignite.internal.processors.cache.GridCacheReturn
@@ -514,6 +519,7 @@ org.apache.ignite.internal.processors.cache.IgniteCacheProxy
 org.apache.ignite.internal.processors.cache.IgniteCacheProxy$1
 org.apache.ignite.internal.processors.cache.IgniteCacheProxy$10
 org.apache.ignite.internal.processors.cache.IgniteCacheProxy$2
+org.apache.ignite.internal.processors.cache.IgniteCacheProxy$2$1
 org.apache.ignite.internal.processors.cache.IgniteCacheProxy$3
 org.apache.ignite.internal.processors.cache.IgniteCacheProxy$4
 org.apache.ignite.internal.processors.cache.IgniteCacheProxy$5
@@ -670,6 +676,7 @@ org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtCol
 org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtColocatedLockFuture$2
 org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtColocatedLockFuture$3
 org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtColocatedLockFuture$4
+org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtColocatedLockFuture$LockTimeoutObject$1
 org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtColocatedLockFuture$MiniFuture$1
 org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtForceKeysFuture$1
 org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtForceKeysRequest
@@ -772,6 +779,7 @@ org.apache.ignite.internal.processors.cache.distributed.near.GridNearUnlockReque
 org.apache.ignite.internal.processors.cache.dr.GridCacheDrExpirationInfo
 org.apache.ignite.internal.processors.cache.dr.GridCacheDrInfo
 org.apache.ignite.internal.processors.cache.local.GridLocalCache
+org.apache.ignite.internal.processors.cache.local.GridLocalLockFuture$LockTimeoutObject$1
 org.apache.ignite.internal.processors.cache.local.atomic.GridLocalAtomicCache
 org.apache.ignite.internal.processors.cache.local.atomic.GridLocalAtomicCache$10
 org.apache.ignite.internal.processors.cache.local.atomic.GridLocalAtomicCache$4
@@ -786,21 +794,25 @@ org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManag
 org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager$4
 org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager$5
 org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager$6
+org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager$7
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryAdapter$1
+org.apache.ignite.internal.processors.cache.query.GridCacheQueryAdapter$ScanQueryFallbackClosableIterator
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryFutureAdapter$1
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryFutureAdapter$2
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$1$1
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$1$2
-org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$10
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$11
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$12
-org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$13$1
+org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$13
+org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$14
+org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$15$1
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$2
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$3
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$4
+org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$5
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$6
-org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$7
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$8
+org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$9
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$CacheSqlIndexMetadata
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$CacheSqlMetadata
 org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$CachedResult$QueueIterator
@@ -825,15 +837,14 @@ org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQuer
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryEvent
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryHandler
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryHandler$1$1
-org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryHandler$1$2
-org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryHandler$2
-org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryHandler$3
+org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryHandler$ContinuousQueryAsyncClosure$1
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryHandler$DeployableObject
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryHandlerV2
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryManager$1
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryManager$2
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryManager$3
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryManager$4
+org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryManager$CacheEntryEventImpl
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryManager$JCacheQuery$1
 org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryManager$JCacheQueryRemoteFilter
 org.apache.ignite.internal.processors.cache.query.jdbc.GridCacheQueryJdbcMetadataTask
@@ -904,7 +915,12 @@ org.apache.ignite.internal.processors.cache.transactions.IgniteTxMap$1$1
 org.apache.ignite.internal.processors.cache.transactions.TransactionMetricsAdapter
 org.apache.ignite.internal.processors.cache.transactions.TransactionProxyImpl
 org.apache.ignite.internal.processors.cache.transactions.TransactionProxyImpl$1
+org.apache.ignite.internal.processors.cache.transactions.TxDeadlockDetection$UniqueDeque
 org.apache.ignite.internal.processors.cache.transactions.TxEntryValueHolder
+org.apache.ignite.internal.processors.cache.transactions.TxLock
+org.apache.ignite.internal.processors.cache.transactions.TxLockList
+org.apache.ignite.internal.processors.cache.transactions.TxLocksRequest
+org.apache.ignite.internal.processors.cache.transactions.TxLocksResponse
 org.apache.ignite.internal.processors.cache.version.GridCacheRawVersionedEntry
 org.apache.ignite.internal.processors.cache.version.GridCacheVersion
 org.apache.ignite.internal.processors.cache.version.GridCacheVersionConflictContext$State
@@ -1061,7 +1077,7 @@ org.apache.ignite.internal.processors.igfs.IgfsCommunicationMessage
 org.apache.ignite.internal.processors.igfs.IgfsDataManager$3
 org.apache.ignite.internal.processors.igfs.IgfsDataManager$4
 org.apache.ignite.internal.processors.igfs.IgfsDataManager$5$1
-org.apache.ignite.internal.processors.igfs.IgfsDataManager$7
+org.apache.ignite.internal.processors.igfs.IgfsDataManager$6
 org.apache.ignite.internal.processors.igfs.IgfsDataManager$UpdateProcessor
 org.apache.ignite.internal.processors.igfs.IgfsDeleteMessage
 org.apache.ignite.internal.processors.igfs.IgfsDirectoryInfo
@@ -1088,6 +1104,7 @@ org.apache.ignite.internal.processors.igfs.IgfsListingEntry
 org.apache.ignite.internal.processors.igfs.IgfsMetaManager$2
 org.apache.ignite.internal.processors.igfs.IgfsMetaManager$3
 org.apache.ignite.internal.processors.igfs.IgfsMetricsAdapter
+org.apache.ignite.internal.processors.igfs.IgfsNodePredicate
 org.apache.ignite.internal.processors.igfs.IgfsPaths
 org.apache.ignite.internal.processors.igfs.IgfsProcessor$1
 org.apache.ignite.internal.processors.igfs.IgfsProcessor$2
@@ -1097,9 +1114,26 @@ org.apache.ignite.internal.processors.igfs.IgfsServerManager$1
 org.apache.ignite.internal.processors.igfs.IgfsStatus
 org.apache.ignite.internal.processors.igfs.IgfsSyncMessage
 org.apache.ignite.internal.processors.igfs.IgfsTaskArgsImpl
+org.apache.ignite.internal.processors.igfs.client.IgfsClientAbstractCallable
+org.apache.ignite.internal.processors.igfs.client.IgfsClientAffinityCallable
+org.apache.ignite.internal.processors.igfs.client.IgfsClientDeleteCallable
+org.apache.ignite.internal.processors.igfs.client.IgfsClientExistsCallable
+org.apache.ignite.internal.processors.igfs.client.IgfsClientInfoCallable
+org.apache.ignite.internal.processors.igfs.client.IgfsClientListFilesCallable
+org.apache.ignite.internal.processors.igfs.client.IgfsClientListPathsCallable
+org.apache.ignite.internal.processors.igfs.client.IgfsClientMkdirsCallable
+org.apache.ignite.internal.processors.igfs.client.IgfsClientRenameCallable
+org.apache.ignite.internal.processors.igfs.client.IgfsClientSetTimesCallable
+org.apache.ignite.internal.processors.igfs.client.IgfsClientSizeCallable
+org.apache.ignite.internal.processors.igfs.client.IgfsClientSummaryCallable
+org.apache.ignite.internal.processors.igfs.client.IgfsClientUpdateCallable
+org.apache.ignite.internal.processors.igfs.client.meta.IgfsClientMetaIdsForPathCallable
+org.apache.ignite.internal.processors.igfs.client.meta.IgfsClientMetaInfoForPathCallable
+org.apache.ignite.internal.processors.igfs.data.IgfsDataPutProcessor
 org.apache.ignite.internal.processors.igfs.meta.IgfsMetaDirectoryCreateProcessor
 org.apache.ignite.internal.processors.igfs.meta.IgfsMetaDirectoryListingAddProcessor
 org.apache.ignite.internal.processors.igfs.meta.IgfsMetaDirectoryListingRemoveProcessor
+org.apache.ignite.internal.processors.igfs.meta.IgfsMetaDirectoryListingRenameProcessor
 org.apache.ignite.internal.processors.igfs.meta.IgfsMetaDirectoryListingReplaceProcessor
 org.apache.ignite.internal.processors.igfs.meta.IgfsMetaFileCreateProcessor
 org.apache.ignite.internal.processors.igfs.meta.IgfsMetaFileLockProcessor
@@ -1119,6 +1153,7 @@ org.apache.ignite.internal.processors.platform.PlatformAbstractPredicate
 org.apache.ignite.internal.processors.platform.PlatformEventFilterListener
 org.apache.ignite.internal.processors.platform.PlatformException
 org.apache.ignite.internal.processors.platform.PlatformExtendedException
+org.apache.ignite.internal.processors.platform.PlatformJavaObjectFactoryProxy
 org.apache.ignite.internal.processors.platform.PlatformNativeException
 org.apache.ignite.internal.processors.platform.PlatformNoCallbackException
 org.apache.ignite.internal.processors.platform.cache.PlatformCache$1
@@ -1257,6 +1292,7 @@ org.apache.ignite.internal.processors.rest.protocols.tcp.GridMemcachedMessage
 org.apache.ignite.internal.processors.rest.protocols.tcp.GridTcpMemcachedNioListener$1
 org.apache.ignite.internal.processors.rest.protocols.tcp.GridTcpMemcachedNioListener$2
 org.apache.ignite.internal.processors.rest.protocols.tcp.GridTcpRestNioListener$1
+org.apache.ignite.internal.processors.rest.protocols.tcp.GridTcpRestNioListener$1$1
 org.apache.ignite.internal.processors.rest.request.RestQueryRequest$QueryType
 org.apache.ignite.internal.processors.service.GridServiceAssignments
 org.apache.ignite.internal.processors.service.GridServiceAssignmentsKey
@@ -1269,11 +1305,13 @@ org.apache.ignite.internal.processors.service.GridServiceProcessor$ServiceDeploy
 org.apache.ignite.internal.processors.service.GridServiceProcessor$ServiceTopologyCallable
 org.apache.ignite.internal.processors.service.GridServiceProxy
 org.apache.ignite.internal.processors.service.GridServiceProxy$ServiceProxyCallable
+org.apache.ignite.internal.processors.service.LazyServiceConfiguration
 org.apache.ignite.internal.processors.service.ServiceContextImpl
 org.apache.ignite.internal.processors.service.ServiceDescriptorImpl
 org.apache.ignite.internal.processors.task.GridTaskProcessor$1
 org.apache.ignite.internal.processors.task.GridTaskThreadContextKey
 org.apache.ignite.internal.processors.task.GridTaskWorker$3
+org.apache.ignite.internal.processors.task.GridTaskWorker$4
 org.apache.ignite.internal.processors.task.GridTaskWorker$State
 org.apache.ignite.internal.transactions.IgniteTxHeuristicCheckedException
 org.apache.ignite.internal.transactions.IgniteTxOptimisticCheckedException
@@ -1558,6 +1596,8 @@ org.apache.ignite.internal.visor.VisorOneNodeTask
 org.apache.ignite.internal.visor.VisorTaskArgument
 org.apache.ignite.internal.visor.cache.VisorCache
 org.apache.ignite.internal.visor.cache.VisorCacheAffinityConfiguration
+org.apache.ignite.internal.visor.cache.VisorCacheAffinityNodeTask
+org.apache.ignite.internal.visor.cache.VisorCacheAffinityNodeTask$VisorCacheAffinityNodeJob
 org.apache.ignite.internal.visor.cache.VisorCacheAggregatedMetrics
 org.apache.ignite.internal.visor.cache.VisorCacheClearTask
 org.apache.ignite.internal.visor.cache.VisorCacheClearTask$VisorCacheClearCallable
@@ -1580,6 +1620,10 @@ org.apache.ignite.internal.visor.cache.VisorCacheMetricsV2
 org.apache.ignite.internal.visor.cache.VisorCacheNearConfiguration
 org.apache.ignite.internal.visor.cache.VisorCacheNodesTask
 org.apache.ignite.internal.visor.cache.VisorCacheNodesTask$VisorCacheNodesJob
+org.apache.ignite.internal.visor.cache.VisorCachePartition
+org.apache.ignite.internal.visor.cache.VisorCachePartitions
+org.apache.ignite.internal.visor.cache.VisorCachePartitionsTask
+org.apache.ignite.internal.visor.cache.VisorCachePartitionsTask$VisorCachePartitionsJob
 org.apache.ignite.internal.visor.cache.VisorCacheQueryConfiguration
 org.apache.ignite.internal.visor.cache.VisorCacheQueryConfigurationV2
 org.apache.ignite.internal.visor.cache.VisorCacheQueryMetrics
@@ -1601,12 +1645,15 @@ org.apache.ignite.internal.visor.cache.VisorCacheTypeFieldMetadata
 org.apache.ignite.internal.visor.cache.VisorCacheTypeMetadata
 org.apache.ignite.internal.visor.cache.VisorCacheV2
 org.apache.ignite.internal.visor.cache.VisorCacheV3
+org.apache.ignite.internal.visor.cache.VisorCacheV4
 org.apache.ignite.internal.visor.compute.VisorComputeCancelSessionsTask
 org.apache.ignite.internal.visor.compute.VisorComputeCancelSessionsTask$VisorComputeCancelSessionsJob
 org.apache.ignite.internal.visor.compute.VisorComputeResetMetricsTask
 org.apache.ignite.internal.visor.compute.VisorComputeResetMetricsTask$VisorComputeResetMetricsJob
 org.apache.ignite.internal.visor.compute.VisorComputeToggleMonitoringTask
 org.apache.ignite.internal.visor.compute.VisorComputeToggleMonitoringTask$VisorComputeToggleMonitoringJob
+org.apache.ignite.internal.visor.compute.VisorGatewayTask
+org.apache.ignite.internal.visor.compute.VisorGatewayTask$VisorGatewayJob
 org.apache.ignite.internal.visor.debug.VisorThreadDumpTask
 org.apache.ignite.internal.visor.debug.VisorThreadDumpTask$VisorDumpThreadJob
 org.apache.ignite.internal.visor.debug.VisorThreadInfo
@@ -1699,6 +1746,8 @@ org.apache.ignite.internal.visor.util.VisorClusterGroupEmptyException
 org.apache.ignite.internal.visor.util.VisorEventMapper
 org.apache.ignite.internal.visor.util.VisorExceptionWrapper
 org.apache.ignite.internal.visor.util.VisorTaskUtils$4
+org.apache.ignite.internal.websession.WebSessionAttributeProcessor
+org.apache.ignite.internal.websession.WebSessionEntity
 org.apache.ignite.lang.IgniteBiClosure
 org.apache.ignite.lang.IgniteBiInClosure
 org.apache.ignite.lang.IgniteBiPredicate
@@ -1803,6 +1852,7 @@ org.apache.ignite.stream.StreamTransformer$1
 org.apache.ignite.stream.StreamVisitor
 org.apache.ignite.stream.StreamVisitor$1
 org.apache.ignite.transactions.TransactionConcurrency
+org.apache.ignite.transactions.TransactionDeadlockException
 org.apache.ignite.transactions.TransactionHeuristicException
 org.apache.ignite.transactions.TransactionIsolation
 org.apache.ignite.transactions.TransactionMetrics


[05/50] [abbrv] ignite git commit: ignite-3336 Added properties IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT, IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT. Refactored cache message logging.

Posted by vo...@apache.org.
ignite-3336 Added properties IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT, IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT. Refactored cache message logging.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 8ed13e84499a2006baf8df22d897509e2d4e3f7e
Parents: 89d722c
Author: sboikov <sb...@gridgain.com>
Authored: Wed Jul 6 10:18:26 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Wed Jul 6 10:18:26 2016 +0300

----------------------------------------------------------------------
 .../apache/ignite/IgniteSystemProperties.java   |   8 +-
 .../apache/ignite/internal/IgniteKernal.java    |  21 ++
 .../processors/cache/GridCacheAdapter.java      |   4 +
 .../processors/cache/GridCacheIoManager.java    | 150 +++++++++-
 .../processors/cache/GridCacheMessage.java      |   9 +
 .../GridCachePartitionExchangeManager.java      | 147 +++++++++-
 .../cache/GridCacheSharedContext.java           |  68 +++++
 .../processors/cache/GridCacheUtils.java        |  21 ++
 .../distributed/GridCacheTxRecoveryFuture.java  |  70 ++++-
 .../distributed/GridCacheTxRecoveryRequest.java |   8 +
 .../GridCacheTxRecoveryResponse.java            |   8 +
 .../distributed/GridDistributedLockRequest.java |   6 +
 .../GridDistributedLockResponse.java            |   6 +
 .../GridDistributedTxFinishRequest.java         |   7 +-
 .../GridDistributedTxFinishResponse.java        |   8 +
 .../GridDistributedTxPrepareRequest.java        |   6 +
 .../GridDistributedTxPrepareResponse.java       |   9 +-
 .../GridDistributedUnlockRequest.java           |   6 +
 .../distributed/dht/GridDhtLockFuture.java      |  52 ++--
 .../dht/GridDhtTransactionalCacheAdapter.java   |  77 ++++-
 .../distributed/dht/GridDhtTxFinishFuture.java  |  92 +++++-
 .../cache/distributed/dht/GridDhtTxLocal.java   |  27 +-
 .../distributed/dht/GridDhtTxPrepareFuture.java | 124 +++++++-
 .../dht/atomic/GridDhtAtomicCache.java          | 137 ++++++---
 .../GridDhtAtomicDeferredUpdateResponse.java    |   7 +
 .../dht/atomic/GridDhtAtomicUpdateFuture.java   |  47 +++-
 .../dht/atomic/GridDhtAtomicUpdateRequest.java  |   6 +
 .../dht/atomic/GridDhtAtomicUpdateResponse.java |   6 +
 .../dht/atomic/GridNearAtomicUpdateFuture.java  |  54 +++-
 .../dht/atomic/GridNearAtomicUpdateRequest.java |   6 +
 .../atomic/GridNearAtomicUpdateResponse.java    |   6 +
 .../dht/colocated/GridDhtColocatedCache.java    |  10 +
 .../colocated/GridDhtColocatedLockFuture.java   |  71 +++--
 .../GridDhtPartitionsExchangeFuture.java        |  26 +-
 .../near/GridNearOptimisticTxPrepareFuture.java |  32 +++
 .../GridNearPessimisticTxPrepareFuture.java     |  34 ++-
 .../near/GridNearTxFinishFuture.java            |  97 ++++++-
 .../near/GridNearTxPrepareFutureAdapter.java    |   7 +-
 .../cache/transactions/IgniteTxHandler.java     | 281 ++++++++++++++-----
 modules/core/src/test/config/log4j-test.xml     |   6 +
 40 files changed, 1495 insertions(+), 272 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java b/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
index 50d60e8..254c60f 100644
--- a/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
+++ b/modules/core/src/main/java/org/apache/ignite/IgniteSystemProperties.java
@@ -375,6 +375,12 @@ public final class IgniteSystemProperties {
     /** Number of times pending cache objects will be dumped to the log in case of partition exchange timeout. */
     public static final String IGNITE_DUMP_PENDING_OBJECTS_THRESHOLD = "IGNITE_DUMP_PENDING_OBJECTS_THRESHOLD";
 
+    /** If this property is set to {@code true} then Ignite will log thread dump in case of partition exchange timeout. */
+    public static final String IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT = "IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT";
+
+    /** Cache operations that take more time than value of this property will be output to log. Set to {@code 0} to disable. */
+    public static final String IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT = "IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT";
+
     /** JDBC driver cursor remove delay. */
     public static final String IGNITE_JDBC_DRIVER_CURSOR_REMOVE_DELAY = "IGNITE_JDBC_DRIVER_CURSOR_RMV_DELAY";
 
@@ -387,7 +393,7 @@ public final class IgniteSystemProperties {
     /**
      * Manages {@link OptimizedMarshaller} behavior of {@code serialVersionUID} computation for
      * {@link Serializable} classes.
-     * */
+     */
     public static final String IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID =
         "IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID";
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java b/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
index 9d42598..9b26276 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java
@@ -300,6 +300,10 @@ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable {
     @GridToStringExclude
     private GridTimeoutProcessor.CancelableTask metricsLogTask;
 
+    /** */
+    @GridToStringExclude
+    private GridTimeoutProcessor.CancelableTask longOpDumpTask;
+
     /** Indicate error on grid stop. */
     @GridToStringExclude
     private boolean errOnStop;
@@ -1073,6 +1077,20 @@ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable {
             }, metricsLogFreq, metricsLogFreq);
         }
 
+        final long longOpDumpTimeout =
+            IgniteSystemProperties.getLong(IgniteSystemProperties.IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT, 60_000);
+
+        if (longOpDumpTimeout > 0) {
+            longOpDumpTask = ctx.timeout().schedule(new Runnable() {
+                @Override public void run() {
+                    GridKernalContext ctx = IgniteKernal.this.ctx;
+
+                    if (ctx != null)
+                        ctx.cache().context().exchange().dumpLongRunningOperations(longOpDumpTimeout);
+                }
+            }, longOpDumpTimeout, longOpDumpTimeout);
+        }
+
         ctx.performance().logSuggestions(log, gridName);
 
         U.quietAndInfo(log, "To start Console Management & Monitoring run ignitevisorcmd.{sh|bat}");
@@ -1883,6 +1901,9 @@ public class IgniteKernal implements IgniteEx, IgniteMXBean, Externalizable {
             if (metricsLogTask != null)
                 metricsLogTask.close();
 
+            if (longOpDumpTask != null)
+                longOpDumpTask.close();
+
             boolean interrupted = false;
 
             while (true) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
index 1a55fe3..028f516 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
@@ -266,6 +266,9 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
     /** Logger. */
     protected IgniteLogger log;
 
+    /** Logger. */
+    protected IgniteLogger txLockMsgLog;
+
     /** Affinity impl. */
     private Affinity<K> aff;
 
@@ -328,6 +331,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
         this.map = map;
 
         log = ctx.logger(getClass());
+        txLockMsgLog = ctx.shared().txLockMessageLogger();
 
         metrics = new CacheMetricsImpl(ctx);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheIoManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheIoManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheIoManager.java
index 0aa8b1b..17718ec 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheIoManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheIoManager.java
@@ -38,6 +38,8 @@ import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.processors.cache.distributed.dht.CacheGetFuture;
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtLockRequest;
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtLockResponse;
+import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxFinishRequest;
+import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxFinishResponse;
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareRequest;
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTxPrepareResponse;
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridPartitionedSingleGetFuture;
@@ -53,10 +55,13 @@ import org.apache.ignite.internal.processors.cache.distributed.near.GridNearLock
 import org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockResponse;
 import org.apache.ignite.internal.processors.cache.distributed.near.GridNearSingleGetRequest;
 import org.apache.ignite.internal.processors.cache.distributed.near.GridNearSingleGetResponse;
+import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxFinishRequest;
+import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxFinishResponse;
 import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareRequest;
 import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareResponse;
 import org.apache.ignite.internal.processors.cache.query.GridCacheQueryRequest;
 import org.apache.ignite.internal.processors.cache.query.GridCacheQueryResponse;
+import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.F0;
 import org.apache.ignite.internal.util.GridLeanSet;
 import org.apache.ignite.internal.util.GridSpinReadWriteLock;
@@ -112,7 +117,7 @@ public class GridCacheIoManager extends GridCacheSharedManagerAdapter {
 
     /** Message listener. */
     private GridMessageListener lsnr = new GridMessageListener() {
-        @Override public void onMessage(final UUID nodeId, Object msg) {
+        @Override public void onMessage(final UUID nodeId, final Object msg) {
             if (log.isDebugEnabled())
                 log.debug("Received unordered cache communication message [nodeId=" + nodeId +
                     ", locId=" + cctx.localNodeId() + ", msg=" + msg + ']');
@@ -138,9 +143,19 @@ public class GridCacheIoManager extends GridCacheSharedManagerAdapter {
                 AffinityTopologyVersion rmtAffVer = cacheMsg.topologyVersion();
 
                 if (locAffVer.compareTo(rmtAffVer) < 0) {
-                    if (log.isDebugEnabled())
-                        log.debug("Received message has higher affinity topology version [msg=" + msg +
-                            ", locTopVer=" + locAffVer + ", rmtTopVer=" + rmtAffVer + ']');
+                    IgniteLogger log = cacheMsg.messageLogger(cctx);
+
+                    if (log.isDebugEnabled()) {
+                        StringBuilder msg0 = new StringBuilder("Received message has higher affinity topology version [");
+
+                        appendMessageInfo(cacheMsg, nodeId, msg0);
+
+                        msg0.append(", locTopVer=").append(locAffVer).
+                            append(", rmtTopVer=").append(rmtAffVer).
+                            append(']');
+
+                        log.debug(msg0.toString());
+                    }
 
                     fut = cctx.exchange().affinityReadyFuture(rmtAffVer);
                 }
@@ -151,6 +166,17 @@ public class GridCacheIoManager extends GridCacheSharedManagerAdapter {
                     @Override public void apply(IgniteInternalFuture<?> t) {
                         cctx.kernalContext().closure().runLocalSafe(new Runnable() {
                             @Override public void run() {
+                                IgniteLogger log = cacheMsg.messageLogger(cctx);
+
+                                if (log.isDebugEnabled()) {
+                                    StringBuilder msg0 = new StringBuilder("Process cache message after wait for " +
+                                        "affinity topology version [");
+
+                                    appendMessageInfo(cacheMsg, nodeId, msg0).append(']');
+
+                                    log.debug(msg0.toString());
+                                }
+
                                 handleMessage(nodeId, cacheMsg);
                             }
                         });
@@ -185,18 +211,23 @@ public class GridCacheIoManager extends GridCacheSharedManagerAdapter {
             c = clsHandlers.get(new ListenerKey(cacheMsg.cacheId(), cacheMsg.getClass()));
 
         if (c == null) {
+            IgniteLogger log = cacheMsg.messageLogger(cctx);
+
+            StringBuilder msg0 = new StringBuilder("Received message without registered handler (will ignore) [");
+
+            appendMessageInfo(cacheMsg, nodeId, msg0);
+
+            msg0.append(", locTopVer=").append(cctx.exchange().readyAffinityVersion()).
+                append(", msgTopVer=").append(cacheMsg.topologyVersion()).
+                append(", cacheDesc=").append(cctx.cache().cacheDescriptor(cacheMsg.cacheId())).
+                append(']');
+
             if (cctx.kernalContext().isStopping()) {
                 if (log.isDebugEnabled())
-                    log.debug("Received message without registered handler (will ignore) [msg=" + cacheMsg +
-                        ", nodeId=" + nodeId + ']');
-            }
-            else {
-                U.warn(log, "Received message without registered handler (will ignore) [msg=" + cacheMsg +
-                    ", nodeId=" + nodeId +
-                    ", locTopVer=" + cctx.exchange().readyAffinityVersion() +
-                    ", msgTopVer=" + cacheMsg.topologyVersion() +
-                    ", cacheDesc=" + cctx.cache().cacheDescriptor(cacheMsg.cacheId()) + ']');
+                    log.debug(msg0.toString());
             }
+            else
+                U.warn(log, msg0.toString());
 
             return;
         }
@@ -312,6 +343,99 @@ public class GridCacheIoManager extends GridCacheSharedManagerAdapter {
         }
     }
 
+
+    /**
+     * @param cacheMsg Cache message.
+     * @param nodeId Node ID.
+     * @param builder Message builder.
+     * @return Message builder.
+     */
+    private StringBuilder appendMessageInfo(GridCacheMessage cacheMsg, UUID nodeId, StringBuilder builder) {
+        if (txId(cacheMsg) != null) {
+            builder.append("txId=").append(txId(cacheMsg)).
+                append(", dhtTxId=").append(dhtTxId(cacheMsg)).
+                append(", msg=").append(cacheMsg);
+        }
+        else if (atomicFututeId(cacheMsg) != null) {
+            builder.append("futId=").append(atomicFututeId(cacheMsg)).
+                append(", writeVer=").append(atomicWriteVersion(cacheMsg)).
+                append(", msg=").append(cacheMsg);
+        }
+        else
+            builder.append("msg=").append(cacheMsg);
+
+        builder.append(", node=").append(nodeId);
+
+        return builder;
+    }
+
+    /**
+     * @param cacheMsg Cache message.
+     * @return Transaction ID if applicable for message.
+     */
+    @Nullable private GridCacheVersion txId(GridCacheMessage cacheMsg) {
+        if (cacheMsg instanceof GridDhtTxPrepareRequest)
+            return ((GridDhtTxPrepareRequest)cacheMsg).nearXidVersion();
+        else if (cacheMsg instanceof GridNearTxPrepareRequest)
+            return ((GridNearTxPrepareRequest)cacheMsg).version();
+        else if (cacheMsg instanceof GridNearTxPrepareResponse)
+            return ((GridNearTxPrepareResponse)cacheMsg).version();
+        else if (cacheMsg instanceof GridNearTxFinishRequest)
+            return ((GridNearTxFinishRequest)cacheMsg).version();
+        else if (cacheMsg instanceof GridNearTxFinishResponse)
+            return ((GridNearTxFinishResponse)cacheMsg).xid();
+
+        return null;
+    }
+
+    /**
+     * @param cacheMsg Cache message.
+     * @return Transaction ID if applicable for message.
+     */
+    @Nullable private GridCacheVersion dhtTxId(GridCacheMessage cacheMsg) {
+        if (cacheMsg instanceof GridDhtTxPrepareRequest)
+            return ((GridDhtTxPrepareRequest)cacheMsg).version();
+        else if (cacheMsg instanceof GridDhtTxPrepareResponse)
+            return ((GridDhtTxPrepareResponse)cacheMsg).version();
+        else if (cacheMsg instanceof GridDhtTxFinishRequest)
+            return ((GridDhtTxFinishRequest)cacheMsg).version();
+        else if (cacheMsg instanceof GridDhtTxFinishResponse)
+            return ((GridDhtTxFinishResponse)cacheMsg).xid();
+
+        return null;
+    }
+
+    /**
+     * @param cacheMsg Cache message.
+     * @return Atomic future ID if applicable for message.
+     */
+    @Nullable private GridCacheVersion atomicFututeId(GridCacheMessage cacheMsg) {
+        if (cacheMsg instanceof GridNearAtomicUpdateRequest)
+            return ((GridNearAtomicUpdateRequest)cacheMsg).futureVersion();
+        else if (cacheMsg instanceof GridNearAtomicUpdateResponse)
+            return ((GridNearAtomicUpdateResponse) cacheMsg).futureVersion();
+        else if (cacheMsg instanceof GridDhtAtomicUpdateRequest)
+            return ((GridDhtAtomicUpdateRequest)cacheMsg).futureVersion();
+        else if (cacheMsg instanceof GridDhtAtomicUpdateResponse)
+            return ((GridDhtAtomicUpdateResponse) cacheMsg).futureVersion();
+
+        return null;
+    }
+
+
+    /**
+     * @param cacheMsg Cache message.
+     * @return Atomic future ID if applicable for message.
+     */
+    @Nullable private GridCacheVersion atomicWriteVersion(GridCacheMessage cacheMsg) {
+        if (cacheMsg instanceof GridNearAtomicUpdateRequest)
+            return ((GridNearAtomicUpdateRequest)cacheMsg).updateVersion();
+        else if (cacheMsg instanceof GridDhtAtomicUpdateRequest)
+            return ((GridDhtAtomicUpdateRequest)cacheMsg).writeVersion();
+
+        return null;
+    }
+
     /**
      * Processes failed messages.
      *

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java
index 3c2ff13..f99d2cd 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java
@@ -24,6 +24,7 @@ import java.util.List;
 import java.util.concurrent.atomic.AtomicInteger;
 import javax.cache.processor.EntryProcessor;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.managers.deployment.GridDeployment;
 import org.apache.ignite.internal.managers.deployment.GridDeploymentInfo;
@@ -613,6 +614,14 @@ public abstract class GridCacheMessage implements Message {
         return col;
     }
 
+    /**
+     * @param ctx Context.
+     * @return Logger.
+     */
+    public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.messageLogger();
+    }
+
     /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCachePartitionExchangeManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCachePartitionExchangeManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCachePartitionExchangeManager.java
index 5e91d01..ce1c502 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCachePartitionExchangeManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCachePartitionExchangeManager.java
@@ -17,9 +17,12 @@
 
 package org.apache.ignite.internal.processors.cache;
 
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Comparator;
+import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -32,12 +35,14 @@ import java.util.concurrent.Callable;
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.ConcurrentSkipListMap;
 import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.concurrent.atomic.AtomicReference;
 import java.util.concurrent.locks.ReadWriteLock;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteSystemProperties;
 import org.apache.ignite.cluster.ClusterNode;
 import org.apache.ignite.events.DiscoveryEvent;
 import org.apache.ignite.events.Event;
@@ -89,6 +94,7 @@ import org.jsr166.ConcurrentLinkedDeque8;
 
 import static java.util.concurrent.TimeUnit.MILLISECONDS;
 import static org.apache.ignite.IgniteSystemProperties.IGNITE_PRELOAD_RESEND_TIMEOUT;
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT;
 import static org.apache.ignite.IgniteSystemProperties.getLong;
 import static org.apache.ignite.events.EventType.EVT_CACHE_REBALANCE_STARTED;
 import static org.apache.ignite.events.EventType.EVT_NODE_FAILED;
@@ -158,6 +164,12 @@ public class GridCachePartitionExchangeManager<K, V> extends GridCacheSharedMana
     /** */
     private volatile IgniteCheckedException stopErr;
 
+    /** */
+    private int longRunningOpsDumpCnt;
+
+    /** */
+    private DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
+
     /** Discovery listener. */
     private final GridLocalEventListener discoLsnr = new GridLocalEventListener() {
         @Override public void onEvent(Event evt) {
@@ -1078,9 +1090,9 @@ public class GridCachePartitionExchangeManager<K, V> extends GridCacheSharedMana
     }
 
     /**
-     *
+     * @throws Exception If failed.
      */
-    public void dumpDebugInfo() {
+    public void dumpDebugInfo() throws Exception {
         U.warn(log, "Ready affinity version: " + readyTopVer.get());
 
         U.warn(log, "Last exchange future: " + lastInitializedFut);
@@ -1122,9 +1134,103 @@ public class GridCachePartitionExchangeManager<K, V> extends GridCacheSharedMana
     }
 
     /**
-     *
+     * @param timeout Operation timeout.
      */
-    public void dumpPendingObjects() {
+    public void dumpLongRunningOperations(long timeout) {
+        try {
+            GridDhtPartitionsExchangeFuture lastFut = lastInitializedFut;
+
+            // If exchange is in progress it will dump all hanging operations if any.
+            if (lastFut != null && !lastFut.isDone())
+                return;
+
+            long curTime = U.currentTimeMillis();
+
+            boolean found = false;
+
+            IgniteTxManager tm = cctx.tm();
+
+            if (tm != null) {
+                for (IgniteInternalTx tx : tm.activeTransactions()) {
+                    if (curTime - tx.startTime() > timeout) {
+                        found = true;
+
+                        if (longRunningOpsDumpCnt < GridDhtPartitionsExchangeFuture.DUMP_PENDING_OBJECTS_THRESHOLD) {
+                            U.warn(log, "Found long running transaction [startTime=" + formatTime(tx.startTime()) +
+                                ", curTime=" + formatTime(curTime) + ", tx=" + tx + ']');
+                        }
+                        else
+                            break;
+                    }
+                }
+            }
+
+            GridCacheMvccManager mvcc = cctx.mvcc();
+
+            if (mvcc != null) {
+                for (GridCacheFuture<?> fut : mvcc.activeFutures()) {
+                    if (curTime - fut.startTime() > timeout) {
+                        found = true;
+
+                        if (longRunningOpsDumpCnt < GridDhtPartitionsExchangeFuture.DUMP_PENDING_OBJECTS_THRESHOLD) {
+                            U.warn(log, "Found long running cache future [startTime=" + formatTime(fut.startTime()) +
+                                ", curTime=" + formatTime(curTime) + ", fut=" + fut + ']');
+                        }
+                        else
+                            break;
+                    }
+                }
+
+                for (GridCacheFuture<?> fut : mvcc.atomicFutures()) {
+                    if (curTime - fut.startTime() > timeout) {
+                        found = true;
+
+                        if (longRunningOpsDumpCnt < GridDhtPartitionsExchangeFuture.DUMP_PENDING_OBJECTS_THRESHOLD) {
+                            U.warn(log, "Found long running cache future [startTime=" + formatTime(fut.startTime()) +
+                                ", curTime=" + formatTime(curTime) + ", fut=" + fut + ']');
+                        }
+                        else
+                            break;
+                    }
+                }
+            }
+
+            if (found) {
+                if (longRunningOpsDumpCnt < GridDhtPartitionsExchangeFuture.DUMP_PENDING_OBJECTS_THRESHOLD) {
+                    longRunningOpsDumpCnt++;
+
+                    if (IgniteSystemProperties.getBoolean(IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT, false)) {
+                        U.warn(log, "Found long running cache operations, dump threads.");
+
+                        U.dumpThreads(log);
+                    }
+
+                    U.warn(log, "Found long running cache operations, dump IO statistics.");
+
+                    // Dump IO manager statistics.
+                    cctx.gridIO().dumpStats();
+                }
+            }
+            else
+                longRunningOpsDumpCnt = 0;
+        }
+        catch (Exception e) {
+            U.error(log, "Failed to dump debug information: " + e, e);
+        }
+    }
+
+    /**
+     * @param time Time.
+     * @return Time string.
+     */
+    private String formatTime(long time) {
+        return dateFormat.format(new Date(time));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    private void dumpPendingObjects() throws Exception {
         IgniteTxManager tm = cctx.tm();
 
         if (tm != null) {
@@ -1281,7 +1387,36 @@ public class GridCachePartitionExchangeManager<K, V> extends GridCacheSharedMana
 
                             exchFut.init();
 
-                            exchFut.get();
+                            int dumpedObjects = 0;
+
+                            while (true) {
+                                try {
+                                    exchFut.get(2 * cctx.gridConfig().getNetworkTimeout(), TimeUnit.MILLISECONDS);
+
+                                    break;
+                                }
+                                catch (IgniteFutureTimeoutCheckedException ignored) {
+                                    U.warn(log, "Failed to wait for partition map exchange [" +
+                                        "topVer=" + exchFut.topologyVersion() +
+                                        ", node=" + cctx.localNodeId() + "]. " +
+                                        "Dumping pending objects that might be the cause: ");
+
+                                    if (dumpedObjects < GridDhtPartitionsExchangeFuture.DUMP_PENDING_OBJECTS_THRESHOLD) {
+                                        try {
+                                            dumpDebugInfo();
+                                        }
+                                        catch (Exception e) {
+                                            U.error(log, "Failed to dump debug information: " + e, e);
+                                        }
+
+                                        if (IgniteSystemProperties.getBoolean(IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT, false))
+                                            U.dumpThreads(log);
+
+                                        dumpedObjects++;
+                                    }
+                                }
+                            }
+
 
                             if (log.isDebugEnabled())
                                 log.debug("After waiting for exchange future [exchFut=" + exchFut + ", worker=" +
@@ -1408,7 +1543,7 @@ public class GridCachePartitionExchangeManager<K, V> extends GridCacheSharedMana
 
                         if (marshR != null || !rebalanceQ.isEmpty()) {
                             if (futQ.isEmpty()) {
-                                U.log(log, "Rebalancing required" +
+                                U.log(log, "Rebalancing required " +
                                     "[top=" + exchFut.topologyVersion() + ", evt=" + exchFut.discoveryEvent().name() +
                                     ", node=" + exchFut.discoveryEvent().eventNode().id() + ']');
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSharedContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSharedContext.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSharedContext.java
index 341f610..1130218 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSharedContext.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheSharedContext.java
@@ -51,6 +51,7 @@ import org.apache.ignite.internal.util.future.GridCompoundFuture;
 import org.apache.ignite.internal.util.future.GridFinishedFuture;
 import org.apache.ignite.internal.util.tostring.GridToStringExclude;
 import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.lang.IgniteFuture;
 import org.apache.ignite.marshaller.Marshaller;
 import org.jetbrains.annotations.Nullable;
@@ -104,6 +105,24 @@ public class GridCacheSharedContext<K, V> {
     /** Indicating whether local store keeps primary only. */
     private final boolean locStorePrimaryOnly = IgniteSystemProperties.getBoolean(IGNITE_LOCAL_STORE_KEEPS_PRIMARY_ONLY);
 
+    /** */
+    private final IgniteLogger msgLog;
+
+    /** */
+    private final IgniteLogger atomicMsgLog;
+
+    /** */
+    private final IgniteLogger txPrepareMsgLog;
+
+    /** */
+    private final IgniteLogger txFinishMsgLog;
+
+    /** */
+    private final IgniteLogger txLockMsgLog;
+
+    /** */
+    private final IgniteLogger txRecoveryMsgLog;
+
     /**
      * @param kernalCtx  Context.
      * @param txMgr Transaction manager.
@@ -137,6 +156,55 @@ public class GridCacheSharedContext<K, V> {
         ctxMap = new ConcurrentHashMap<>();
 
         locStoreCnt = new AtomicInteger();
+
+        msgLog = kernalCtx.log(CU.CACHE_MSG_LOG_CATEGORY);
+        atomicMsgLog = kernalCtx.log(CU.ATOMIC_MSG_LOG_CATEGORY);
+        txPrepareMsgLog = kernalCtx.log(CU.TX_MSG_PREPARE_LOG_CATEGORY);
+        txFinishMsgLog = kernalCtx.log(CU.TX_MSG_FINISH_LOG_CATEGORY);
+        txLockMsgLog = kernalCtx.log(CU.TX_MSG_LOCK_LOG_CATEGORY);
+        txRecoveryMsgLog = kernalCtx.log(CU.TX_MSG_RECOVERY_LOG_CATEGORY);
+    }
+
+    /**
+     * @return Logger.
+     */
+    public IgniteLogger messageLogger() {
+        return msgLog;
+    }
+
+    /**
+     * @return Logger.
+     */
+    public IgniteLogger atomicMessageLogger() {
+        return atomicMsgLog;
+    }
+
+    /**
+     * @return Logger.
+     */
+    public IgniteLogger txPrepareMessageLogger() {
+        return txPrepareMsgLog;
+    }
+
+    /**
+     * @return Logger.
+     */
+    public IgniteLogger txFinishMessageLogger() {
+        return txFinishMsgLog;
+    }
+
+    /**
+     * @return Logger.
+     */
+    public IgniteLogger txLockMessageLogger() {
+        return txLockMsgLog;
+    }
+
+    /**
+     * @return Logger.
+     */
+    public IgniteLogger txRecoveryMessageLogger() {
+        return txRecoveryMsgLog;
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java
index 87c4a3a..ba563e6 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java
@@ -128,6 +128,27 @@ public class GridCacheUtils {
     /** Marshaller system cache name. */
     public static final String MARSH_CACHE_NAME = "ignite-marshaller-sys-cache";
 
+    /** */
+    public static final String CACHE_MSG_LOG_CATEGORY = "org.apache.ignite.cache.msg";
+
+    /** */
+    public static final String ATOMIC_MSG_LOG_CATEGORY = CACHE_MSG_LOG_CATEGORY + ".atomic";
+
+    /** */
+    public static final String TX_MSG_LOG_CATEGORY = CACHE_MSG_LOG_CATEGORY + ".tx";
+
+    /** */
+    public static final String TX_MSG_PREPARE_LOG_CATEGORY = TX_MSG_LOG_CATEGORY + ".prepare";
+
+    /** */
+    public static final String TX_MSG_FINISH_LOG_CATEGORY = TX_MSG_LOG_CATEGORY + ".finish";
+
+    /** */
+    public static final String TX_MSG_LOCK_LOG_CATEGORY = TX_MSG_LOG_CATEGORY + ".lock";
+
+    /** */
+    public static final String TX_MSG_RECOVERY_LOG_CATEGORY = TX_MSG_LOG_CATEGORY + ".recovery";
+
     /** Default mask name. */
     private static final String DEFAULT_MASK_NAME = "<default>";
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryFuture.java
index 1648de0..4fd45b2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryFuture.java
@@ -54,6 +54,9 @@ public class GridCacheTxRecoveryFuture extends GridCompoundIdentityFuture<Boolea
     /** Logger. */
     private static IgniteLogger log;
 
+    /** Logger. */
+    private static IgniteLogger msgLog;
+
     /** Trackable flag. */
     private boolean trackable = true;
 
@@ -97,8 +100,10 @@ public class GridCacheTxRecoveryFuture extends GridCompoundIdentityFuture<Boolea
         this.txNodes = txNodes;
         this.failedNodeId = failedNodeId;
 
-        if (log == null)
+        if (log == null) {
+            msgLog = cctx.txRecoveryMessageLogger();
             log = U.logger(cctx.kernalContext(), logRef, GridCacheTxRecoveryFuture.class);
+        }
 
         nodes = new GridLeanMap<>();
 
@@ -168,11 +173,24 @@ public class GridCacheTxRecoveryFuture extends GridCompoundIdentityFuture<Boolea
 
                 try {
                     cctx.io().send(nearNodeId, req, tx.ioPolicy());
+
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("Recovery fut, sent request near tx [txId=" + tx.nearXidVersion() +
+                            ", dhtTxId=" + tx.xidVersion() +
+                            ", node=" + nearNodeId + ']');
+                    }
                 }
                 catch (ClusterTopologyCheckedException ignore) {
                     fut.onNodeLeft();
                 }
                 catch (IgniteCheckedException e) {
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("Recovery fut, failed to send request near tx [txId=" + tx.nearXidVersion() +
+                            ", dhtTxId=" + tx.xidVersion() +
+                            ", node=" + nearNodeId +
+                            ", err=" + e + ']');
+                    }
+
                     fut.onError(e);
                 }
 
@@ -274,11 +292,24 @@ public class GridCacheTxRecoveryFuture extends GridCompoundIdentityFuture<Boolea
 
                     try {
                         cctx.io().send(id, req, tx.ioPolicy());
+
+                        if (msgLog.isDebugEnabled()) {
+                            msgLog.debug("Recovery fut, sent request to backup [txId=" + tx.nearXidVersion() +
+                                ", dhtTxId=" + tx.xidVersion() +
+                                ", node=" + id + ']');
+                        }
                     }
                     catch (ClusterTopologyCheckedException ignored) {
                         fut.onNodeLeft();
                     }
                     catch (IgniteCheckedException e) {
+                        if (msgLog.isDebugEnabled()) {
+                            msgLog.debug("Recovery fut, failed to send request to backup [txId=" + tx.nearXidVersion() +
+                                ", dhtTxId=" + tx.xidVersion() +
+                                ", node=" + id +
+                                ", err=" + e + ']');
+                        }
+
                         fut.onError(e);
 
                         break;
@@ -300,11 +331,24 @@ public class GridCacheTxRecoveryFuture extends GridCompoundIdentityFuture<Boolea
 
                 try {
                     cctx.io().send(nodeId, req, tx.ioPolicy());
+
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("Recovery fut, sent request to primary [txId=" + tx.nearXidVersion() +
+                            ", dhtTxId=" + tx.xidVersion() +
+                            ", node=" + nodeId + ']');
+                    }
                 }
                 catch (ClusterTopologyCheckedException ignored) {
                     fut.onNodeLeft();
                 }
                 catch (IgniteCheckedException e) {
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("Recovery fut, failed to send request to primary [txId=" + tx.nearXidVersion() +
+                            ", dhtTxId=" + tx.xidVersion() +
+                            ", node=" + nodeId +
+                            ", err=" + e + ']');
+                    }
+
                     fut.onError(e);
 
                     break;
@@ -348,6 +392,22 @@ public class GridCacheTxRecoveryFuture extends GridCompoundIdentityFuture<Boolea
 
                 mini.onResult(res);
             }
+            else {
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Tx recovery fut, failed to find mini future [txId=" + tx.nearXidVersion() +
+                        ", dhtTxId=" + tx.xidVersion() +
+                        ", node=" + nodeId +
+                        ", res=" + res +
+                        ", fut=" + this + ']');
+                }
+            }
+        }
+        else {
+            msgLog.debug("Tx recovery fut, response for finished future [txId=" + tx.nearXidVersion() +
+                ", dhtTxId=" + tx.xidVersion() +
+                ", node=" + nodeId +
+                ", res=" + res +
+                ", fut=" + this + ']');
         }
     }
 
@@ -509,8 +569,12 @@ public class GridCacheTxRecoveryFuture extends GridCompoundIdentityFuture<Boolea
         /**
          */
         private void onNodeLeft() {
-            if (log.isDebugEnabled())
-                log.debug("Transaction node left grid (will ignore) [fut=" + this + ']');
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("Tx recovery fut, mini future node left [txId=" + tx.nearXidVersion() +
+                    ", dhtTxId=" + tx.xidVersion() +
+                    ", node=" + nodeId +
+                    ", nearTxCheck=" + nearTxCheck + ']');
+            }
 
             if (nearTxCheck) {
                 // Near and originating nodes left, need initiate tx check.

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryRequest.java
index e5787d7..6fdb30b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryRequest.java
@@ -19,6 +19,9 @@ package org.apache.ignite.internal.processors.cache.distributed;
 
 import java.io.Externalizable;
 import java.nio.ByteBuffer;
+
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.typedef.internal.S;
@@ -127,6 +130,11 @@ public class GridCacheTxRecoveryRequest extends GridDistributedBaseMessage {
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.txRecoveryMessageLogger();
+    }
+
+    /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryResponse.java
index 361d381..265d53b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridCacheTxRecoveryResponse.java
@@ -19,6 +19,9 @@ package org.apache.ignite.internal.processors.cache.distributed;
 
 import java.io.Externalizable;
 import java.nio.ByteBuffer;
+
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.lang.IgniteUuid;
@@ -92,6 +95,11 @@ public class GridCacheTxRecoveryResponse extends GridDistributedBaseMessage {
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.txRecoveryMessageLogger();
+    }
+
+    /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockRequest.java
index 5d07b6f..34610ff 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockRequest.java
@@ -22,6 +22,7 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.UUID;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.GridDirectCollection;
 import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.processors.cache.GridCacheContext;
@@ -308,6 +309,11 @@ public class GridDistributedLockRequest extends GridDistributedBaseMessage {
         return timeout;
     }
 
+    /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.txLockMessageLogger();
+    }
+
     /** {@inheritDoc}
      * @param ctx*/
     @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java
index 7f95ec6..f56ba8f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java
@@ -23,6 +23,7 @@ import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.GridDirectCollection;
 import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.processors.cache.CacheObject;
@@ -188,6 +189,11 @@ public class GridDistributedLockResponse extends GridDistributedBaseMessage {
         return null;
     }
 
+    /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.txLockMessageLogger();
+    }
+
     /** {@inheritDoc}
      * @param ctx*/
     @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishRequest.java
index 34b3112..15c8fd4 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishRequest.java
@@ -20,7 +20,7 @@ package org.apache.ignite.internal.processors.cache.distributed;
 import java.io.Externalizable;
 import java.nio.ByteBuffer;
 import java.util.Collection;
-import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.tostring.GridToStringBuilder;
@@ -213,6 +213,11 @@ public class GridDistributedTxFinishRequest extends GridDistributedBaseMessage {
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.txFinishMessageLogger();
+    }
+
+    /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishResponse.java
index 4e17e79..c08c5b2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxFinishResponse.java
@@ -19,7 +19,10 @@ package org.apache.ignite.internal.processors.cache.distributed;
 
 import java.io.Externalizable;
 import java.nio.ByteBuffer;
+
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.processors.cache.GridCacheMessage;
+import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.tostring.GridToStringBuilder;
 import org.apache.ignite.lang.IgniteUuid;
@@ -79,6 +82,11 @@ public class GridDistributedTxFinishResponse extends GridCacheMessage {
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.txFinishMessageLogger();
+    }
+
+    /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java
index ea0f01c..871a599 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java
@@ -26,6 +26,7 @@ import java.util.Iterator;
 import java.util.Map;
 import java.util.UUID;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.GridDirectCollection;
 import org.apache.ignite.internal.GridDirectMap;
 import org.apache.ignite.internal.GridDirectTransient;
@@ -380,6 +381,11 @@ public class GridDistributedTxPrepareRequest extends GridDistributedBaseMessage
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.txPrepareMessageLogger();
+    }
+
+    /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java
index 34fff94..7011e80 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java
@@ -20,6 +20,7 @@ package org.apache.ignite.internal.processors.cache.distributed;
 import java.io.Externalizable;
 import java.nio.ByteBuffer;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
@@ -89,8 +90,12 @@ public class GridDistributedTxPrepareResponse extends GridDistributedBaseMessage
         return err != null;
     }
 
-    /** {@inheritDoc}
-     * @param ctx*/
+    /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.txPrepareMessageLogger();
+    }
+
+    /** {@inheritDoc} */
     @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {
         super.prepareMarshal(ctx);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedUnlockRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedUnlockRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedUnlockRequest.java
index 213a0ff..3091272 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedUnlockRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedUnlockRequest.java
@@ -22,6 +22,7 @@ import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.List;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.GridDirectCollection;
 import org.apache.ignite.internal.processors.cache.GridCacheContext;
 import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
@@ -97,6 +98,11 @@ public class GridDistributedUnlockRequest extends GridDistributedBaseMessage {
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.txLockMessageLogger();
+    }
+
+    /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockFuture.java
index 0a3513a..3b9ba4e 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLockFuture.java
@@ -87,6 +87,9 @@ public final class GridDhtLockFuture extends GridCompoundIdentityFuture<Boolean>
     /** Logger. */
     private static IgniteLogger log;
 
+    /** Logger. */
+    private static IgniteLogger msgLog;
+
     /** Cache registry. */
     @GridToStringExclude
     private GridCacheContext<?, ?> cctx;
@@ -235,8 +238,10 @@ public final class GridDhtLockFuture extends GridCompoundIdentityFuture<Boolean>
         entries = new ArrayList<>(cnt);
         pendingLocks = U.newHashSet(cnt);
 
-        if (log == null)
+        if (log == null) {
+            msgLog = cctx.shared().txLockMessageLogger();
             log = U.logger(cctx.kernalContext(), logRef, GridDhtLockFuture.class);
+        }
 
         if (timeout > 0) {
             timeoutObj = new LockTimeoutObject();
@@ -515,27 +520,21 @@ public final class GridDhtLockFuture extends GridCompoundIdentityFuture<Boolean>
      */
     void onResult(UUID nodeId, GridDhtLockResponse res) {
         if (!isDone()) {
-            if (log.isDebugEnabled())
-                log.debug("Received lock response from node [nodeId=" + nodeId + ", res=" + res + ", fut=" + this + ']');
-
             MiniFuture mini = miniFuture(res.miniId());
 
             if (mini != null) {
                 assert mini.node().id().equals(nodeId);
 
-                if (log.isDebugEnabled())
-                    log.debug("Found mini future for response [mini=" + mini + ", res=" + res + ']');
-
                 mini.onResult(res);
 
-                if (log.isDebugEnabled())
-                    log.debug("Futures after processed lock response [fut=" + this + ", mini=" + mini +
-                        ", res=" + res + ']');
-
                 return;
             }
 
-            U.warn(log, "Failed to find mini future for response (perhaps due to stale message) [res=" + res +
+            U.warn(msgLog, "DHT lock fut, failed to find mini future [txId=" + nearLockVer +
+                ", dhtTxId=" + lockVer +
+                ", inTx=" + inTx() +
+                ", node=" + nodeId +
+                ", res=" + res +
                 ", fut=" + this + ']');
         }
     }
@@ -951,18 +950,31 @@ public final class GridDhtLockFuture extends GridCompoundIdentityFuture<Boolean>
 
                             add(fut); // Append new future.
 
-                            if (log.isDebugEnabled())
-                                log.debug("Sending DHT lock request to DHT node [node=" + n.id() + ", req=" + req + ']');
-
                             cctx.io().send(n, req, cctx.ioPolicy());
+
+                            if (msgLog.isDebugEnabled()) {
+                                msgLog.debug("DHT lock fut, sent request [txId=" + nearLockVer +
+                                    ", dhtTxId=" + lockVer +
+                                    ", inTx=" + inTx() +
+                                    ", nodeId=" + n.id() + ']');
+                            }
                         }
                     }
                     catch (IgniteCheckedException e) {
                         // Fail the whole thing.
                         if (e instanceof ClusterTopologyCheckedException)
                             fut.onResult((ClusterTopologyCheckedException)e);
-                        else
+                        else {
+                            if (msgLog.isDebugEnabled()) {
+                                msgLog.debug("DHT lock fut, failed to send request [txId=" + nearLockVer +
+                                    ", dhtTxId=" + lockVer +
+                                    ", inTx=" + inTx() +
+                                    ", node=" + n.id() +
+                                    ", err=" + e + ']');
+                            }
+
                             fut.onResult(e);
+                        }
                     }
                 }
             }
@@ -1167,8 +1179,12 @@ public final class GridDhtLockFuture extends GridCompoundIdentityFuture<Boolean>
          * @param e Node failure.
          */
         void onResult(ClusterTopologyCheckedException e) {
-            if (log.isDebugEnabled())
-                log.debug("Remote node left grid while sending or waiting for reply (will ignore): " + this);
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("DHT lock fut, mini future node left [txId=" + nearLockVer +
+                    ", dhtTxId=" + lockVer +
+                    ", inTx=" + inTx() +
+                    ", node=" + node.id() + ']');
+            }
 
             if (tx != null)
                 tx.removeMapping(node.id());

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTransactionalCacheAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTransactionalCacheAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTransactionalCacheAdapter.java
index 0ca02c3..e2c0891 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTransactionalCacheAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTransactionalCacheAdapter.java
@@ -375,6 +375,13 @@ public abstract class GridDhtTransactionalCacheAdapter<K, V> extends GridDhtCach
      * @param req Request.
      */
     protected final void processDhtLockRequest(final UUID nodeId, final GridDhtLockRequest req) {
+        if (txLockMsgLog.isDebugEnabled()) {
+            txLockMsgLog.debug("Received dht lock request [txId=" + req.nearXidVersion() +
+                ", dhtTxId=" + req.version() +
+                ", inTx=" + req.inTx() +
+                ", node=" + nodeId + ']');
+        }
+
         IgniteInternalFuture<Object> keyFut = F.isEmpty(req.keys()) ? null :
             ctx.dht().dhtPreloader().request(req.keys(), req.topologyVersion());
 
@@ -450,10 +457,6 @@ public abstract class GridDhtTransactionalCacheAdapter<K, V> extends GridDhtCach
         assert req != null;
         assert !nodeId.equals(locNodeId);
 
-        if (log.isDebugEnabled())
-            log.debug("Processing dht lock request [locNodeId=" + locNodeId + ", nodeId=" + nodeId + ", req=" + req +
-                ']');
-
         int cnt = F.size(req.keys());
 
         GridDhtLockResponse res;
@@ -527,15 +530,30 @@ public abstract class GridDhtTransactionalCacheAdapter<K, V> extends GridDhtCach
             try {
                 // Reply back to sender.
                 ctx.io().send(nodeId, res, ctx.ioPolicy());
+
+                if (txLockMsgLog.isDebugEnabled()) {
+                    txLockMsgLog.debug("Sent dht lock response [txId=" + req.nearXidVersion() +
+                        ", dhtTxId=" + req.version() +
+                        ", inTx=" + req.inTx() +
+                        ", node=" + nodeId + ']');
+                }
             }
             catch (ClusterTopologyCheckedException ignored) {
-                U.warn(log, "Failed to send lock reply to remote node because it left grid: " + nodeId);
+                U.warn(txLockMsgLog, "Failed to send dht lock response, node failed [" +
+                    "txId=" + req.nearXidVersion() +
+                    ", dhtTxId=" + req.version() +
+                    ", inTx=" + req.inTx() +
+                    ", node=" + nodeId + ']');
 
                 fail = true;
                 releaseAll = true;
             }
             catch (IgniteCheckedException e) {
-                U.error(log, "Failed to send lock reply to node (lock will not be acquired): " + nodeId, e);
+                U.error(txLockMsgLog, "Failed to send dht lock response (lock will not be acquired) " +
+                    "txId=" + req.nearXidVersion() +
+                    ", dhtTxId=" + req.version() +
+                    ", inTx=" + req.inTx() +
+                    ", node=" + nodeId + ']', e);
 
                 fail = true;
             }
@@ -600,14 +618,18 @@ public abstract class GridDhtTransactionalCacheAdapter<K, V> extends GridDhtCach
         assert nodeId != null;
         assert req != null;
 
-        if (log.isDebugEnabled())
-            log.debug("Processing near lock request [locNodeId=" + locNodeId + ", nodeId=" + nodeId + ", req=" + req +
-                ']');
+        if (txLockMsgLog.isDebugEnabled()) {
+            txLockMsgLog.debug("Received near lock request [txId=" + req.version() +
+                ", inTx=" + req.inTx() +
+                ", node=" + nodeId + ']');
+        }
 
         ClusterNode nearNode = ctx.discovery().node(nodeId);
 
         if (nearNode == null) {
-            U.warn(log, "Received lock request from unknown node (will ignore): " + nodeId);
+            U.warn(txLockMsgLog, "Received near lock request from unknown node (will ignore) [txId=" + req.version() +
+                ", inTx=" + req.inTx() +
+                ", node=" + nodeId + ']');
 
             return;
         }
@@ -630,11 +652,18 @@ public abstract class GridDhtTransactionalCacheAdapter<K, V> extends GridDhtCach
         GridDhtLockFuture fut = (GridDhtLockFuture)ctx.mvcc().<Boolean>mvccFuture(res.version(), res.futureId());
 
         if (fut == null) {
-            if (log.isDebugEnabled())
-                log.debug("Received response for unknown future (will ignore): " + res);
+            if (txLockMsgLog.isDebugEnabled())
+                txLockMsgLog.debug("Received dht lock response for unknown future [txId=null" +
+                    ", dhtTxId=" + res.version() +
+                    ", node=" + nodeId + ']');
 
             return;
         }
+        else if (txLockMsgLog.isDebugEnabled()) {
+            txLockMsgLog.debug("Received dht lock response [txId=" + fut.nearLockVersion() +
+                ", dhtTxId=" + res.version() +
+                ", node=" + nodeId + ']');
+        }
 
         fut.onResult(nodeId, res);
     }
@@ -1283,12 +1312,30 @@ public abstract class GridDhtTransactionalCacheAdapter<K, V> extends GridDhtCach
 
         try {
             // Don't send reply message to this node or if lock was cancelled.
-            if (!nearNode.id().equals(ctx.nodeId()) && !X.hasCause(err, GridDistributedLockCancelledException.class))
+            if (!nearNode.id().equals(ctx.nodeId()) && !X.hasCause(err, GridDistributedLockCancelledException.class)) {
                 ctx.io().send(nearNode, res, ctx.ioPolicy());
+
+                if (txLockMsgLog.isDebugEnabled()) {
+                    txLockMsgLog.debug("Sent near lock response [txId=" + req.version() +
+                        ", inTx=" + req.inTx() +
+                        ", node=" + nearNode.id() + ']');
+                }
+            }
+            else {
+                if (txLockMsgLog.isDebugEnabled() && !nearNode.id().equals(ctx.nodeId())) {
+                    txLockMsgLog.debug("Skip send near lock response [txId=" + req.version() +
+                        ", inTx=" + req.inTx() +
+                        ", node=" + nearNode.id() +
+                        ", err=" + err + ']');
+                }
+            }
         }
         catch (IgniteCheckedException e) {
-            U.error(log, "Failed to send lock reply to originating node (will rollback transaction) [node=" +
-                U.toShortString(nearNode) + ", req=" + req + ']', e);
+            U.error(txLockMsgLog, "Failed to send near lock response (will rollback transaction) [" +
+                "txId=" + req.version() +
+                ", inTx=" + req.inTx() +
+                ", node=" + nearNode.id() +
+                ", res=" + res + ']', e);
 
             if (tx != null)
                 tx.rollbackAsync();

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishFuture.java
index 9a0d778..ee5434b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishFuture.java
@@ -60,6 +60,9 @@ public final class GridDhtTxFinishFuture<K, V> extends GridCompoundIdentityFutur
     /** Logger. */
     private static IgniteLogger log;
 
+    /** Logger. */
+    private static IgniteLogger msgLog;
+
     /** Context. */
     private GridCacheSharedContext<K, V> cctx;
 
@@ -103,8 +106,17 @@ public final class GridDhtTxFinishFuture<K, V> extends GridCompoundIdentityFutur
 
         futId = IgniteUuid.randomUuid();
 
-        if (log == null)
+        if (log == null) {
+            msgLog = cctx.txFinishMessageLogger();
             log = U.logger(cctx.kernalContext(), logRef, GridDhtTxFinishFuture.class);
+        }
+    }
+
+    /**
+     * @return Transaction.
+     */
+    public GridDhtTxLocalAdapter tx() {
+        return tx;
     }
 
     /** {@inheritDoc} */
@@ -179,17 +191,40 @@ public final class GridDhtTxFinishFuture<K, V> extends GridCompoundIdentityFutur
      */
     public void onResult(UUID nodeId, GridDhtTxFinishResponse res) {
         if (!isDone()) {
+            boolean found = false;
+
             for (IgniteInternalFuture<IgniteInternalTx> fut : futures()) {
                 if (isMini(fut)) {
                     MiniFuture f = (MiniFuture)fut;
 
                     if (f.futureId().equals(res.miniId())) {
+                        found = true;
+
                         assert f.node().id().equals(nodeId);
 
                         f.onResult(res);
                     }
                 }
             }
+
+            if (!found) {
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("DHT finish fut, failed to find mini future [txId=" + tx.nearXidVersion() +
+                        ", dhtTxId=" + tx.xidVersion() +
+                        ", node=" + nodeId +
+                        ", res=" + res +
+                        ", fut=" + this + ']');
+                }
+            }
+        }
+        else {
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("DHT finish fut, failed to find mini future [txId=" + tx.nearXidVersion() +
+                    ", dhtTxId=" + tx.xidVersion() +
+                    ", node=" + nodeId +
+                    ", res=" + res +
+                    ", fut=" + this + ']');
+            }
         }
     }
 
@@ -312,6 +347,12 @@ public final class GridDhtTxFinishFuture<K, V> extends GridCompoundIdentityFutur
             try {
                 cctx.io().send(n, req, tx.ioPolicy());
 
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("DHT finish fut, sent request lock tx [txId=" + tx.nearXidVersion() +
+                        ", dhtTxId=" + tx.xidVersion() +
+                        ", node=" + n.id() + ']');
+                }
+
                 if (sync)
                     res = true;
                 else
@@ -321,8 +362,16 @@ public final class GridDhtTxFinishFuture<K, V> extends GridCompoundIdentityFutur
                 // Fail the whole thing.
                 if (e instanceof ClusterTopologyCheckedException)
                     fut.onResult((ClusterTopologyCheckedException)e);
-                else
+                else {
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("DHT finish fut, failed to send request lock tx [txId=" + tx.nearXidVersion() +
+                            ", dhtTxId=" + tx.xidVersion() +
+                            ", node=" + n.id() +
+                            ", err=" + e + ']');
+                    }
+
                     fut.onResult(e);
+                }
             }
         }
 
@@ -398,6 +447,12 @@ public final class GridDhtTxFinishFuture<K, V> extends GridCompoundIdentityFutur
             try {
                 cctx.io().send(n, req, tx.ioPolicy());
 
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("DHT finish fut, sent request dht [txId=" + tx.nearXidVersion() +
+                        ", dhtTxId=" + tx.xidVersion() +
+                        ", node=" + n.id() + ']');
+                }
+
                 if (sync)
                     res = true;
                 else
@@ -407,8 +462,16 @@ public final class GridDhtTxFinishFuture<K, V> extends GridCompoundIdentityFutur
                 // Fail the whole thing.
                 if (e instanceof ClusterTopologyCheckedException)
                     fut.onResult((ClusterTopologyCheckedException)e);
-                else
+                else {
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("DHT finish fut, failed to send request dht [txId=" + tx.nearXidVersion() +
+                            ", dhtTxId=" + tx.xidVersion() +
+                            ", node=" + n.id() +
+                            ", err=" + e + ']');
+                    }
+
                     fut.onResult(e);
+                }
             }
         }
 
@@ -452,6 +515,12 @@ public final class GridDhtTxFinishFuture<K, V> extends GridCompoundIdentityFutur
                 try {
                     cctx.io().send(nearMapping.node(), req, tx.ioPolicy());
 
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("DHT finish fut, sent request near [txId=" + tx.nearXidVersion() +
+                            ", dhtTxId=" + tx.xidVersion() +
+                            ", node=" + nearMapping.node().id() + ']');
+                    }
+
                     if (sync)
                         res = true;
                     else
@@ -461,8 +530,16 @@ public final class GridDhtTxFinishFuture<K, V> extends GridCompoundIdentityFutur
                     // Fail the whole thing.
                     if (e instanceof ClusterTopologyCheckedException)
                         fut.onResult((ClusterTopologyCheckedException)e);
-                    else
+                    else {
+                        if (msgLog.isDebugEnabled()) {
+                            msgLog.debug("DHT finish fut, failed to send request near [txId=" + tx.nearXidVersion() +
+                                ", dhtTxId=" + tx.xidVersion() +
+                                ", node=" + nearMapping.node().id() +
+                                ", err=" + e + ']');
+                        }
+
                         fut.onResult(e);
+                    }
                 }
             }
         }
@@ -557,8 +634,11 @@ public final class GridDhtTxFinishFuture<K, V> extends GridCompoundIdentityFutur
          * @param e Node failure.
          */
         void onResult(ClusterTopologyCheckedException e) {
-            if (log.isDebugEnabled())
-                log.debug("Remote node left grid while sending or waiting for reply (will ignore): " + this);
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("DHT finish fut, mini future node left [txId=" + tx.nearXidVersion() +
+                    ", dhtTxId=" + tx.xidVersion() +
+                    ", node=" + node().id() + ']');
+            }
 
             // If node left, then there is nothing to commit on it.
             onDone(tx);

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxLocal.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxLocal.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxLocal.java
index f344d48..f862957 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxLocal.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxLocal.java
@@ -664,23 +664,38 @@ public class GridDhtTxLocal extends GridDhtTxLocalAdapter implements GridCacheMa
 
             try {
                 cctx.io().send(nearNodeId, res, ioPolicy());
+
+                if (cctx.txFinishMessageLogger().isDebugEnabled()) {
+                    cctx.txFinishMessageLogger().debug("Sent near finish response [txId=" + nearXidVersion() +
+                        ", dhtTxId=" + xidVersion() +
+                        ", node=" + nearNodeId + ']');
+                }
             }
             catch (ClusterTopologyCheckedException ignored) {
-                if (log.isDebugEnabled())
-                    log.debug("Node left before sending finish response (transaction was committed) [node=" +
-                        nearNodeId + ", res=" + res + ']');
+                if (cctx.txFinishMessageLogger().isDebugEnabled()) {
+                    cctx.txFinishMessageLogger().debug("Failed to send near finish response, node left [txId=" + nearXidVersion() +
+                        ", dhtTxId=" + xidVersion() +
+                        ", node=" + nearNodeId() + ']');
+                }
             }
             catch (Throwable ex) {
                 U.error(log, "Failed to send finish response to node (transaction was " +
-                    (commit ? "committed" : "rolledback") + ") [node=" + nearNodeId + ", res=" + res + ']', ex);
+                    (commit ? "committed" : "rolledback") + ") [txId=" + nearXidVersion() +
+                    ", dhtTxId=" + xidVersion() +
+                    ", node=" + nearNodeId +
+                    ", res=" + res + ']', ex);
 
                 if (ex instanceof Error)
                     throw (Error)ex;
             }
         }
         else {
-            if (log.isDebugEnabled())
-                log.debug("Will not send finish reply because sender node has not sent finish request yet: " + this);
+            if (cctx.txFinishMessageLogger().isDebugEnabled()) {
+                cctx.txFinishMessageLogger().debug("Will not send finish reply because sender node has not sent finish " +
+                    "request yet [txId=" + nearXidVersion() +
+                    ", dhtTxId=" + xidVersion() +
+                    ", node=" + nearNodeId() + ']');
+            }
         }
     }
 


[49/50] [abbrv] ignite git commit: IGNITE-2649: Replaced all usages of IgnitionEx.gridx() with IgnitionEx.localIgnite().

Posted by vo...@apache.org.
IGNITE-2649: Replaced all usages of IgnitionEx.gridx() with IgnitionEx.localIgnite().


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 6f7e3a8771b054f5678e310229e2f34f801f95d8
Parents: e5f3abd
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Mon Sep 5 12:47:08 2016 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Mon Sep 5 12:47:08 2016 +0300

----------------------------------------------------------------------
 .../java/org/apache/ignite/internal/GridKernalContextImpl.java     | 2 +-
 .../src/main/java/org/apache/ignite/internal/GridLoggerProxy.java  | 2 +-
 .../core/src/main/java/org/apache/ignite/internal/IgnitionEx.java  | 2 +-
 .../org/apache/ignite/internal/cluster/ClusterGroupAdapter.java    | 2 +-
 .../apache/ignite/internal/cluster/ClusterNodeLocalMapImpl.java    | 2 +-
 .../apache/ignite/internal/processors/cache/GridCacheAdapter.java  | 2 +-
 .../apache/ignite/internal/processors/cache/GridCacheContext.java  | 2 +-
 7 files changed, 7 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/6f7e3a87/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
index ebc2688..9a3fda2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridKernalContextImpl.java
@@ -875,7 +875,7 @@ public class GridKernalContextImpl implements GridKernalContext, Externalizable
      */
     protected Object readResolve() throws ObjectStreamException {
         try {
-            return IgnitionEx.gridx(stash.get()).context();
+            return IgnitionEx.localIgnite().context();
         }
         catch (IllegalStateException e) {
             throw U.withCause(new InvalidObjectException(e.getMessage()), e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f7e3a87/modules/core/src/main/java/org/apache/ignite/internal/GridLoggerProxy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridLoggerProxy.java b/modules/core/src/main/java/org/apache/ignite/internal/GridLoggerProxy.java
index f6bddca..b1da577 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridLoggerProxy.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridLoggerProxy.java
@@ -206,7 +206,7 @@ public class GridLoggerProxy implements IgniteLogger, LifecycleAware, Externaliz
             String gridNameR = t.get1();
             Object ctgrR = t.get2();
 
-            IgniteLogger log = IgnitionEx.gridx(gridNameR).log();
+            IgniteLogger log = IgnitionEx.localIgnite().log();
 
             return ctgrR != null ? log.getLogger(ctgrR) : log;
         }

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f7e3a87/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java b/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
index 5e55706..62bfd4a 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
@@ -1302,7 +1302,7 @@ public class IgnitionEx {
      * @param name Grid name.
      * @return Grid instance.
      */
-    public static IgniteKernal gridx(@Nullable String name) {
+    private static IgniteKernal gridx(@Nullable String name) {
         IgniteNamedInstance grid = name != null ? grids.get(name) : dfltGrid;
 
         IgniteKernal res;

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f7e3a87/modules/core/src/main/java/org/apache/ignite/internal/cluster/ClusterGroupAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/cluster/ClusterGroupAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/cluster/ClusterGroupAdapter.java
index c664f1e..648c86d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/cluster/ClusterGroupAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/cluster/ClusterGroupAdapter.java
@@ -727,7 +727,7 @@ public class ClusterGroupAdapter implements ClusterGroupEx, Externalizable {
      */
     protected Object readResolve() throws ObjectStreamException {
         try {
-            IgniteKernal g = IgnitionEx.gridx(gridName);
+            IgniteKernal g = IgnitionEx.localIgnite();
 
             return ids != null ? new ClusterGroupAdapter(g.context(), subjId, ids) :
                 new ClusterGroupAdapter(g.context(), subjId, p);

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f7e3a87/modules/core/src/main/java/org/apache/ignite/internal/cluster/ClusterNodeLocalMapImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/cluster/ClusterNodeLocalMapImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/cluster/ClusterNodeLocalMapImpl.java
index 4890231..26a9013 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/cluster/ClusterNodeLocalMapImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/cluster/ClusterNodeLocalMapImpl.java
@@ -89,7 +89,7 @@ public class ClusterNodeLocalMapImpl<K, V> extends ConcurrentHashMap8<K, V> impl
      */
     protected Object readResolve() throws ObjectStreamException {
         try {
-            return IgnitionEx.gridx(stash.get()).cluster().nodeLocalMap();
+            return IgnitionEx.localIgnite().cluster().nodeLocalMap();
         }
         catch (IllegalStateException e) {
             throw U.withCause(new InvalidObjectException(e.getMessage()), e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f7e3a87/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
index 05fd7d8..84d3fdf 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
@@ -4770,7 +4770,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
         try {
             IgniteBiTuple<String, String> t = stash.get();
 
-            return IgnitionEx.gridx(t.get1()).cachex(t.get2());
+            return IgnitionEx.localIgnite().cachex(t.get2());
         }
         catch (IllegalStateException e) {
             throw U.withCause(new InvalidObjectException(e.getMessage()), e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/6f7e3a87/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheContext.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheContext.java
index b7c8592..91ace02 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheContext.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheContext.java
@@ -2045,7 +2045,7 @@ public class GridCacheContext<K, V> implements Externalizable {
         try {
             IgniteBiTuple<String, String> t = stash.get();
 
-            IgniteKernal grid = IgnitionEx.gridx(t.get1());
+            IgniteKernal grid = IgnitionEx.localIgnite();
 
             GridCacheAdapter<K, V> cache = grid.internalCache(t.get2());
 


[35/50] [abbrv] ignite git commit: GG-11293: .NET: Backported affinity functions feature to 7.5.30.

Posted by vo...@apache.org.
GG-11293: .NET: Backported affinity functions feature to 7.5.30.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 5f57cc8d703f9e8f749c9e3c403781365642dc3a
Parents: 78d7c13
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Tue Jul 19 14:34:35 2016 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Tue Jul 19 14:34:35 2016 +0300

----------------------------------------------------------------------
 .../internal/binary/GridBinaryMarshaller.java   |  11 +-
 .../GridAffinityFunctionContextImpl.java        |   9 +
 .../processors/cache/GridCacheProcessor.java    |  65 +++--
 .../affinity/PlatformAffinityFunction.java      | 277 +++++++++++++++++++
 .../PlatformAffinityFunctionTarget.java         | 113 ++++++++
 .../cache/affinity/PlatformAffinityUtils.java   | 116 ++++++++
 .../callback/PlatformCallbackGateway.java       |  89 ++++++
 .../callback/PlatformCallbackUtils.java         |  49 ++++
 .../PlatformDotNetConfigurationClosure.java     | 115 +++++++-
 .../dotnet/PlatformDotNetAffinityFunction.java  | 171 ++++++++++++
 .../cpp/common/include/ignite/common/java.h     |  18 ++
 modules/platforms/cpp/common/src/java.cpp       |  36 ++-
 .../Apache.Ignite.Core.Tests.csproj             |   9 +-
 .../Affinity/AffinityFunctionSpringTest.cs      | 184 ++++++++++++
 .../Config/Cache/Affinity/affinity-function.xml | 129 +++++++++
 .../Cache/Affinity/affinity-function2.xml       |  49 ++++
 .../Apache.Ignite.Core.Tests/TestRunner.cs      |   3 +-
 .../Apache.Ignite.Core.csproj                   |  11 +-
 .../Cache/Affinity/AffinityFunctionBase.cs      | 139 ++++++++++
 .../Cache/Affinity/AffinityFunctionContext.cs   | 120 ++++++++
 .../Cache/Affinity/AffinityTopologyVersion.cs   | 138 +++++++++
 .../Cache/Affinity/Fair/FairAffinityFunction.cs |  32 +++
 .../Cache/Affinity/IAffinityFunction.cs         |  82 ++++++
 .../Rendezvous/RendezvousAffinityFunction.cs    |  31 +++
 .../Apache.Ignite.Core/Events/EventReader.cs    |   8 +-
 .../dotnet/Apache.Ignite.Core/Ignition.cs       |  38 ++-
 .../Impl/Binary/BinaryReaderExtensions.cs       |  14 +
 .../Impl/Binary/Marshaller.cs                   |   6 +-
 .../Affinity/AffinityFunctionSerializer.cs      | 277 +++++++++++++++++++
 .../Cache/Affinity/PlatformAffinityFunction.cs  |  74 +++++
 .../Impl/Common/ObjectInfoHolder.cs             |  86 ++++++
 .../Apache.Ignite.Core/Impl/IgniteUtils.cs      |  10 +-
 .../Impl/Unmanaged/UnmanagedCallbackHandlers.cs |   6 +
 .../Impl/Unmanaged/UnmanagedCallbacks.cs        | 133 ++++++++-
 34 files changed, 2596 insertions(+), 52 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/core/src/main/java/org/apache/ignite/internal/binary/GridBinaryMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/GridBinaryMarshaller.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/GridBinaryMarshaller.java
index 535207c..3a3dfd1 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/GridBinaryMarshaller.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/GridBinaryMarshaller.java
@@ -305,6 +305,15 @@ public class GridBinaryMarshaller {
     /**
      * Push binary context and return the old one.
      *
+     * @return Old binary context.
+     */
+    public BinaryContext pushContext() {
+        return pushContext(ctx);
+    }
+
+    /**
+     * Push binary context and return the old one.
+     *
      * @param ctx Binary context.
      * @return Old binary context.
      */
@@ -321,7 +330,7 @@ public class GridBinaryMarshaller {
      *
      * @param oldCtx Old binary context.
      */
-    private static void popContext(@Nullable BinaryContext oldCtx) {
+    public static void popContext(@Nullable BinaryContext oldCtx) {
         if (oldCtx == null)
             BINARY_CTX.remove();
         else

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/GridAffinityFunctionContextImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/GridAffinityFunctionContextImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/GridAffinityFunctionContextImpl.java
index 6c97efd..4ddee00 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/GridAffinityFunctionContextImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/GridAffinityFunctionContextImpl.java
@@ -80,4 +80,13 @@ public class GridAffinityFunctionContextImpl implements AffinityFunctionContext
     @Override public int backups() {
         return backups;
     }
+
+    /**
+     * Gets the previous assignment.
+     *
+     * @return Previous assignment.
+     */
+    public List<List<ClusterNode>> prevAssignment() {
+        return prevAssignment;
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
index 6484d4d..6761fac 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
@@ -69,10 +69,13 @@ import org.apache.ignite.internal.IgniteComponentType;
 import org.apache.ignite.internal.IgniteInternalFuture;
 import org.apache.ignite.internal.IgniteNodeAttributes;
 import org.apache.ignite.internal.IgniteTransactionsEx;
+import org.apache.ignite.internal.binary.BinaryContext;
 import org.apache.ignite.internal.binary.BinaryMarshaller;
+import org.apache.ignite.internal.binary.GridBinaryMarshaller;
 import org.apache.ignite.internal.managers.discovery.DiscoveryCustomMessage;
 import org.apache.ignite.internal.processors.GridProcessorAdapter;
 import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
+import org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl;
 import org.apache.ignite.internal.processors.cache.datastructures.CacheDataStructuresManager;
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtCache;
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtCacheAdapter;
@@ -94,12 +97,14 @@ import org.apache.ignite.internal.processors.cache.store.CacheStoreManager;
 import org.apache.ignite.internal.processors.cache.transactions.IgniteTransactionsImpl;
 import org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersionManager;
+import org.apache.ignite.internal.processors.cacheobject.IgniteCacheObjectProcessor;
 import org.apache.ignite.internal.processors.plugin.CachePluginManager;
 import org.apache.ignite.internal.processors.query.GridQueryProcessor;
 import org.apache.ignite.internal.util.F0;
 import org.apache.ignite.internal.util.future.GridCompoundFuture;
 import org.apache.ignite.internal.util.future.GridFinishedFuture;
 import org.apache.ignite.internal.util.future.GridFutureAdapter;
+import org.apache.ignite.internal.util.lang.IgniteOutClosureX;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.CIX1;
 import org.apache.ignite.internal.util.typedef.F;
@@ -3379,32 +3384,60 @@ public class GridCacheProcessor extends GridProcessorAdapter {
      * @throws IgniteCheckedException If validation failed.
      * @return Configuration copy.
      */
-    private CacheConfiguration cloneCheckSerializable(CacheConfiguration val) throws IgniteCheckedException {
+    private CacheConfiguration cloneCheckSerializable(final CacheConfiguration val) throws IgniteCheckedException {
         if (val == null)
             return null;
 
-        if (val.getCacheStoreFactory() != null) {
-            try {
-                ClassLoader ldr = ctx.config().getClassLoader();
+        return withBinaryContext(new IgniteOutClosureX<CacheConfiguration>() {
+            @Override public CacheConfiguration applyx() throws IgniteCheckedException {
+                if (val.getCacheStoreFactory() != null) {
+                    try {
+                        ClassLoader ldr = ctx.config().getClassLoader();
 
-                if (ldr == null)
-                    ldr = val.getCacheStoreFactory().getClass().getClassLoader();
+                        if (ldr == null)
+                            ldr = val.getCacheStoreFactory().getClass().getClassLoader();
 
-                marshaller.unmarshal(marshaller.marshal(val.getCacheStoreFactory()),
-                    U.resolveClassLoader(ldr, ctx.config()));
-            }
-            catch (IgniteCheckedException e) {
-                throw new IgniteCheckedException("Failed to validate cache configuration. " +
-                    "Cache store factory is not serializable. Cache name: " + U.maskName(val.getName()), e);
+                        marshaller.unmarshal(marshaller.marshal(val.getCacheStoreFactory()),
+                            U.resolveClassLoader(ldr, ctx.config()));
+                    }
+                    catch (IgniteCheckedException e) {
+                        throw new IgniteCheckedException("Failed to validate cache configuration. " +
+                            "Cache store factory is not serializable. Cache name: " + U.maskName(val.getName()), e);
+                    }
+                }
+
+                try {
+                    return marshaller.unmarshal(marshaller.marshal(val), U.resolveClassLoader(ctx.config()));
+                }
+                catch (IgniteCheckedException e) {
+                    throw new IgniteCheckedException("Failed to validate cache configuration " +
+                        "(make sure all objects in cache configuration are serializable): " + U.maskName(val.getName()), e);
+                }
             }
+        });
+    }
+
+    /**
+     * @param c Closure.
+     * @return Closure result.
+     * @throws IgniteCheckedException If failed.
+     */
+    private <T> T withBinaryContext(IgniteOutClosureX<T> c) throws IgniteCheckedException {
+        IgniteCacheObjectProcessor objProc = ctx.cacheObjects();
+        BinaryContext oldCtx = null;
+
+        if (objProc instanceof CacheObjectBinaryProcessorImpl) {
+            GridBinaryMarshaller binMarsh = ((CacheObjectBinaryProcessorImpl)objProc).marshaller();
+
+            oldCtx = binMarsh == null ? null : binMarsh.pushContext();
         }
 
         try {
-            return marshaller.unmarshal(marshaller.marshal(val), U.resolveClassLoader(ctx.config()));
+            return c.applyx();
         }
-        catch (IgniteCheckedException e) {
-            throw new IgniteCheckedException("Failed to validate cache configuration " +
-                "(make sure all objects in cache configuration are serializable): " + U.maskName(val.getName()), e);
+        finally {
+            if (objProc instanceof CacheObjectBinaryProcessorImpl)
+                GridBinaryMarshaller.popContext(oldCtx);
         }
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityFunction.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityFunction.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityFunction.java
new file mode 100644
index 0000000..6681e7a
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityFunction.java
@@ -0,0 +1,277 @@
+/*
+ * 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.platform.cache.affinity;
+
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.cache.affinity.AffinityFunction;
+import org.apache.ignite.cache.affinity.AffinityFunctionContext;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.internal.binary.BinaryRawWriterEx;
+import org.apache.ignite.internal.processors.platform.PlatformContext;
+import org.apache.ignite.internal.processors.platform.memory.PlatformMemory;
+import org.apache.ignite.internal.processors.platform.memory.PlatformOutputStream;
+import org.apache.ignite.internal.processors.platform.utils.PlatformUtils;
+import org.apache.ignite.lifecycle.LifecycleAware;
+import org.apache.ignite.resources.IgniteInstanceResource;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.List;
+import java.util.UUID;
+
+/**
+ * Platform AffinityFunction.
+ */
+public class PlatformAffinityFunction implements AffinityFunction, Externalizable, LifecycleAware {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** */
+    private static final byte FLAG_PARTITION = 1;
+
+    /** */
+    private static final byte FLAG_REMOVE_NODE = 1 << 1;
+
+    /** */
+    private static final byte FLAG_ASSIGN_PARTITIONS = 1 << 2;
+
+    /** */
+    private Object userFunc;
+
+    /**
+     * Partition count.
+     *
+     * 1) Java calls partitions() method very early (before LifecycleAware.start) during CacheConfiguration validation.
+     * 2) Partition count never changes.
+     * Therefore, we get the value on .NET side once, and pass it along with PlatformAffinity.
+     */
+    private int partitions;
+
+    /** */
+    private AffinityFunction baseFunc;
+
+    /** */
+    private byte overrideFlags;
+
+    /** */
+    private transient Ignite ignite;
+
+    /** */
+    private transient PlatformContext ctx;
+
+    /** */
+    private transient long ptr;
+
+    /** */
+    private transient PlatformAffinityFunctionTarget baseTarget;
+
+
+    /**
+     * Ctor for serialization.
+     *
+     */
+    public PlatformAffinityFunction() {
+        partitions = -1;
+    }
+
+    /**
+     * Ctor.
+     *
+     * @param func User fun object.
+     * @param partitions Number of partitions.
+     */
+    public PlatformAffinityFunction(Object func, int partitions, byte overrideFlags, AffinityFunction baseFunc) {
+        userFunc = func;
+        this.partitions = partitions;
+        this.overrideFlags = overrideFlags;
+        this.baseFunc = baseFunc;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void reset() {
+        // userFunc is always in initial state (it is serialized only once on start).
+        if (baseFunc != null)
+            baseFunc.reset();
+    }
+
+    /** {@inheritDoc} */
+    @Override public int partitions() {
+        // Affinity function can not return different number of partitions,
+        // so we pass this value once from the platform.
+        assert partitions > 0;
+
+        return partitions;
+    }
+
+    /** {@inheritDoc} */
+    @Override public int partition(Object key) {
+        if ((overrideFlags & FLAG_PARTITION) == 0) {
+            assert baseFunc != null;
+
+            return baseFunc.partition(key);
+        }
+
+        assert ctx != null;
+        assert ptr != 0;
+
+        try (PlatformMemory mem = ctx.memory().allocate()) {
+            PlatformOutputStream out = mem.output();
+            BinaryRawWriterEx writer = ctx.writer(out);
+
+            writer.writeObject(key);
+
+            out.synchronize();
+
+            return ctx.gateway().affinityFunctionPartition(ptr, mem.pointer());
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<List<ClusterNode>> assignPartitions(AffinityFunctionContext affCtx) {
+        if ((overrideFlags & FLAG_ASSIGN_PARTITIONS) == 0) {
+            assert baseFunc != null;
+
+            return baseFunc.assignPartitions(affCtx);
+        }
+
+        assert ctx != null;
+        assert ptr != 0;
+        assert affCtx != null;
+
+        try (PlatformMemory outMem = ctx.memory().allocate()) {
+            try (PlatformMemory inMem = ctx.memory().allocate()) {
+                PlatformOutputStream out = outMem.output();
+                BinaryRawWriterEx writer = ctx.writer(out);
+
+                // Write previous assignment
+                PlatformAffinityUtils.writeAffinityFunctionContext(affCtx, writer, ctx);
+
+                out.synchronize();
+
+                // Call platform
+                // We can not restore original AffinityFunctionContext after the call to platform,
+                // due to DiscoveryEvent (when node leaves, we can't get it by id anymore).
+                // Secondly, AffinityFunctionContext can't be changed by the user.
+                if (baseTarget != null)
+                    baseTarget.setCurrentAffinityFunctionContext(affCtx);
+
+                try {
+                    ctx.gateway().affinityFunctionAssignPartitions(ptr, outMem.pointer(), inMem.pointer());
+                }
+                finally {
+                    if (baseTarget != null)
+                        baseTarget.setCurrentAffinityFunctionContext(null);
+                }
+
+                // Read result
+                return PlatformAffinityUtils.readPartitionAssignment(ctx.reader(inMem), ctx);
+            }
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void removeNode(UUID nodeId) {
+        if ((overrideFlags & FLAG_REMOVE_NODE) == 0) {
+            assert baseFunc != null;
+
+            baseFunc.removeNode(nodeId);
+
+            return;
+        }
+
+        assert ctx != null;
+        assert ptr != 0;
+
+        try (PlatformMemory mem = ctx.memory().allocate()) {
+            PlatformOutputStream out = mem.output();
+            BinaryRawWriterEx writer = ctx.writer(out);
+
+            writer.writeUuid(nodeId);
+
+            out.synchronize();
+
+            ctx.gateway().affinityFunctionRemoveNode(ptr, mem.pointer());
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeExternal(ObjectOutput out) throws IOException {
+        out.writeObject(userFunc);
+        out.writeInt(partitions);
+        out.writeByte(overrideFlags);
+        out.writeObject(baseFunc);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+        userFunc = in.readObject();
+        partitions = in.readInt();
+        overrideFlags = in.readByte();
+        baseFunc = (AffinityFunction)in.readObject();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void start() throws IgniteException {
+        // userFunc is null when there is nothing overridden
+        if (userFunc == null)
+            return;
+
+        assert ignite != null;
+        ctx = PlatformUtils.platformContext(ignite);
+        assert ctx != null;
+
+        try (PlatformMemory mem = ctx.memory().allocate()) {
+            PlatformOutputStream out = mem.output();
+            BinaryRawWriterEx writer = ctx.writer(out);
+
+            writer.writeObject(userFunc);
+
+            out.synchronize();
+
+            baseTarget = baseFunc != null
+                ? new PlatformAffinityFunctionTarget(ctx, baseFunc)
+                : null;
+
+            ptr = ctx.gateway().affinityFunctionInit(mem.pointer(), baseTarget);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void stop() throws IgniteException {
+        if (ptr == 0)
+            return;
+
+        assert ctx != null;
+
+        ctx.gateway().affinityFunctionDestroy(ptr);
+    }
+
+    /**
+     * Injects the Ignite.
+     *
+     * @param ignite Ignite.
+     */
+    @SuppressWarnings("unused")
+    @IgniteInstanceResource
+    public void setIgnite(Ignite ignite) {
+        this.ignite = ignite;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityFunctionTarget.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityFunctionTarget.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityFunctionTarget.java
new file mode 100644
index 0000000..8a07b33
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityFunctionTarget.java
@@ -0,0 +1,113 @@
+/*
+ * 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.platform.cache.affinity;
+
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.cache.affinity.AffinityFunction;
+import org.apache.ignite.cache.affinity.AffinityFunctionContext;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.internal.binary.BinaryRawReaderEx;
+import org.apache.ignite.internal.binary.BinaryRawWriterEx;
+import org.apache.ignite.internal.processors.platform.PlatformAbstractTarget;
+import org.apache.ignite.internal.processors.platform.PlatformContext;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+import java.util.List;
+
+/**
+ * Platform affinity function target:
+ * to be invoked when Platform function calls base implementation of one of the AffinityFunction methods.
+ */
+public class PlatformAffinityFunctionTarget extends PlatformAbstractTarget {
+    /** */
+    private static final int OP_PARTITION = 1;
+
+    /** */
+    private static final int OP_REMOVE_NODE = 2;
+
+    /** */
+    private static final int OP_ASSIGN_PARTITIONS = 3;
+
+    /** Inner function to delegate calls to. */
+    private final AffinityFunction baseFunc;
+
+    /** Thread local to hold the current affinity function context. */
+    private static final ThreadLocal<AffinityFunctionContext> currentAffCtx = new ThreadLocal<>();
+
+    /**
+     * Constructor.
+     *
+     * @param platformCtx Context.
+     * @param baseFunc Function to wrap.
+     */
+    protected PlatformAffinityFunctionTarget(PlatformContext platformCtx, AffinityFunction baseFunc) {
+        super(platformCtx);
+
+        assert baseFunc != null;
+        this.baseFunc = baseFunc;
+
+        try {
+            platformCtx.kernalContext().resource().injectGeneric(baseFunc);
+        }
+        catch (IgniteCheckedException e) {
+            throw U.convertException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override protected long processInStreamOutLong(int type, BinaryRawReaderEx reader) throws IgniteCheckedException {
+        if (type == OP_PARTITION)
+            return baseFunc.partition(reader.readObjectDetached());
+        else if (type == OP_REMOVE_NODE) {
+            baseFunc.removeNode(reader.readUuid());
+
+            return 0;
+        }
+
+        return super.processInStreamOutLong(type, reader);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void processOutStream(int type, BinaryRawWriterEx writer) throws IgniteCheckedException {
+        if (type == OP_ASSIGN_PARTITIONS) {
+            AffinityFunctionContext affCtx = currentAffCtx.get();
+
+            if (affCtx == null)
+                throw new IgniteException("Thread-local AffinityFunctionContext is null. " +
+                        "This may indicate an unsupported call to the base AffinityFunction.");
+
+            final List<List<ClusterNode>> partitions = baseFunc.assignPartitions(affCtx);
+
+            PlatformAffinityUtils.writePartitionAssignment(partitions, writer, platformContext());
+
+            return;
+        }
+
+        super.processOutStream(type, writer);
+    }
+
+    /**
+     * Sets the context for current operation.
+     *
+     * @param ctx Context.
+     */
+    void setCurrentAffinityFunctionContext(AffinityFunctionContext ctx) {
+        currentAffCtx.set(ctx);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityUtils.java
new file mode 100644
index 0000000..b1e1b23
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityUtils.java
@@ -0,0 +1,116 @@
+/*
+ * 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.platform.cache.affinity;
+
+import org.apache.ignite.binary.BinaryRawReader;
+import org.apache.ignite.cache.affinity.AffinityFunctionContext;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.internal.binary.BinaryRawWriterEx;
+import org.apache.ignite.internal.cluster.IgniteClusterEx;
+import org.apache.ignite.internal.processors.affinity.GridAffinityFunctionContextImpl;
+import org.apache.ignite.internal.processors.platform.PlatformContext;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * Affinity serialization functions.
+ */
+public class PlatformAffinityUtils {
+    /**
+     * Writes the affinity function context.
+     * @param affCtx Affinity context.
+     * @param writer Writer.
+     * @param ctx Platform context.
+     */
+    public static void writeAffinityFunctionContext(AffinityFunctionContext affCtx, BinaryRawWriterEx writer,
+        PlatformContext ctx) {
+        assert affCtx != null;
+        assert writer != null;
+        assert ctx != null;
+
+        ctx.writeNodes(writer, affCtx.currentTopologySnapshot());
+
+        writer.writeInt(affCtx.backups());
+        writer.writeLong(affCtx.currentTopologyVersion().topologyVersion());
+        writer.writeInt(affCtx.currentTopologyVersion().minorTopologyVersion());
+
+        ctx.writeEvent(writer, affCtx.discoveryEvent());
+
+        // Write previous assignment
+        List<List<ClusterNode>> prevAssignment = ((GridAffinityFunctionContextImpl)affCtx).prevAssignment();
+
+        if (prevAssignment == null)
+            writer.writeInt(-1);
+        else {
+            writer.writeInt(prevAssignment.size());
+
+            for (List<ClusterNode> part : prevAssignment)
+                ctx.writeNodes(writer, part);
+        }
+    }
+
+    /**
+     * Writes the partition assignment to a stream.
+     *
+     * @param partitions Partitions.
+     * @param writer Writer.
+     */
+    public static void writePartitionAssignment(Collection<List<ClusterNode>> partitions, BinaryRawWriterEx writer,
+        PlatformContext ctx) {
+        assert partitions != null;
+        assert writer != null;
+
+        writer.writeInt(partitions.size());
+
+        for (List<ClusterNode> part : partitions)
+            ctx.writeNodes(writer, part);
+    }
+
+    /**
+     * Reads the partition assignment.
+     *
+     * @param reader Reader.
+     * @param ctx Platform context.
+     * @return Partitions.
+     */
+    public static List<List<ClusterNode>> readPartitionAssignment(BinaryRawReader reader, PlatformContext ctx) {
+        assert reader != null;
+        assert ctx != null;
+
+        int partCnt = reader.readInt();
+
+        List<List<ClusterNode>> res = new ArrayList<>(partCnt);
+
+        IgniteClusterEx cluster = ctx.kernalContext().grid().cluster();
+
+        for (int i = 0; i < partCnt; i++) {
+            int partSize = reader.readInt();
+
+            List<ClusterNode> part = new ArrayList<>(partSize);
+
+            for (int j = 0; j < partSize; j++)
+                part.add(cluster.node(reader.readUuid()));
+
+            res.add(part);
+        }
+
+        return res;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackGateway.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackGateway.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackGateway.java
index 47862a2..1759a5b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackGateway.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackGateway.java
@@ -19,6 +19,7 @@ package org.apache.ignite.internal.processors.platform.callback;
 
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteException;
+import org.apache.ignite.internal.processors.platform.cache.affinity.PlatformAffinityFunctionTarget;
 import org.apache.ignite.internal.util.GridStripedSpinBusyLock;
 
 /**
@@ -920,6 +921,94 @@ public class PlatformCallbackGateway {
     }
 
     /**
+     * Initializes affinity function.
+     *
+     * @param memPtr Pointer to a stream with serialized affinity function.
+     * @param baseFunc Optional func for base calls.
+     * @return Affinity function pointer.
+     */
+    public long affinityFunctionInit(long memPtr, PlatformAffinityFunctionTarget baseFunc) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.affinityFunctionInit(envPtr, memPtr, baseFunc);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Gets the partition from affinity function.
+     *
+     * @param ptr Affinity function pointer.
+     * @param memPtr Pointer to a stream with key object.
+     * @return Partition number for a given key.
+     */
+    public int affinityFunctionPartition(long ptr, long memPtr) {
+        enter();
+
+        try {
+            return PlatformCallbackUtils.affinityFunctionPartition(envPtr, ptr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Assigns the affinity partitions.
+     *
+     * @param ptr Affinity function pointer.
+     * @param outMemPtr Pointer to a stream with affinity context.
+     * @param inMemPtr Pointer to a stream with result.
+     */
+    public void affinityFunctionAssignPartitions(long ptr, long outMemPtr, long inMemPtr){
+        enter();
+
+        try {
+            PlatformCallbackUtils.affinityFunctionAssignPartitions(envPtr, ptr, outMemPtr, inMemPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Removes the node from affinity function.
+     *
+     * @param ptr Affinity function pointer.
+     * @param memPtr Pointer to a stream with node id.
+     */
+    public void affinityFunctionRemoveNode(long ptr, long memPtr) {
+        enter();
+
+        try {
+            PlatformCallbackUtils.affinityFunctionRemoveNode(envPtr, ptr, memPtr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
+     * Destroys the affinity function.
+     *
+     * @param ptr Affinity function pointer.
+     */
+    public void affinityFunctionDestroy(long ptr) {
+        if (!lock.enterBusy())
+            return;  // skip: destroy is not necessary during shutdown.
+
+        try {
+            PlatformCallbackUtils.affinityFunctionDestroy(envPtr, ptr);
+        }
+        finally {
+            leave();
+        }
+    }
+
+    /**
      * Enter gateway.
      */
     protected void enter() {

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackUtils.java
index 7f3ba6f..1cbbd7e 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackUtils.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/callback/PlatformCallbackUtils.java
@@ -17,6 +17,8 @@
 
 package org.apache.ignite.internal.processors.platform.callback;
 
+import org.apache.ignite.internal.processors.platform.cache.affinity.PlatformAffinityFunctionTarget;
+
 /**
  * Platform callback utility methods. Implemented in target platform. All methods in this class must be
  * package-visible and invoked only through {@link PlatformCallbackGateway}.
@@ -482,6 +484,53 @@ public class PlatformCallbackUtils {
     static native long extensionCallbackInLongLongOutLong(long envPtr, int typ, long arg1, long arg2);
 
     /**
+     * Initializes affinity function.
+     *
+     * @param envPtr Environment pointer.
+     * @param memPtr Pointer to a stream with serialized affinity function.
+     * @param baseFunc Optional func for base calls.
+     * @return Affinity function pointer.
+     */
+    static native long affinityFunctionInit(long envPtr, long memPtr, PlatformAffinityFunctionTarget baseFunc);
+
+    /**
+     * Gets the partition from affinity function.
+     *
+     * @param envPtr Environment pointer.
+     * @param ptr Affinity function pointer.
+     * @param memPtr Pointer to a stream with key object.
+     * @return Partition number for a given key.
+     */
+    static native int affinityFunctionPartition(long envPtr, long ptr, long memPtr);
+
+    /**
+     * Assigns the affinity partitions.
+     *
+     * @param envPtr Environment pointer.
+     * @param ptr Affinity function pointer.
+     * @param outMemPtr Pointer to a stream with affinity context.
+     * @param inMemPtr Pointer to a stream with result.
+     */
+    static native void affinityFunctionAssignPartitions(long envPtr, long ptr, long outMemPtr, long inMemPtr);
+
+    /**
+     * Removes the node from affinity function.
+     *
+     * @param envPtr Environment pointer.
+     * @param ptr Affinity function pointer.
+     * @param memPtr Pointer to a stream with node id.
+     */
+    static native void affinityFunctionRemoveNode(long envPtr, long ptr, long memPtr);
+
+    /**
+     * Destroys the affinity function.
+     *
+     * @param envPtr Environment pointer.
+     * @param ptr Affinity function pointer.
+     */
+    static native void affinityFunctionDestroy(long envPtr, long ptr);
+
+    /**
      * Private constructor.
      */
     private PlatformCallbackUtils() {

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/dotnet/PlatformDotNetConfigurationClosure.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/dotnet/PlatformDotNetConfigurationClosure.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/dotnet/PlatformDotNetConfigurationClosure.java
index 6b9b441..f441f4c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/dotnet/PlatformDotNetConfigurationClosure.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/platform/dotnet/PlatformDotNetConfigurationClosure.java
@@ -19,21 +19,28 @@ package org.apache.ignite.internal.processors.platform.dotnet;
 
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteException;
-import org.apache.ignite.binary.BinaryIdMapper;
 import org.apache.ignite.binary.BinaryBasicIdMapper;
-import org.apache.ignite.binary.BinaryNameMapper;
 import org.apache.ignite.binary.BinaryBasicNameMapper;
+import org.apache.ignite.binary.BinaryIdMapper;
+import org.apache.ignite.binary.BinaryNameMapper;
+import org.apache.ignite.cache.affinity.AffinityFunction;
+import org.apache.ignite.cache.affinity.fair.FairAffinityFunction;
+import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction;
 import org.apache.ignite.configuration.BinaryConfiguration;
+import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.configuration.PlatformConfiguration;
 import org.apache.ignite.internal.MarshallerContextImpl;
+import org.apache.ignite.internal.binary.BinaryContext;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.binary.BinaryNoopMetadataHandler;
+import org.apache.ignite.internal.binary.BinaryRawReaderEx;
 import org.apache.ignite.internal.binary.BinaryRawWriterEx;
+import org.apache.ignite.internal.binary.BinaryReaderExImpl;
 import org.apache.ignite.internal.binary.GridBinaryMarshaller;
-import org.apache.ignite.internal.binary.BinaryContext;
 import org.apache.ignite.internal.processors.platform.PlatformAbstractConfigurationClosure;
+import org.apache.ignite.internal.processors.platform.cache.affinity.PlatformAffinityFunction;
 import org.apache.ignite.internal.processors.platform.lifecycle.PlatformLifecycleBean;
-import org.apache.ignite.internal.processors.platform.memory.PlatformInputStream;
 import org.apache.ignite.internal.processors.platform.memory.PlatformMemory;
 import org.apache.ignite.internal.processors.platform.memory.PlatformMemoryManagerImpl;
 import org.apache.ignite.internal.processors.platform.memory.PlatformOutputStream;
@@ -42,8 +49,8 @@ import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lifecycle.LifecycleBean;
 import org.apache.ignite.logger.NullLogger;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.platform.dotnet.PlatformDotNetAffinityFunction;
 import org.apache.ignite.platform.dotnet.PlatformDotNetConfiguration;
-import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.platform.dotnet.PlatformDotNetLifecycleBean;
 
 import java.util.ArrayList;
@@ -183,7 +190,9 @@ public class PlatformDotNetConfigurationClosure extends PlatformAbstractConfigur
             try (PlatformMemory inMem = memMgr.allocate()) {
                 PlatformOutputStream out = outMem.output();
 
-                BinaryRawWriterEx writer = marshaller().writer(out);
+                final GridBinaryMarshaller marshaller = marshaller();
+
+                BinaryRawWriterEx writer = marshaller.writer(out);
 
                 PlatformUtils.writeDotNetConfiguration(writer, interopCfg.unwrap());
 
@@ -196,12 +205,24 @@ public class PlatformDotNetConfigurationClosure extends PlatformAbstractConfigur
                     writer.writeMap(bean.getProperties());
                 }
 
+                // Write .NET affinity funcs
+                List<PlatformDotNetAffinityFunction> affFuncs = affinityFunctions(igniteCfg);
+
+                writer.writeInt(affFuncs.size());
+
+                for (PlatformDotNetAffinityFunction func : affFuncs) {
+                    writer.writeString(func.getTypeName());
+                    writer.writeMap(func.getProperties());
+                }
+
                 out.synchronize();
 
                 gate.extensionCallbackInLongLongOutLong(
                     PlatformUtils.OP_PREPARE_DOT_NET, outMem.pointer(), inMem.pointer());
 
-                processPrepareResult(inMem.input());
+                BinaryReaderExImpl reader = new BinaryReaderExImpl(marshaller.context(), inMem.input(), null);
+
+                processPrepareResult(reader);
             }
         }
     }
@@ -211,7 +232,7 @@ public class PlatformDotNetConfigurationClosure extends PlatformAbstractConfigur
      *
      * @param in Input stream.
      */
-    private void processPrepareResult(PlatformInputStream in) {
+    private void processPrepareResult(BinaryReaderExImpl in) {
         assert cfg != null;
 
         List<PlatformDotNetLifecycleBean> beans = beans(cfg);
@@ -245,6 +266,63 @@ public class PlatformDotNetConfigurationClosure extends PlatformAbstractConfigur
                 cfg.setLifecycleBeans(mergedBeans);
             }
         }
+
+        // Process affinity functions
+        List<PlatformDotNetAffinityFunction> affFuncs = affinityFunctions(cfg);
+
+        if (!affFuncs.isEmpty()) {
+            for (PlatformDotNetAffinityFunction aff : affFuncs)
+                aff.init(readAffinityFunction(in));
+        }
+    }
+
+    /**
+     * Reads the affinity function.
+     *
+     * @param in Stream.
+     * @return Affinity function.
+     */
+    private static PlatformAffinityFunction readAffinityFunction(BinaryRawReaderEx in) {
+        byte plcTyp = in.readByte();
+
+        if (plcTyp == 0)
+            return null;
+
+        int partitions = in.readInt();
+        boolean exclNeighbours = in.readBoolean();
+        byte overrideFlags = in.readByte();
+        Object userFunc = in.readObjectDetached();
+
+        AffinityFunction baseFunc = null;
+
+        switch (plcTyp) {
+            case 1: {
+                FairAffinityFunction f = new FairAffinityFunction();
+
+                f.setPartitions(partitions);
+                f.setExcludeNeighbors(exclNeighbours);
+
+                baseFunc = f;
+
+                break;
+            }
+
+            case 2: {
+                RendezvousAffinityFunction f = new RendezvousAffinityFunction();
+
+                f.setPartitions(partitions);
+                f.setExcludeNeighbors(exclNeighbours);
+
+                baseFunc = f;
+
+                break;
+            }
+
+            default:
+                assert plcTyp == 3 : "Unknown affinity function policy type: " + plcTyp;
+        }
+
+        return new PlatformAffinityFunction(userFunc, partitions, overrideFlags, baseFunc);
     }
 
     /**
@@ -289,4 +367,25 @@ public class PlatformDotNetConfigurationClosure extends PlatformAbstractConfigur
             throw U.convertException(e);
         }
     }
+
+    /**
+     * Find .NET affinity functions in configuration.
+     *
+     * @param cfg Configuration.
+     * @return affinity functions.
+     */
+    private static List<PlatformDotNetAffinityFunction> affinityFunctions(IgniteConfiguration cfg) {
+        List<PlatformDotNetAffinityFunction> res = new ArrayList<>();
+
+        CacheConfiguration[] cacheCfg = cfg.getCacheConfiguration();
+
+        if (cacheCfg != null) {
+            for (CacheConfiguration ccfg : cacheCfg) {
+                if (ccfg.getAffinity() instanceof PlatformDotNetAffinityFunction)
+                    res.add((PlatformDotNetAffinityFunction)ccfg.getAffinity());
+            }
+        }
+
+        return res;
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/core/src/main/java/org/apache/ignite/platform/dotnet/PlatformDotNetAffinityFunction.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/platform/dotnet/PlatformDotNetAffinityFunction.java b/modules/core/src/main/java/org/apache/ignite/platform/dotnet/PlatformDotNetAffinityFunction.java
new file mode 100644
index 0000000..254c379
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/platform/dotnet/PlatformDotNetAffinityFunction.java
@@ -0,0 +1,171 @@
+/*
+ * 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.platform.dotnet;
+
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.cache.affinity.AffinityFunction;
+import org.apache.ignite.cache.affinity.AffinityFunctionContext;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.internal.processors.platform.cache.affinity.PlatformAffinityFunction;
+import org.apache.ignite.lifecycle.LifecycleAware;
+import org.apache.ignite.resources.IgniteInstanceResource;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ * AffinityFunction implementation which can be used to configure .NET affinity function in Java Spring configuration.
+ */
+public class PlatformDotNetAffinityFunction implements AffinityFunction, Externalizable, LifecycleAware {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** .NET type name. */
+    private transient String typName;
+
+    /** Properties. */
+    private transient Map<String, ?> props;
+
+    /** Inner function. */
+    private PlatformAffinityFunction func;
+
+    /**
+     * Gets .NET type name.
+     *
+     * @return .NET type name.
+     */
+    public String getTypeName() {
+        return typName;
+    }
+
+    /**
+     * Sets .NET type name.
+     *
+     * @param typName .NET type name.
+     */
+    public void setTypeName(String typName) {
+        this.typName = typName;
+    }
+
+    /**
+     * Get properties.
+     *
+     * @return Properties.
+     */
+    public Map<String, ?> getProperties() {
+        return props;
+    }
+
+    /**
+     * Set properties.
+     *
+     * @param props Properties.
+     */
+    public void setProperties(Map<String, ?> props) {
+        this.props = props;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void reset() {
+        assert func != null;
+
+        func.reset();
+    }
+
+    /** {@inheritDoc} */
+    @Override public int partitions() {
+        assert func != null;
+
+        return func.partitions();
+    }
+
+    /** {@inheritDoc} */
+    @Override public int partition(Object key) {
+        assert func != null;
+
+        return func.partition(key);
+    }
+
+    /** {@inheritDoc} */
+    @Override public List<List<ClusterNode>> assignPartitions(AffinityFunctionContext affCtx) {
+        assert func != null;
+
+        return func.assignPartitions(affCtx);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void removeNode(UUID nodeId) {
+        assert func != null;
+
+        func.removeNode(nodeId);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void writeExternal(ObjectOutput out) throws IOException {
+        out.writeObject(func);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+        func = (PlatformAffinityFunction) in.readObject();
+    }
+
+    /**
+     * Initializes this instance.
+     *
+     * @param func Underlying func.
+     */
+    public void init(PlatformAffinityFunction func) {
+        assert func != null;
+
+        this.func = func;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void start() throws IgniteException {
+        assert func != null;
+
+        func.start();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void stop() throws IgniteException {
+        assert func != null;
+
+        func.stop();
+    }
+
+    /**
+     * Injects the Ignite.
+     *
+     * @param ignite Ignite.
+     */
+    @SuppressWarnings("unused")
+    @IgniteInstanceResource
+    private void setIgnite(Ignite ignite) {
+        assert func != null;
+
+        func.setIgnite(ignite);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/cpp/common/include/ignite/common/java.h
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/common/include/ignite/common/java.h b/modules/platforms/cpp/common/include/ignite/common/java.h
index e629c77..91caddd 100644
--- a/modules/platforms/cpp/common/include/ignite/common/java.h
+++ b/modules/platforms/cpp/common/include/ignite/common/java.h
@@ -103,6 +103,12 @@ namespace ignite
             typedef long long(JNICALL *ExtensionCallbackInLongOutLongHandler)(void* target, int typ, long long arg1);
             typedef long long(JNICALL *ExtensionCallbackInLongLongOutLongHandler)(void* target, int typ, long long arg1, long long arg2);
 
+            typedef long long(JNICALL *AffinityFunctionInitHandler)(void* target, long long memPtr, void* baseFunc);
+            typedef int(JNICALL *AffinityFunctionPartitionHandler)(void* target, long long ptr, long long memPtr);
+            typedef void(JNICALL *AffinityFunctionAssignPartitionsHandler)(void* target, long long ptr, long long inMemPtr, long long outMemPtr);
+            typedef void(JNICALL *AffinityFunctionRemoveNodeHandler)(void* target, long long ptr, long long memPtr);
+            typedef void(JNICALL *AffinityFunctionDestroyHandler)(void* target, long long ptr);
+
             /**
              * JNI handlers holder.
              */
@@ -177,6 +183,12 @@ namespace ignite
 
                 ExtensionCallbackInLongOutLongHandler extensionCallbackInLongOutLong;
                 ExtensionCallbackInLongLongOutLongHandler extensionCallbackInLongLongOutLong;
+
+                AffinityFunctionInitHandler affinityFunctionInit;
+                AffinityFunctionPartitionHandler affinityFunctionPartition;
+                AffinityFunctionAssignPartitionsHandler affinityFunctionAssignPartitions;
+                AffinityFunctionRemoveNodeHandler affinityFunctionRemoveNode;
+                AffinityFunctionDestroyHandler affinityFunctionDestroy;
             };
 
             /**
@@ -683,6 +695,12 @@ namespace ignite
 
             JNIEXPORT jlong JNICALL JniExtensionCallbackInLongOutLong(JNIEnv *env, jclass cls, jlong envPtr, jint typ, jlong arg1);
             JNIEXPORT jlong JNICALL JniExtensionCallbackInLongLongOutLong(JNIEnv *env, jclass cls, jlong envPtr, jint typ, jlong arg1, jlong arg2);
+
+            JNIEXPORT jlong JNICALL JniAffinityFunctionInit(JNIEnv *env, jclass cls, jlong envPtr, jlong memPtr, jobject baseFunc);
+            JNIEXPORT jint JNICALL JniAffinityFunctionPartition(JNIEnv *env, jclass cls, jlong envPtr, jlong ptr, jlong memPtr);
+            JNIEXPORT void JNICALL JniAffinityFunctionAssignPartitions(JNIEnv *env, jclass cls, jlong envPtr, jlong ptr, jlong inMemPtr, jlong outMemPtr);
+            JNIEXPORT void JNICALL JniAffinityFunctionRemoveNode(JNIEnv *env, jclass cls, jlong envPtr, jlong ptr, jlong memPtr);
+            JNIEXPORT void JNICALL JniAffinityFunctionDestroy(JNIEnv *env, jclass cls, jlong envPtr, jlong ptr);
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/cpp/common/src/java.cpp
----------------------------------------------------------------------
diff --git a/modules/platforms/cpp/common/src/java.cpp b/modules/platforms/cpp/common/src/java.cpp
index 63deba5..789b6a3 100644
--- a/modules/platforms/cpp/common/src/java.cpp
+++ b/modules/platforms/cpp/common/src/java.cpp
@@ -346,6 +346,12 @@ namespace ignite
             JniMethod M_PLATFORM_CALLBACK_UTILS_EXTENSION_CALLBACK_IN_LONG_OUT_LONG = JniMethod("extensionCallbackInLongOutLong", "(JIJ)J", true);
             JniMethod M_PLATFORM_CALLBACK_UTILS_EXTENSION_CALLBACK_IN_LONG_LONG_OUT_LONG = JniMethod("extensionCallbackInLongLongOutLong", "(JIJJ)J", true);
 
+            JniMethod M_PLATFORM_CALLBACK_UTILS_AFFINITY_FUNCTION_INIT = JniMethod("affinityFunctionInit", "(JJLorg/apache/ignite/internal/processors/platform/cache/affinity/PlatformAffinityFunctionTarget;)J", true);
+            JniMethod M_PLATFORM_CALLBACK_UTILS_AFFINITY_FUNCTION_PARTITION = JniMethod("affinityFunctionPartition", "(JJJ)I", true);
+            JniMethod M_PLATFORM_CALLBACK_UTILS_AFFINITY_FUNCTION_ASSIGN_PARTITIONS = JniMethod("affinityFunctionAssignPartitions", "(JJJJ)V", true);
+            JniMethod M_PLATFORM_CALLBACK_UTILS_AFFINITY_FUNCTION_REMOVE_NODE = JniMethod("affinityFunctionRemoveNode", "(JJJ)V", true);
+            JniMethod M_PLATFORM_CALLBACK_UTILS_AFFINITY_FUNCTION_DESTROY = JniMethod("affinityFunctionDestroy", "(JJ)V", true);
+
             const char* C_PLATFORM_UTILS = "org/apache/ignite/internal/processors/platform/utils/PlatformUtils";
             JniMethod M_PLATFORM_UTILS_REALLOC = JniMethod("reallocate", "(JI)V", true);
             JniMethod M_PLATFORM_UTILS_ERR_DATA = JniMethod("errorData", "(Ljava/lang/Throwable;)[B", true);
@@ -766,7 +772,7 @@ namespace ignite
 
             void RegisterNatives(JNIEnv* env) {
                 {
-					JNINativeMethod methods[52];
+					JNINativeMethod methods[57];
 
                     int idx = 0;
 
@@ -840,6 +846,12 @@ namespace ignite
                     AddNativeMethod(methods + idx++, M_PLATFORM_CALLBACK_UTILS_EXTENSION_CALLBACK_IN_LONG_OUT_LONG, reinterpret_cast<void*>(JniExtensionCallbackInLongOutLong));
                     AddNativeMethod(methods + idx++, M_PLATFORM_CALLBACK_UTILS_EXTENSION_CALLBACK_IN_LONG_LONG_OUT_LONG, reinterpret_cast<void*>(JniExtensionCallbackInLongLongOutLong));
 
+                    AddNativeMethod(methods + idx++, M_PLATFORM_CALLBACK_UTILS_AFFINITY_FUNCTION_INIT, reinterpret_cast<void*>(JniAffinityFunctionInit));
+                    AddNativeMethod(methods + idx++, M_PLATFORM_CALLBACK_UTILS_AFFINITY_FUNCTION_PARTITION, reinterpret_cast<void*>(JniAffinityFunctionPartition));
+                    AddNativeMethod(methods + idx++, M_PLATFORM_CALLBACK_UTILS_AFFINITY_FUNCTION_ASSIGN_PARTITIONS, reinterpret_cast<void*>(JniAffinityFunctionAssignPartitions));
+                    AddNativeMethod(methods + idx++, M_PLATFORM_CALLBACK_UTILS_AFFINITY_FUNCTION_REMOVE_NODE, reinterpret_cast<void*>(JniAffinityFunctionRemoveNode));
+                    AddNativeMethod(methods + idx++, M_PLATFORM_CALLBACK_UTILS_AFFINITY_FUNCTION_DESTROY, reinterpret_cast<void*>(JniAffinityFunctionDestroy));
+
                     jint res = env->RegisterNatives(FindClass(env, C_PLATFORM_CALLBACK_UTILS), methods, idx);
 
                     if (res != JNI_OK)
@@ -2471,6 +2483,26 @@ namespace ignite
             JNIEXPORT jlong JNICALL JniExtensionCallbackInLongLongOutLong(JNIEnv *env, jclass cls, jlong envPtr, jint typ, jlong arg1, jlong arg2) {
                 IGNITE_SAFE_FUNC(env, envPtr, ExtensionCallbackInLongLongOutLongHandler, extensionCallbackInLongLongOutLong, typ, arg1, arg2);
             }
-        }
+
+            JNIEXPORT jlong JNICALL JniAffinityFunctionInit(JNIEnv *env, jclass cls, jlong envPtr, jlong memPtr, jobject baseFunc) {
+                void* baseFuncRef = baseFunc ? env->NewGlobalRef(baseFunc) : nullptr;
+                IGNITE_SAFE_FUNC(env, envPtr, AffinityFunctionInitHandler, affinityFunctionInit, memPtr, baseFuncRef);
+            }
+
+            JNIEXPORT jint JNICALL JniAffinityFunctionPartition(JNIEnv *env, jclass cls, jlong envPtr, jlong ptr, jlong memPtr) {
+                IGNITE_SAFE_FUNC(env, envPtr, AffinityFunctionPartitionHandler, affinityFunctionPartition, ptr, memPtr);
+            }
+
+            JNIEXPORT void JNICALL JniAffinityFunctionAssignPartitions(JNIEnv *env, jclass cls, jlong envPtr, jlong ptr, jlong inMemPtr, jlong outMemPtr) {
+                IGNITE_SAFE_PROC(env, envPtr, AffinityFunctionAssignPartitionsHandler, affinityFunctionAssignPartitions, ptr, inMemPtr, outMemPtr);
+            }
+
+            JNIEXPORT void JNICALL JniAffinityFunctionRemoveNode(JNIEnv *env, jclass cls, jlong envPtr, jlong ptr, jlong memPtr) {
+                IGNITE_SAFE_PROC(env, envPtr, AffinityFunctionRemoveNodeHandler, affinityFunctionRemoveNode, ptr, memPtr);
+            }
+
+            JNIEXPORT void JNICALL JniAffinityFunctionDestroy(JNIEnv *env, jclass cls, jlong envPtr, jlong ptr) {
+                IGNITE_SAFE_PROC(env, envPtr, AffinityFunctionDestroyHandler, affinityFunctionDestroy, ptr);
+            }        }
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj
index 0194450..89cd2a7 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj
+++ b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Apache.Ignite.Core.Tests.csproj
@@ -60,6 +60,7 @@
     <Reference Include="System.XML" />
   </ItemGroup>
   <ItemGroup>
+    <Compile Include="Cache\Affinity\AffinityFunctionSpringTest.cs" />
     <Compile Include="Cache\CacheDynamicStartTest.cs" />
     <Compile Include="Cache\CacheTestAsyncWrapper.cs" />
     <Compile Include="Cache\CacheAbstractTest.cs" />
@@ -175,6 +176,12 @@
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>
       <SubType>Designer</SubType>
     </Content>
+    <Content Include="Config\Cache\Affinity\affinity-function2.xml">
+      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+    </Content>
+    <Content Include="Config\Cache\Affinity\affinity-function.xml">
+      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+    </Content>
     <Content Include="Config\Cache\Store\cache-store-session.xml">
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>
     </Content>
@@ -262,4 +269,4 @@ copy /Y $(SolutionDir)Apache.Ignite\bin\$(PlatformName)\$(ConfigurationName)\Apa
   <Target Name="AfterBuild">
   </Target>
   -->
-</Project>
+</Project>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Cache/Affinity/AffinityFunctionSpringTest.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Cache/Affinity/AffinityFunctionSpringTest.cs b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Cache/Affinity/AffinityFunctionSpringTest.cs
new file mode 100644
index 0000000..7b317ac
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Cache/Affinity/AffinityFunctionSpringTest.cs
@@ -0,0 +1,184 @@
+\ufeff/*
+ * 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.
+ */
+
+// ReSharper disable UnusedAutoPropertyAccessor.Local
+// ReSharper disable UnusedMember.Local
+namespace Apache.Ignite.Core.Tests.Cache.Affinity
+{
+    using System;
+    using System.Collections.Generic;
+    using System.Linq;
+    using Apache.Ignite.Core.Cache;
+    using Apache.Ignite.Core.Cache.Affinity;
+    using Apache.Ignite.Core.Cache.Affinity.Fair;
+    using Apache.Ignite.Core.Cluster;
+    using Apache.Ignite.Core.Resource;
+    using NUnit.Framework;
+
+    /// <summary>
+    /// Tests AffinityFunction defined in Spring XML.
+    /// </summary>
+    public class AffinityFunctionSpringTest : IgniteTestBase
+    {
+        /// <summary>
+        /// Initializes a new instance of the <see cref="AffinityFunctionSpringTest"/> class.
+        /// </summary>
+        public AffinityFunctionSpringTest() : base(6,
+            "config\\cache\\affinity\\affinity-function.xml",
+            "config\\cache\\affinity\\affinity-function2.xml")
+        {
+            // No-op.
+        }
+
+        /// <summary>
+        /// Tests the static cache.
+        /// </summary>
+        [Test]
+        public void TestStaticCache()
+        {
+            ValidateAffinityFunction(Grid.GetCache<long, int>("cache1"));
+            ValidateAffinityFunction(Grid2.GetCache<long, int>("cache1"));
+            ValidateAffinityFunction(Grid.GetCache<long, int>("cache2"));
+            ValidateAffinityFunction(Grid2.GetCache<long, int>("cache2"));
+        }
+
+        /// <summary>
+        /// Tests the dynamic cache.
+        /// </summary>
+        [Test]
+        public void TestDynamicCache()
+        {
+            ValidateAffinityFunction(Grid.CreateCache<long, int>("dyn-cache-1"));
+            ValidateAffinityFunction(Grid2.GetCache<long, int>("dyn-cache-1"));
+
+            ValidateAffinityFunction(Grid2.CreateCache<long, int>("dyn-cache-2"));
+            ValidateAffinityFunction(Grid.GetCache<long, int>("dyn-cache-2"));
+
+            ValidateAffinityFunction(Grid.CreateCache<long, int>("dyn-cache2-1"));
+            ValidateAffinityFunction(Grid2.GetCache<long, int>("dyn-cache2-1"));
+
+            ValidateAffinityFunction(Grid2.CreateCache<long, int>("dyn-cache2-2"));
+            ValidateAffinityFunction(Grid.GetCache<long, int>("dyn-cache2-2"));
+        }
+
+        /// <summary>
+        /// Validates the affinity function.
+        /// </summary>
+        /// <param name="cache">The cache.</param>
+        private static void ValidateAffinityFunction(ICache<long, int> cache)
+        {
+            var aff = cache.Ignite.GetAffinity(cache.Name);
+
+            Assert.AreEqual(5, aff.Partitions);
+
+            // Predefined map
+            Assert.AreEqual(2, aff.GetPartition(1L));
+            Assert.AreEqual(1, aff.GetPartition(2L));
+
+            // Other keys
+            Assert.AreEqual(1, aff.GetPartition(13L));
+            Assert.AreEqual(3, aff.GetPartition(4L));
+        }
+
+        private class TestFunc : IAffinityFunction   // [Serializable] is not necessary
+        {
+            [InstanceResource]
+            private readonly IIgnite _ignite = null;
+
+            private int Property1 { get; set; }
+
+            private string Property2 { get; set; }
+
+            public int Partitions
+            {
+                get { return 5; }
+            }
+
+            public int GetPartition(object key)
+            {
+                Assert.IsNotNull(_ignite);
+                Assert.AreEqual(1, Property1);
+                Assert.AreEqual("1", Property2);
+
+                var longKey = (long)key;
+                int res;
+
+                if (TestFairFunc.PredefinedParts.TryGetValue(longKey, out res))
+                    return res;
+
+                return (int)(longKey * 2 % 5);
+            }
+
+            // ReSharper disable once UnusedParameter.Local
+            public void RemoveNode(Guid nodeId)
+            {
+                // No-op.
+            }
+
+            public IEnumerable<IEnumerable<IClusterNode>> AssignPartitions(AffinityFunctionContext context)
+            {
+                return Enumerable.Range(0, Partitions).Select(x => context.CurrentTopologySnapshot);
+            }
+        }
+
+        private class TestFairFunc : FairAffinityFunction   // [Serializable] is not necessary
+        {
+            public static readonly Dictionary<long, int> PredefinedParts = new Dictionary<long, int>
+            {
+                {1, 2},
+                {2, 1}
+            };
+
+            [InstanceResource]
+            private readonly IIgnite _ignite = null;
+
+            private int Property1 { get; set; }
+
+            private string Property2 { get; set; }
+
+            public override int GetPartition(object key)
+            {
+                Assert.IsNotNull(_ignite);
+                Assert.AreEqual(1, Property1);
+                Assert.AreEqual("1", Property2);
+
+                Assert.IsInstanceOf<long>(key);
+
+                var basePart = base.GetPartition(key);
+                Assert.Greater(basePart, -1);
+                Assert.Less(basePart, Partitions);
+
+                var longKey = (long) key;
+                int res;
+
+                if (PredefinedParts.TryGetValue(longKey, out res))
+                    return res;
+
+                return (int) (longKey * 2 % 5);
+            }
+
+            public override IEnumerable<IEnumerable<IClusterNode>> AssignPartitions(AffinityFunctionContext context)
+            {
+                var baseRes = base.AssignPartitions(context).ToList();  // test base call
+
+                Assert.AreEqual(Partitions, baseRes.Count);
+
+                return baseRes;
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Config/Cache/Affinity/affinity-function.xml
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Config/Cache/Affinity/affinity-function.xml b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Config/Cache/Affinity/affinity-function.xml
new file mode 100644
index 0000000..67ff128
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Config/Cache/Affinity/affinity-function.xml
@@ -0,0 +1,129 @@
+\ufeff<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+  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.
+-->
+
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:util="http://www.springframework.org/schema/util"
+       xsi:schemaLocation="
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans.xsd
+        http://www.springframework.org/schema/util
+        http://www.springframework.org/schema/util/spring-util.xsd">
+    <bean id="grid.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
+        <property name="localHost" value="127.0.0.1"/>
+        <property name="connectorConfiguration">
+            <null/>
+        </property>
+
+        <property name="cacheConfiguration">
+            <list>
+                <bean class="org.apache.ignite.configuration.CacheConfiguration">
+                    <property name="name" value="cache1"/>
+
+                    <property name="affinity">
+                        <bean class="org.apache.ignite.platform.dotnet.PlatformDotNetAffinityFunction">
+                            <property name="typeName" value="Apache.Ignite.Core.Tests.Cache.Affinity.AffinityFunctionSpringTest+TestFunc, Apache.Ignite.Core.Tests"/>
+                            <property name="properties">
+                                <map>
+                                    <entry key="Property1">
+                                        <value type="java.lang.Integer">1</value>
+                                    </entry>
+                                    <entry key="Property2" value="1"/>
+                                </map>
+                            </property>
+                        </bean>
+                    </property>
+                </bean>
+                <bean class="org.apache.ignite.configuration.CacheConfiguration">
+                    <property name="name" value="dyn-cache-*"/>
+
+                    <property name="affinity">
+                        <bean class="org.apache.ignite.platform.dotnet.PlatformDotNetAffinityFunction">
+                            <property name="typeName" value="Apache.Ignite.Core.Tests.Cache.Affinity.AffinityFunctionSpringTest+TestFunc, Apache.Ignite.Core.Tests"/>
+                            <property name="properties">
+                                <map>
+                                    <entry key="Property1">
+                                        <value type="java.lang.Integer">1</value>
+                                    </entry>
+                                    <entry key="Property2" value="1"/>
+                                </map>
+                            </property>
+                        </bean>
+                    </property>
+                </bean>
+                <bean class="org.apache.ignite.configuration.CacheConfiguration">
+                    <property name="name" value="cache2"/>
+
+                    <property name="affinity">
+                        <bean class="org.apache.ignite.platform.dotnet.PlatformDotNetAffinityFunction">
+                            <property name="typeName" value="Apache.Ignite.Core.Tests.Cache.Affinity.AffinityFunctionSpringTest+TestFairFunc, Apache.Ignite.Core.Tests"/>
+                            <property name="properties">
+                                <map>
+                                    <entry key="Property1">
+                                        <value type="java.lang.Integer">1</value>
+                                    </entry>
+                                    <entry key="Property2" value="1"/>
+                                    <entry key="Partitions">
+                                        <value type="java.lang.Integer">5</value>
+                                    </entry>
+                                </map>
+                            </property>
+                        </bean>
+                    </property>
+                </bean>
+                <bean class="org.apache.ignite.configuration.CacheConfiguration">
+                    <property name="name" value="dyn-cache2-*"/>
+
+                    <property name="affinity">
+                        <bean class="org.apache.ignite.platform.dotnet.PlatformDotNetAffinityFunction">
+                            <property name="typeName" value="Apache.Ignite.Core.Tests.Cache.Affinity.AffinityFunctionSpringTest+TestFairFunc, Apache.Ignite.Core.Tests"/>
+                            <property name="properties">
+                                <map>
+                                    <entry key="Property1">
+                                        <value type="java.lang.Integer">1</value>
+                                    </entry>
+                                    <entry key="Property2" value="1"/>
+                                    <entry key="Partitions">
+                                        <value type="java.lang.Integer">5</value>
+                                    </entry>
+                                </map>
+                            </property>
+                        </bean>
+                    </property>
+                </bean>
+            </list>
+        </property>
+
+        <property name="discoverySpi">
+            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
+                <property name="ipFinder">
+                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">
+                        <property name="addresses">
+                            <list>
+                                <!-- In distributed environment, replace with actual host IP address. -->
+                                <value>127.0.0.1:47500</value>
+                            </list>
+                        </property>
+                    </bean>
+                </property>
+                <property name="socketTimeout" value="300" />
+            </bean>
+        </property>
+    </bean>
+</beans>

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Config/Cache/Affinity/affinity-function2.xml
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Config/Cache/Affinity/affinity-function2.xml b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Config/Cache/Affinity/affinity-function2.xml
new file mode 100644
index 0000000..cab34b5
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/Config/Cache/Affinity/affinity-function2.xml
@@ -0,0 +1,49 @@
+\ufeff<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+  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.
+-->
+
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:util="http://www.springframework.org/schema/util"
+       xsi:schemaLocation="
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans.xsd
+        http://www.springframework.org/schema/util
+        http://www.springframework.org/schema/util/spring-util.xsd">
+    <bean id="grid.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
+        <property name="localHost" value="127.0.0.1"/>
+        <property name="connectorConfiguration"><null/></property>
+        <property name="gridName" value="grid2" />
+
+        <property name="discoverySpi">
+            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
+                <property name="ipFinder">
+                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">
+                        <property name="addresses">
+                            <list>
+                                <!-- In distributed environment, replace with actual host IP address. -->
+                                <value>127.0.0.1:47500</value>
+                            </list>
+                        </property>
+                    </bean>
+                </property>
+                <property name="socketTimeout" value="300" />
+            </bean>
+        </property>
+    </bean>
+</beans>

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core.Tests/TestRunner.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/TestRunner.cs b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/TestRunner.cs
index 2b0ab8e..95be6dc 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/TestRunner.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/TestRunner.cs
@@ -20,6 +20,7 @@ namespace Apache.Ignite.Core.Tests
     using System;
     using System.Diagnostics;
     using System.Reflection;
+    using Apache.Ignite.Core.Tests.Cache.Affinity;
     using Apache.Ignite.Core.Tests.Memory;
     using NUnit.ConsoleRunner;
 
@@ -33,7 +34,7 @@ namespace Apache.Ignite.Core.Tests
 
             //TestOne(typeof(ContinuousQueryAtomiclBackupTest), "TestInitialQuery");
 
-            TestAll(typeof (ExecutableTest));
+            TestAll(typeof (AffinityFunctionSpringTest));
             //TestAllInAssembly();
         }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj b/modules/platforms/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
index 05a7fa7..6793873 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
@@ -55,6 +55,12 @@
   </ItemGroup>
   <ItemGroup>
     <Compile Include="Binary\Package-Info.cs" />
+    <Compile Include="Cache\Affinity\AffinityFunctionBase.cs" />
+    <Compile Include="Cache\Affinity\AffinityFunctionContext.cs" />
+    <Compile Include="Cache\Affinity\AffinityTopologyVersion.cs" />
+    <Compile Include="Cache\Affinity\Fair\FairAffinityFunction.cs" />
+    <Compile Include="Cache\Affinity\IAffinityFunction.cs" />
+    <Compile Include="Cache\Affinity\Rendezvous\RendezvousAffinityFunction.cs" />
     <Compile Include="Cache\CacheAtomicUpdateTimeoutException.cs" />
     <Compile Include="Cache\CacheEntryProcessorException.cs" />
     <Compile Include="Cache\CacheException.cs" />
@@ -108,7 +114,10 @@
     <Compile Include="Common\IgniteFutureCancelledException.cs" />
     <Compile Include="Common\IgniteGuid.cs" />
     <Compile Include="Common\Package-Info.cs" />
+    <Compile Include="Impl\Cache\Affinity\AffinityFunctionSerializer.cs" />
+    <Compile Include="Impl\Cache\Affinity\PlatformAffinityFunction.cs" />
     <Compile Include="Impl\Cache\Event\JavaCacheEntryEventFilter.cs" />
+    <Compile Include="Impl\Common\ObjectInfoHolder.cs" />
     <Compile Include="Impl\Common\PlatformJavaObjectFactoryProxy.cs" />
     <Compile Include="Compute\ComputeExecutionRejectedException.cs" />
     <Compile Include="Compute\ComputeJobAdapter.cs" />
@@ -414,4 +423,4 @@
   <Target Name="AfterBuild">
   </Target>
   -->
-</Project>
+</Project>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityFunctionBase.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityFunctionBase.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityFunctionBase.cs
new file mode 100644
index 0000000..ce2e5e1
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityFunctionBase.cs
@@ -0,0 +1,139 @@
+\ufeff/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Cache.Affinity
+{
+    using System;
+    using System.Collections.Generic;
+    using System.ComponentModel;
+    using Apache.Ignite.Core.Cluster;
+    using Apache.Ignite.Core.Common;
+
+    /// <summary>
+    /// Base class for predefined affinity functions.
+    /// </summary>
+    [Serializable]
+    public abstract class AffinityFunctionBase : IAffinityFunction
+    {
+        /// <summary> The default value for <see cref="Partitions"/> property. </summary>
+        public const int DefaultPartitions = 1024;
+
+        /** */
+        private int _partitions = DefaultPartitions;
+
+        /** */
+        private IAffinityFunction _baseFunction;
+
+
+        /// <summary>
+        /// Gets or sets the total number of partitions.
+        /// </summary>
+        [DefaultValue(DefaultPartitions)]
+        public virtual int Partitions
+        {
+            get { return _partitions; }
+            set { _partitions = value; }
+        }
+
+        /// <summary>
+        /// Gets partition number for a given key starting from 0. Partitioned caches
+        /// should make sure that keys are about evenly distributed across all partitions
+        /// from 0 to <see cref="Partitions" /> for best performance.
+        /// <para />
+        /// Note that for fully replicated caches it is possible to segment key sets among different
+        /// grid node groups. In that case each node group should return a unique partition
+        /// number. However, unlike partitioned cache, mappings of keys to nodes in
+        /// replicated caches are constant and a node cannot migrate from one partition
+        /// to another.
+        /// </summary>
+        /// <param name="key">Key to get partition for.</param>
+        /// <returns>
+        /// Partition number for a given key.
+        /// </returns>
+        public virtual int GetPartition(object key)
+        {
+            ThrowIfUninitialized();
+
+            return _baseFunction.GetPartition(key);
+        }
+
+        /// <summary>
+        /// Removes node from affinity. This method is called when it is safe to remove
+        /// disconnected node from affinity mapping.
+        /// </summary>
+        /// <param name="nodeId">The node identifier.</param>
+        public virtual void RemoveNode(Guid nodeId)
+        {
+            ThrowIfUninitialized();
+
+            _baseFunction.RemoveNode(nodeId);
+        }
+
+        /// <summary>
+        /// Gets affinity nodes for a partition. In case of replicated cache, all returned
+        /// nodes are updated in the same manner. In case of partitioned cache, the returned
+        /// list should contain only the primary and back up nodes with primary node being
+        /// always first.
+        /// <pare />
+        /// Note that partitioned affinity must obey the following contract: given that node
+        /// <code>N</code> is primary for some key <code>K</code>, if any other node(s) leave
+        /// grid and no node joins grid, node <code>N</code> will remain primary for key <code>K</code>.
+        /// </summary>
+        /// <param name="context">The affinity function context.</param>
+        /// <returns>
+        /// A collection of partitions, where each partition is a collection of nodes,
+        /// where first node is a primary node, and other nodes are backup nodes.
+        /// </returns>
+        public virtual IEnumerable<IEnumerable<IClusterNode>> AssignPartitions(AffinityFunctionContext context)
+        {
+            ThrowIfUninitialized();
+
+            return _baseFunction.AssignPartitions(context);
+        }
+
+        /// <summary>
+        /// Gets or sets a value indicating whether to exclude same-host-neighbors from being backups of each other.
+        /// </summary>
+        public virtual bool ExcludeNeighbors { get; set; }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="AffinityFunctionBase"/> class.
+        /// </summary>
+        internal AffinityFunctionBase()
+        {
+            // No-op.
+        }
+
+        /// <summary>
+        /// Sets the base function.
+        /// </summary>
+        /// <param name="baseFunc">The base function.</param>
+        internal void SetBaseFunction(IAffinityFunction baseFunc)
+        {
+            _baseFunction = baseFunc;
+        }
+
+        /// <summary>
+        /// Gets the direct usage error.
+        /// </summary>
+        private void ThrowIfUninitialized()
+        {
+            if (_baseFunction == null)
+                throw new IgniteException(GetType() + " has not yet been initialized.");
+        }
+    }
+}


[16/50] [abbrv] ignite git commit: IGNITE-3227 - Added method to get partition size

Posted by vo...@apache.org.
IGNITE-3227 - Added method to get partition size


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 8af307819dba9f9fea4946cb09df01c4ef146f8a
Parents: 5b49dad
Author: Alexey Goncharuk <al...@gmail.com>
Authored: Thu Jul 7 15:58:50 2016 -0700
Committer: Alexey Goncharuk <al...@gmail.com>
Committed: Thu Jul 7 15:58:50 2016 -0700

----------------------------------------------------------------------
 .../java/org/apache/ignite/IgniteCache.java     |  25 +
 .../processors/cache/GridCacheAdapter.java      | 215 ++++++++-
 .../processors/cache/GridCacheProxyImpl.java    |  36 ++
 .../processors/cache/IgniteCacheProxy.java      |  40 ++
 .../processors/cache/IgniteInternalCache.java   |  23 +
 .../cache/IgniteCacheAtomicPeekModesTest.java   |   2 +-
 .../cache/IgniteCachePeekModesAbstractTest.java | 463 ++++++++++++++++++-
 .../multijvm/IgniteCacheProcessProxy.java       |  46 +-
 8 files changed, 846 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/8af30781/modules/core/src/main/java/org/apache/ignite/IgniteCache.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/IgniteCache.java b/modules/core/src/main/java/org/apache/ignite/IgniteCache.java
index 3af2c44..8cefb4f 100644
--- a/modules/core/src/main/java/org/apache/ignite/IgniteCache.java
+++ b/modules/core/src/main/java/org/apache/ignite/IgniteCache.java
@@ -370,6 +370,20 @@ public interface IgniteCache<K, V> extends javax.cache.Cache<K, V>, IgniteAsyncS
     public long sizeLong(CachePeekMode... peekModes) throws CacheException;
 
     /**
+     * Gets the number of all entries cached in a partition as a long value. By default, if {@code peekModes} value
+     * isn't defined, only size of primary copies across all nodes will be returned. This behavior is identical to
+     * calling this method with {@link CachePeekMode#PRIMARY} peek mode.
+     * <p>
+     * NOTE: this operation is distributed and will query all participating nodes for their partition cache sizes.
+     *
+     * @param partition partition.
+     * @param peekModes Optional peek modes. If not provided, then total partition cache size is returned.
+     * @return Partion cache size across all nodes.
+     */
+    @IgniteAsyncSupported
+    public long sizeLong(int partition, CachePeekMode... peekModes) throws CacheException;
+
+    /**
      * Gets the number of all entries cached on this node. By default, if {@code peekModes} value isn't defined,
      * only size of primary copies will be returned. This behavior is identical to calling this method with
      * {@link CachePeekMode#PRIMARY} peek mode.
@@ -390,6 +404,17 @@ public interface IgniteCache<K, V> extends javax.cache.Cache<K, V>, IgniteAsyncS
     public long localSizeLong(CachePeekMode... peekModes);
 
     /**
+     * Gets the number of all entries cached on this node for the partition as a long value. By default, if {@code peekModes} value isn't
+     * defined, only size of primary copies will be returned. This behavior is identical to calling this method with
+     * {@link CachePeekMode#PRIMARY} peek mode.
+     *
+     * @param partition partition.
+     * @param peekModes Optional peek modes. If not provided, then total cache size is returned.
+     * @return Cache size on this node.
+     */
+    public long localSizeLong(int partition, CachePeekMode... peekModes);
+
+    /**
      * @param map Map containing keys and entry processors to be applied to values.
      * @param args Additional arguments to pass to the {@link EntryProcessor}.
      * @return The map of {@link EntryProcessorResult}s of the processing per key,

http://git-wip-us.apache.org/repos/asf/ignite/blob/8af30781/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
index 028f516..55bd81d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
@@ -84,6 +84,7 @@ import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.processors.cache.affinity.GridCacheAffinityImpl;
 import org.apache.ignite.internal.processors.cache.distributed.IgniteExternalizableExpiryPolicy;
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtCacheAdapter;
+import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtLocalPartition;
 import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtInvalidPartitionException;
 import org.apache.ignite.internal.processors.cache.dr.GridCacheDrInfo;
 import org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx;
@@ -3965,6 +3966,14 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
     }
 
     /** {@inheritDoc} */
+    @Override public long sizeLong(int partition, CachePeekMode[] peekModes) throws IgniteCheckedException {
+        if (isLocal())
+            return localSizeLong(partition, peekModes);
+
+        return sizeLongAsync(partition, peekModes).get();
+    }
+
+    /** {@inheritDoc} */
     @Override public IgniteInternalFuture<Integer> sizeAsync(final CachePeekMode[] peekModes) {
         assert peekModes != null;
 
@@ -4007,6 +4016,36 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteInternalFuture<Long> sizeLongAsync(final int part, final CachePeekMode[] peekModes) {
+        assert peekModes != null;
+
+        final PeekModes modes = parsePeekModes(peekModes, true);
+
+        IgniteClusterEx cluster = ctx.grid().cluster();
+        final GridCacheAffinityManager aff = ctx.affinity();
+        final AffinityTopologyVersion topVer = aff.affinityTopologyVersion();
+
+        ClusterGroup grp = cluster.forDataNodes(name());
+
+        Collection<ClusterNode> nodes = grp.forPredicate(new IgnitePredicate<ClusterNode>() {
+            /** {@inheritDoc} */
+            @Override public boolean apply(ClusterNode clusterNode) {
+                return clusterNode.version().compareTo(PartitionSizeLongTask.SINCE_VER) >= 0 &&
+                    ((modes.primary && aff.primary(clusterNode, part, topVer)) ||
+                        (modes.backup && aff.backup(clusterNode, part, topVer)));
+            }
+        }).nodes();
+
+        if (nodes.isEmpty())
+            return new GridFinishedFuture<>(0L);
+
+        ctx.kernalContext().task().setThreadContext(TC_SUBGRID, nodes);
+
+        return ctx.kernalContext().task().execute(
+                new PartitionSizeLongTask(ctx.name(), ctx.affinity().affinityTopologyVersion(), peekModes, part), null);
+    }
+
+    /** {@inheritDoc} */
     @Override public int localSize(CachePeekMode[] peekModes) throws IgniteCheckedException {
         return (int)localSizeLong(peekModes);
     }
@@ -4060,6 +4099,50 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
     }
 
     /** {@inheritDoc} */
+    @Override public long localSizeLong(int part, CachePeekMode[] peekModes) throws IgniteCheckedException {
+        PeekModes modes = parsePeekModes(peekModes, true);
+
+        long size = 0;
+
+        AffinityTopologyVersion topVer = ctx.affinity().affinityTopologyVersion();
+
+        // Swap and offheap are disabled for near cache.
+        GridCacheSwapManager swapMgr = ctx.isNear() ? ctx.near().dht().context().swap() : ctx.swap();
+
+        if (ctx.isLocal()){
+            modes.primary = true;
+            modes.backup = true;
+
+            if (modes.heap)
+                size += size();
+
+            if (modes.swap)
+                size += swapMgr.swapEntriesCount(0);
+
+            if (modes.offheap)
+                size += swapMgr.offheapEntriesCount(0);
+        }
+        else {
+            GridDhtLocalPartition dhtPart = ctx.topology().localPartition(part, topVer, false);
+
+            if (dhtPart != null) {
+                if (modes.primary && dhtPart.primary(topVer) || modes.backup && dhtPart.backup(topVer)) {
+                    if (modes.heap)
+                        size += dhtPart.publicSize();
+
+                    if (modes.swap)
+                        size += swapMgr.swapEntriesCount(part);
+
+                    if (modes.offheap)
+                        size += swapMgr.offheapEntriesCount(part);
+                }
+            }
+        }
+
+        return size;
+    }
+
+    /** {@inheritDoc} */
     @Override public int size() {
         return map.publicSize();
     }
@@ -5637,6 +5720,52 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
     }
 
     /**
+     * Internal callable for partition size calculation.
+     */
+    @GridInternal
+    private static class PartitionSizeLongJob extends TopologyVersionAwareJob {
+        /** */
+        private static final long serialVersionUID = 0L;
+
+        /** Partition. */
+        private final int partition;
+
+        /** Peek modes. */
+        private final CachePeekMode[] peekModes;
+
+        /**
+         * @param cacheName Cache name.
+         * @param topVer Affinity topology version.
+         * @param peekModes Cache peek modes.
+         * @param partition partition.
+         */
+        private PartitionSizeLongJob(String cacheName, AffinityTopologyVersion topVer, CachePeekMode[] peekModes, int partition) {
+            super(cacheName, topVer);
+
+            this.peekModes = peekModes;
+            this.partition = partition;
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public Object localExecute(@Nullable IgniteInternalCache cache) {
+            if (cache == null)
+                return 0;
+
+            try {
+                return cache.localSizeLong(partition, peekModes);
+            }
+            catch (IgniteCheckedException e) {
+                throw U.convertException(e);
+            }
+        }
+
+        /** {@inheritDoc} */
+        public String toString() {
+            return S.toString(PartitionSizeLongJob.class, this);
+        }
+    }
+
+    /**
      * Internal callable for global size calculation.
      */
     @GridInternal
@@ -6610,7 +6739,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
          * @param topVer Affinity topology version.
          * @param peekModes Cache peek modes.
          */
-        public SizeLongTask(String cacheName, AffinityTopologyVersion topVer, CachePeekMode[] peekModes) {
+        private SizeLongTask(String cacheName, AffinityTopologyVersion topVer, CachePeekMode[] peekModes) {
             this.cacheName = cacheName;
             this.topVer = topVer;
             this.peekModes = peekModes;
@@ -6655,6 +6784,90 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
     }
 
     /**
+     * Partition Size Long task.
+     */
+    private static class PartitionSizeLongTask extends ComputeTaskAdapter<Object, Long> {
+        /** */
+        private static final long serialVersionUID = 0L;
+
+        /** */
+        private static final IgniteProductVersion SINCE_VER = IgniteProductVersion.fromString("1.5.30");
+
+        /** Partition */
+        private final int partition;
+
+        /** Cache name. */
+        private final String cacheName;
+
+        /** Affinity topology version. */
+        private final AffinityTopologyVersion topVer;
+
+        /** Peek modes. */
+        private final CachePeekMode[] peekModes;
+
+        /**
+         * @param cacheName Cache name.
+         * @param topVer Affinity topology version.
+         * @param peekModes Cache peek modes.
+         * @param partition partition.
+         */
+        private PartitionSizeLongTask(
+            String cacheName,
+            AffinityTopologyVersion topVer,
+            CachePeekMode[] peekModes,
+            int partition
+        ) {
+            this.cacheName = cacheName;
+            this.topVer = topVer;
+            this.peekModes = peekModes;
+            this.partition = partition;
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public Map<? extends ComputeJob, ClusterNode> map(
+            List<ClusterNode> subgrid,
+            @Nullable Object arg
+        ) throws IgniteException {
+            Map<ComputeJob, ClusterNode> jobs = new HashMap();
+
+            for (ClusterNode node : subgrid)
+                jobs.put(new PartitionSizeLongJob(cacheName, topVer, peekModes, partition), node);
+
+            return jobs;
+        }
+
+        /** {@inheritDoc} */
+        @Override public ComputeJobResultPolicy result(ComputeJobResult res, List<ComputeJobResult> rcvd) {
+            IgniteException e = res.getException();
+
+            if (e != null) {
+                if (e instanceof ClusterTopologyException)
+                    return ComputeJobResultPolicy.WAIT;
+
+                throw new IgniteException("Remote job threw exception.", e);
+            }
+
+            return ComputeJobResultPolicy.WAIT;
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public Long reduce(List<ComputeJobResult> results) throws IgniteException {
+            long size = 0;
+
+            for (ComputeJobResult res : results) {
+                if (res != null) {
+                    if (res.getException() == null)
+                        size += res.<Long>getData();
+                    else
+                        throw res.getException();
+                }
+            }
+
+            return size;
+        }
+    }
+
+    /**
      * Clear task.
      */
     private static class ClearTask<K> extends ComputeTaskAdapter<Object, Object> {

http://git-wip-us.apache.org/repos/asf/ignite/blob/8af30781/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProxyImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProxyImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProxyImpl.java
index 99dd608..b46c4dc 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProxyImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProxyImpl.java
@@ -1483,6 +1483,18 @@ public class GridCacheProxyImpl<K, V> implements IgniteInternalCache<K, V>, Exte
     }
 
     /** {@inheritDoc} */
+    @Override public long sizeLong(int partition, CachePeekMode[] peekModes) throws IgniteCheckedException {
+        CacheOperationContext prev = gate.enter(opCtx);
+
+        try {
+            return delegate.sizeLong(partition, peekModes);
+        }
+        finally {
+            gate.leave(prev);
+        }
+    }
+
+    /** {@inheritDoc} */
     @Override public IgniteInternalFuture<Integer> sizeAsync(CachePeekMode[] peekModes) {
         CacheOperationContext prev = gate.enter(opCtx);
 
@@ -1507,6 +1519,18 @@ public class GridCacheProxyImpl<K, V> implements IgniteInternalCache<K, V>, Exte
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteInternalFuture<Long> sizeLongAsync(int partition, CachePeekMode[] peekModes) {
+        CacheOperationContext prev = gate.enter(opCtx);
+
+        try {
+            return delegate.sizeLongAsync(partition, peekModes);
+        }
+        finally {
+            gate.leave(prev);
+        }
+    }
+
+    /** {@inheritDoc} */
     @Override public int localSize(CachePeekMode[] peekModes) throws IgniteCheckedException {
         CacheOperationContext prev = gate.enter(opCtx);
 
@@ -1531,6 +1555,18 @@ public class GridCacheProxyImpl<K, V> implements IgniteInternalCache<K, V>, Exte
     }
 
     /** {@inheritDoc} */
+    @Override public long localSizeLong(int partition, CachePeekMode[] peekModes) throws IgniteCheckedException {
+        CacheOperationContext prev = gate.enter(opCtx);
+
+        try {
+            return delegate.localSizeLong(partition, peekModes);
+        }
+        finally {
+            gate.leave(prev);
+        }
+    }
+
+    /** {@inheritDoc} */
     @Override public int nearSize() {
         CacheOperationContext prev = gate.enter(opCtx);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8af30781/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
index 12ec8b8..92e59db 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
@@ -840,6 +840,29 @@ public class IgniteCacheProxy<K, V> extends AsyncSupportAdapter<IgniteCache<K, V
 
 
     /** {@inheritDoc} */
+    @Override public long sizeLong(int part, CachePeekMode... peekModes) throws CacheException {
+        GridCacheGateway<K, V> gate = this.gate;
+
+        CacheOperationContext prev = onEnter(gate, opCtx);
+
+        try {
+            if (isAsync()) {
+                setFuture(delegate.sizeLongAsync(part, peekModes));
+
+                return 0;
+            }
+            else
+                return delegate.sizeLong(part, peekModes);
+        }
+        catch (IgniteCheckedException e) {
+            throw cacheException(e);
+        }
+        finally {
+            onLeave(gate, prev);
+        }
+    }
+
+    /** {@inheritDoc} */
     @Override public int localSize(CachePeekMode... peekModes) {
         GridCacheGateway<K, V> gate = this.gate;
 
@@ -874,6 +897,23 @@ public class IgniteCacheProxy<K, V> extends AsyncSupportAdapter<IgniteCache<K, V
     }
 
     /** {@inheritDoc} */
+    @Override public long localSizeLong(int part, CachePeekMode... peekModes) {
+        GridCacheGateway<K, V> gate = this.gate;
+
+        CacheOperationContext prev = onEnter(gate, opCtx);
+
+        try {
+            return delegate.localSizeLong(part, peekModes);
+        }
+        catch (IgniteCheckedException e) {
+            throw cacheException(e);
+        }
+        finally {
+            onLeave(gate, prev);
+        }
+    }
+
+    /** {@inheritDoc} */
     @Override public V get(K key) {
         try {
             GridCacheGateway<K, V> gate = this.gate;

http://git-wip-us.apache.org/repos/asf/ignite/blob/8af30781/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteInternalCache.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteInternalCache.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteInternalCache.java
index d155b0e..4dc9a23f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteInternalCache.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteInternalCache.java
@@ -1453,6 +1453,14 @@ public interface IgniteInternalCache<K, V> extends Iterable<Cache.Entry<K, V>> {
     public long localSizeLong(CachePeekMode[] peekModes) throws IgniteCheckedException;
 
     /**
+     * @param partition partition.
+     * @param peekModes Peek modes.
+     * @return Local cache size as a long value.
+     * @throws IgniteCheckedException If failed.
+     */
+    public long localSizeLong(int partition, CachePeekMode[] peekModes) throws IgniteCheckedException;
+
+    /**
      * @param peekModes Peek modes.
      * @return Global cache size.
      * @throws IgniteCheckedException If failed.
@@ -1467,6 +1475,14 @@ public interface IgniteInternalCache<K, V> extends Iterable<Cache.Entry<K, V>> {
     public long sizeLong(CachePeekMode[] peekModes) throws IgniteCheckedException;
 
     /**
+     * @param partition partition
+     * @param peekModes Peek modes.
+     * @return Global cache size as a long value.
+     * @throws IgniteCheckedException If failed.
+     */
+    public long sizeLong(int partition, CachePeekMode[] peekModes) throws IgniteCheckedException;
+
+    /**
      * @param peekModes Peek modes.
      * @return Future.
      */
@@ -1479,6 +1495,13 @@ public interface IgniteInternalCache<K, V> extends Iterable<Cache.Entry<K, V>> {
     public IgniteInternalFuture<Long> sizeLongAsync(CachePeekMode[] peekModes);
 
     /**
+     * @param partition partiton
+     * @param peekModes Peek modes.
+     * @return Future.
+     */
+    public IgniteInternalFuture<Long> sizeLongAsync(int partition, CachePeekMode[] peekModes);
+
+    /**
      * Gets size of near cache key set. This method will return count of all entries in near
      * cache and has O(1) complexity on base cache projection.
      * <p>

http://git-wip-us.apache.org/repos/asf/ignite/blob/8af30781/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAtomicPeekModesTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAtomicPeekModesTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAtomicPeekModesTest.java
index 4270bab..8b7859a 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAtomicPeekModesTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheAtomicPeekModesTest.java
@@ -48,4 +48,4 @@ public class IgniteCacheAtomicPeekModesTest extends IgniteCachePeekModesAbstract
     @Override protected CacheAtomicWriteOrderMode atomicWriteOrderMode() {
         return PRIMARY;
     }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8af30781/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCachePeekModesAbstractTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCachePeekModesAbstractTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCachePeekModesAbstractTest.java
index c27cccb..5dc059b 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCachePeekModesAbstractTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCachePeekModesAbstractTest.java
@@ -28,6 +28,7 @@ import java.util.Set;
 import javax.cache.Cache;
 import org.apache.ignite.Ignite;
 import org.apache.ignite.IgniteCache;
+import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.cache.CacheMemoryMode;
 import org.apache.ignite.cache.CachePeekMode;
 import org.apache.ignite.cache.affinity.Affinity;
@@ -38,6 +39,7 @@ import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.configuration.NearCacheConfiguration;
 import org.apache.ignite.internal.IgniteEx;
 import org.apache.ignite.internal.IgniteKernal;
+import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.util.typedef.T2;
 import org.apache.ignite.spi.IgniteSpiCloseableIterator;
 import org.apache.ignite.spi.swapspace.SwapSpaceSpi;
@@ -501,6 +503,144 @@ public abstract class IgniteCachePeekModesAbstractTest extends IgniteCacheAbstra
     }
 
     /**
+     * @throws Exception If failed.
+     */
+    public void testLocalPartitionSize() throws Exception {
+        if (cacheMode() != LOCAL)
+            return;
+
+        awaitPartitionMapExchange();
+        checkEmpty();
+        int part = 0;
+        IgniteCache<Integer, String> cache0 = jcache(0);
+
+        IgniteCache<Integer, String> cacheAsync0 = cache0.withAsync();
+
+        for (int i = 0; i < HEAP_ENTRIES; i++) {
+            cache0.put(i, String.valueOf(i));
+
+            final long size = i + 1;
+
+            assertEquals(size, cache0.localSize());
+            assertEquals(size, cache0.localSizeLong(part, PRIMARY));
+            assertEquals(size, cache0.localSizeLong(part, BACKUP));
+            assertEquals(size, cache0.localSizeLong(part, NEAR));
+            assertEquals(size, cache0.localSizeLong(part, ALL));
+
+            assertEquals(size, cache0.size());
+            assertEquals(size, cache0.sizeLong(part, PRIMARY));
+            assertEquals(size, cache0.sizeLong(part, BACKUP));
+            assertEquals(size, cache0.sizeLong(part, NEAR));
+            assertEquals(size, cache0.sizeLong(part, ALL));
+
+            cacheAsync0.size();
+
+            assertEquals(size, (long) cacheAsync0.<Integer>future().get());
+
+            cacheAsync0.sizeLong(part, PRIMARY);
+
+            assertEquals(size, cacheAsync0.future().get());
+        }
+
+        for (int i = 0; i < HEAP_ENTRIES; i++) {
+            cache0.remove(i, String.valueOf(i));
+
+            final int size = HEAP_ENTRIES - i - 1;
+
+            assertEquals(size, cache0.localSize());
+            assertEquals(size, cache0.localSizeLong(part, PRIMARY));
+            assertEquals(size, cache0.localSizeLong(part, BACKUP));
+            assertEquals(size, cache0.localSizeLong(part, NEAR));
+            assertEquals(size, cache0.localSizeLong(part, ALL));
+
+            assertEquals(size, cache0.size());
+            assertEquals(size, cache0.sizeLong(part, PRIMARY));
+            assertEquals(size, cache0.sizeLong(part, BACKUP));
+            assertEquals(size, cache0.sizeLong(part, NEAR));
+            assertEquals(size, cache0.sizeLong(part, ALL));
+
+            cacheAsync0.size();
+
+            assertEquals(size, (long) cacheAsync0.<Integer>future().get());
+        }
+    }
+
+    /**
+     * @throws InterruptedException If failed.
+     */
+    public void testLocalPartitionSizeFlags() throws InterruptedException {
+        if (cacheMode() != LOCAL)
+            return;
+
+        awaitPartitionMapExchange();
+        checkEmpty();
+        int part = 0;
+        IgniteCache<Integer, String> cache0 = jcache(0);
+
+        Set<Integer> keys = new HashSet<>();
+
+        for (int i = 0; i < 200; i++) {
+            cache0.put(i, "test_val");
+
+            keys.add(i);
+        }
+
+        try {
+            int totalKeys = 200;
+
+            T2<Integer, Integer> swapKeys = swapKeysCount(0);
+
+            T2<Integer, Integer> offheapKeys = offheapKeysCount(0);
+
+            int totalSwap = swapKeys.get1() + swapKeys.get2();
+            int totalOffheap = offheapKeys.get1() + offheapKeys.get2();
+
+            log.info("Keys [total=" + totalKeys + ", offheap=" + offheapKeys + ", swap=" + swapKeys + ']');
+
+            assertTrue(totalSwap + totalOffheap < totalKeys);
+
+            assertEquals(totalKeys, cache0.localSize());
+            assertEquals(totalKeys, cache0.localSizeLong(part, ALL));
+
+            assertEquals(totalOffheap, cache0.localSizeLong(part, OFFHEAP));
+            assertEquals(totalSwap, cache0.localSizeLong(part, SWAP));
+            assertEquals(totalKeys - (totalSwap + totalOffheap), cache0.localSizeLong(part, ONHEAP));
+
+            assertEquals(totalOffheap, cache0.sizeLong(part, OFFHEAP));
+            assertEquals(totalSwap, cache0.sizeLong(part, SWAP));
+            assertEquals(totalKeys - (totalSwap + totalOffheap), cache0.sizeLong(part, ONHEAP));
+
+            assertEquals(totalOffheap, cache0.localSizeLong(part, OFFHEAP, PRIMARY));
+            assertEquals(totalSwap, cache0.localSizeLong(part, SWAP, PRIMARY));
+            assertEquals(totalKeys - (totalSwap + totalOffheap), cache0.localSizeLong(part, ONHEAP, PRIMARY));
+
+            assertEquals(totalOffheap, cache0.localSizeLong(part, OFFHEAP, BACKUP));
+            assertEquals(totalSwap, cache0.localSizeLong(part, SWAP, BACKUP));
+            assertEquals(totalKeys - (totalSwap + totalOffheap), cache0.localSizeLong(part, ONHEAP, BACKUP));
+        }
+        finally {
+            cache0.removeAll(keys);
+        }
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testNonLocalPartitionSize() throws Exception {
+        if (cacheMode() == LOCAL)
+            return;
+
+        awaitPartitionMapExchange(true, true);
+
+        checkEmpty();
+
+        for (int i = 0; i < gridCount(); i++) {
+            checkPartitionSizeAffinityFilter(i);
+            checkPartitionSizeStorageFilter(i);
+        }
+    }
+
+    /**
      * @param nodeIdx Node index.
      * @throws Exception If failed.
      */
@@ -627,6 +767,164 @@ public abstract class IgniteCachePeekModesAbstractTest extends IgniteCacheAbstra
     }
 
     /**
+     * @param nodeIdx Node index.
+     * @throws Exception If failed.
+     */
+    private void checkPartitionSizeAffinityFilter(int nodeIdx) throws Exception {
+        IgniteCache<Integer, String> cache0 = jcache(nodeIdx);
+
+        final int PUT_KEYS = 10;
+
+        int part = nodeIdx;
+
+        List<Integer> keys = null;
+
+        try {
+            if (cacheMode() == REPLICATED) {
+                keys = backupKeys(cache0, 10, 0);
+
+                for (Integer key : keys)
+                    cache0.put(key, String.valueOf(key));
+
+                int partSize = 0;
+
+                for (Integer key : keys){
+                    int keyPart = ignite(nodeIdx).affinity(null).partition(key);
+                    if (keyPart == part)
+                        partSize++;
+                }
+
+                assertEquals(PUT_KEYS, cache0.localSize(BACKUP));
+                assertEquals(PUT_KEYS, cache0.localSize(ALL));
+                assertEquals(partSize, cache0.localSizeLong(part, BACKUP));
+                assertEquals(partSize, cache0.localSizeLong(part, ALL));
+                assertEquals(0, cache0.localSizeLong(part, PRIMARY));
+                assertEquals(0, cache0.localSizeLong(part, NEAR));
+
+                for (int i = 0; i < gridCount(); i++) {
+                    IgniteCache<Integer, String> cache = jcache(i);
+                    assertEquals(0, cache.size(NEAR));
+                    assertEquals(partSize, cache.sizeLong(part, PRIMARY));
+                    assertEquals(partSize * (gridCount() - 1), cache.sizeLong(part, BACKUP));
+                    assertEquals(partSize * gridCount(), cache.sizeLong(part, PRIMARY, BACKUP));
+                    assertEquals(partSize * gridCount(), cache.sizeLong(part, ALL)); // Primary + backups.
+                }
+            }
+            else {
+                keys = nearKeys(cache0, PUT_KEYS, 0);
+
+                for (Integer key : keys)
+                    cache0.put(key, String.valueOf(key));
+
+                int partSize = 0;
+
+                for (Integer key :keys){
+                    int keyPart = ignite(nodeIdx).affinity(null).partition(key);
+                    if(keyPart == part)
+                        partSize++;
+                }
+
+                if (hasNearCache()) {
+                    assertEquals(0, cache0.localSize());
+                    assertEquals(0, cache0.localSizeLong(part, ALL));
+                    assertEquals(0, cache0.localSizeLong(part, NEAR));
+
+                    for (int i = 0; i < gridCount(); i++) {
+                        IgniteCache<Integer, String> cache = jcache(i);
+
+                        assertEquals(0, cache.sizeLong(part, NEAR));
+                        assertEquals(partSize, cache.sizeLong(part, BACKUP));
+                        assertEquals(partSize * 2, cache.sizeLong(part, PRIMARY, BACKUP));
+                        assertEquals(partSize * 2, cache.sizeLong(part, ALL)); // Primary + backups + near.
+                    }
+                }
+                else {
+                    assertEquals(0, cache0.localSize());
+                    //assertEquals(partitionSize, cache0.localSizeLong(partition, ALL));
+                    assertEquals(0, cache0.localSizeLong(part, NEAR));
+
+                    for (int i = 0; i < gridCount(); i++) {
+                        IgniteCache<Integer, String> cache = jcache(i);
+
+                        assertEquals(0, cache.size(NEAR));
+                        assertEquals(partSize, cache.sizeLong(part, BACKUP));
+                        assertEquals(partSize * 2, cache.sizeLong(part, PRIMARY, BACKUP));
+                        assertEquals(partSize * 2, cache.sizeLong(part, ALL)); // Primary + backups.
+                    }
+                }
+
+                assertEquals(0, cache0.localSize(BACKUP));
+                assertEquals(0, cache0.localSize(PRIMARY));
+            }
+
+            checkPrimarySize(PUT_KEYS);
+
+            Affinity<Integer> aff = ignite(0).affinity(null);
+
+            for (int i = 0; i < gridCount(); i++) {
+                if (i == nodeIdx)
+                    continue;
+
+                ClusterNode node = ignite(i).cluster().localNode();
+
+                int primary = 0;
+                int backups = 0;
+
+                for (Integer key : keys) {
+                    if (aff.isPrimary(node, key) && aff.partition(key) == part)
+                        primary++;
+                    else if (aff.isBackup(node, key) && aff.partition(key) == part)
+                        backups++;
+                }
+
+                IgniteCache<Integer, String> cache = jcache(i);
+
+                assertEquals(primary, cache.localSizeLong(part, PRIMARY));
+                assertEquals(backups, cache.localSizeLong(part, BACKUP));
+                assertEquals(primary + backups, cache.localSizeLong(part, PRIMARY, BACKUP));
+                assertEquals(primary + backups, cache.localSizeLong(part, BACKUP, PRIMARY));
+                assertEquals(primary + backups, cache.localSizeLong(part, ALL));
+            }
+
+            cache0.remove(keys.get(0));
+
+            keys.remove(0);
+
+            checkPrimarySize(PUT_KEYS - 1);
+
+            int primary = 0;
+            int backups = 0;
+
+            ClusterNode node = ignite(nodeIdx).cluster().localNode();
+
+            for (Integer key : keys) {
+                if (aff.isPrimary(node, key) && aff.partition(key) == part)
+                    primary++;
+                else if (aff.isBackup(node, key) && aff.partition(key) == part)
+                    backups++;
+            }
+
+            if (cacheMode() == REPLICATED) {
+                assertEquals(primary+backups, cache0.localSizeLong(part, ALL));
+                assertEquals(primary, cache0.localSizeLong(part, PRIMARY));
+                assertEquals(backups, cache0.localSizeLong(part, BACKUP));
+            }
+            else {
+                if (hasNearCache())
+                    assertEquals(0, cache0.localSizeLong(part, ALL));
+                else
+                    assertEquals(0, cache0.localSizeLong(part, ALL));
+            }
+        }
+        finally {
+            if (keys != null)
+                cache0.removeAll(new HashSet<>(keys));
+        }
+
+        checkEmpty();
+    }
+
+    /**
      * Checks size is zero.
      */
     private void checkEmpty() {
@@ -695,6 +993,31 @@ public abstract class IgniteCachePeekModesAbstractTest extends IgniteCacheAbstra
 
     /**
      * @param nodeIdx Node index.
+     * @param part Cache partition
+     * @return Tuple with number of primary and backup keys (one or both will be zero).
+     */
+    private T2<Integer, Integer> swapKeysCount(int nodeIdx, int part) throws IgniteCheckedException {
+        GridCacheContext ctx = ((IgniteEx)ignite(nodeIdx)).context().cache().internalCache().context();
+        // Swap and offheap are disabled for near cache.
+        GridCacheSwapManager swapMgr = ctx.isNear() ? ctx.near().dht().context().swap() : ctx.swap();
+        //First count entries...
+        int cnt = (int)swapMgr.swapEntriesCount(part);
+
+        GridCacheAffinityManager affinity = ctx.affinity();
+        AffinityTopologyVersion topVer = affinity.affinityTopologyVersion();
+
+        //And then find out whether they are primary or backup ones.
+        int primaryCnt = 0;
+        int backupCnt = 0;
+        if (affinity.primary(ctx.localNode(), part, topVer))
+            primaryCnt = cnt;
+        else if (affinity.backup(ctx.localNode(), part, topVer))
+            backupCnt = cnt;
+        return new T2<>(primaryCnt, backupCnt);
+    }
+
+    /**
+     * @param nodeIdx Node index.
      * @return Tuple with primary and backup keys.
      */
     private T2<List<Integer>, List<Integer>> offheapKeys(int nodeIdx) {
@@ -742,6 +1065,31 @@ public abstract class IgniteCachePeekModesAbstractTest extends IgniteCacheAbstra
 
     /**
      * @param nodeIdx Node index.
+     * @param part Cache partition.
+     * @return Tuple with number of primary and backup keys (one or both will be zero).
+     */
+    private T2<Integer, Integer> offheapKeysCount(int nodeIdx, int part) throws IgniteCheckedException {
+        GridCacheContext ctx = ((IgniteEx)ignite(nodeIdx)).context().cache().internalCache().context();
+        // Swap and offheap are disabled for near cache.
+        GridCacheSwapManager swapMgr = ctx.isNear() ? ctx.near().dht().context().swap() : ctx.swap();
+        //First count entries...
+        int cnt = (int)swapMgr.offheapEntriesCount(part);
+
+        GridCacheAffinityManager affinity = ctx.affinity();
+        AffinityTopologyVersion topVer = affinity.affinityTopologyVersion();
+
+        //And then find out whether they are primary or backup ones.
+        int primaryCnt = 0;
+        int backupCnt = 0;
+        if (affinity.primary(ctx.localNode(), part, topVer))
+            primaryCnt = cnt;
+        else if (affinity.backup(ctx.localNode(), part, topVer))
+            backupCnt = cnt;
+        return new T2<>(primaryCnt, backupCnt);
+    }
+
+    /**
+     * @param nodeIdx Node index.
      * @throws Exception If failed.
      */
     private void checkSizeStorageFilter(int nodeIdx) throws Exception {
@@ -862,6 +1210,119 @@ public abstract class IgniteCachePeekModesAbstractTest extends IgniteCacheAbstra
     }
 
     /**
+     * @param nodeIdx Node index.
+     * @throws Exception If failed.
+     */
+    private void checkPartitionSizeStorageFilter(int nodeIdx) throws Exception {
+        IgniteCache<Integer, String> cache0 = jcache(nodeIdx);
+
+        int part = nodeIdx;
+
+        List<Integer> primaryKeys = primaryKeys(cache0, 100, 10_000);
+        List<Integer> backupKeys = backupKeys(cache0, 100, 10_000);
+
+        try {
+            final String val = "test_value";
+
+            for (int i = 0; i < 100; i++) {
+                cache0.put(primaryKeys.get(i), val);
+                cache0.put(backupKeys.get(i), val);
+            }
+
+
+            int totalKeys = 200;
+
+            T2<Integer, Integer> swapKeys = swapKeysCount(nodeIdx, part);
+
+            T2<Integer, Integer> offheapKeys = offheapKeysCount(nodeIdx, part);
+
+            int totalSwap = swapKeys.get1() + swapKeys.get2();
+            int totalOffheap = offheapKeys.get1() + offheapKeys.get2();
+
+            log.info("Local keys [total=" + totalKeys + ", offheap=" + offheapKeys + ", swap=" + swapKeys + ']');
+
+            assertTrue(totalSwap + totalOffheap < totalKeys);
+
+            assertEquals(primaryKeys.size(), cache0.localSize());
+            assertEquals(totalKeys, cache0.localSize(ALL));
+            assertEquals(totalOffheap, cache0.localSizeLong(part, PRIMARY, BACKUP, NEAR, OFFHEAP));
+            assertEquals(totalSwap, cache0.localSizeLong(part, PRIMARY, BACKUP, NEAR, SWAP));
+            assertEquals((long)swapKeys.get1(), cache0.localSizeLong(part, SWAP, PRIMARY));
+            assertEquals((long)swapKeys.get2(), cache0.localSizeLong(part, SWAP, BACKUP));
+
+            assertEquals((long)offheapKeys.get1(), cache0.localSizeLong(part, OFFHEAP, PRIMARY));
+            assertEquals((long)offheapKeys.get2(), cache0.localSizeLong(part, OFFHEAP, BACKUP));
+
+            assertEquals(swapKeys.get1() + offheapKeys.get1(), cache0.localSizeLong(part, SWAP, OFFHEAP, PRIMARY));
+            assertEquals(swapKeys.get2() + offheapKeys.get2(), cache0.localSizeLong(part, SWAP, OFFHEAP, BACKUP));
+
+            assertEquals(totalSwap + totalOffheap, cache0.localSizeLong(part, PRIMARY, BACKUP, NEAR, SWAP, OFFHEAP));
+
+            int globalParitionSwapPrimary = 0;
+            int globalPartSwapBackup = 0;
+
+            int globalPartOffheapPrimary = 0;
+            int globalPartOffheapBackup = 0;
+
+            for (int i = 0; i < gridCount(); i++) {
+                T2<Integer, Integer> swap = swapKeysCount(i, part);
+
+                globalParitionSwapPrimary += swap.get1();
+                globalPartSwapBackup += swap.get2();
+
+                T2<Integer, Integer> offheap = offheapKeysCount(i, part);
+
+                globalPartOffheapPrimary += offheap.get1();
+                globalPartOffheapBackup += offheap.get2();
+            }
+
+            int backups;
+
+            if (cacheMode() == LOCAL)
+                backups = 0;
+            else if (cacheMode() == PARTITIONED)
+                backups = 1;
+            else // REPLICATED.
+                backups = gridCount() - 1;
+
+            int globalTotal = totalKeys + totalKeys * backups;
+            int globalPartTotalSwap = globalParitionSwapPrimary + globalPartSwapBackup;
+            int globalPartTotalOffheap = globalPartOffheapPrimary + globalPartOffheapBackup;
+
+            log.info("Global keys [total=" + globalTotal +
+                    ", offheap=" + globalPartTotalOffheap +
+                    ", swap=" + globalPartTotalSwap + ']');
+
+            for (int i = 0; i < gridCount(); i++) {
+                IgniteCache<Integer, String> cache = jcache(i);
+
+                assertEquals(totalKeys, cache.size(PRIMARY));
+                assertEquals(globalTotal, cache.size(ALL));
+                assertEquals(globalTotal, cache.size(PRIMARY, BACKUP, NEAR, ONHEAP, OFFHEAP, SWAP));
+                assertEquals(globalTotal, cache.size(ONHEAP, OFFHEAP, SWAP, PRIMARY, BACKUP));
+
+                assertEquals(globalPartTotalSwap, cache.sizeLong(part, PRIMARY, BACKUP, NEAR, SWAP));
+                assertEquals(globalParitionSwapPrimary, cache.sizeLong(part, SWAP, PRIMARY));
+                assertEquals(globalPartSwapBackup, cache.sizeLong(part, SWAP, BACKUP));
+
+                assertEquals(globalPartTotalOffheap, cache.sizeLong(part, PRIMARY, BACKUP, NEAR, OFFHEAP));
+                assertEquals(globalPartOffheapPrimary, cache.sizeLong(part, OFFHEAP, PRIMARY));
+                assertEquals(globalPartOffheapBackup, cache.sizeLong(part, OFFHEAP, BACKUP));
+
+                assertEquals(globalPartTotalSwap + globalPartTotalOffheap, cache.sizeLong(part, PRIMARY, BACKUP, NEAR, SWAP, OFFHEAP));
+                assertEquals(globalParitionSwapPrimary + globalPartOffheapPrimary, cache.sizeLong(part, SWAP, OFFHEAP, PRIMARY));
+                assertEquals(globalPartSwapBackup + globalPartOffheapBackup, cache.sizeLong(part, SWAP, OFFHEAP, BACKUP));
+            }
+        }
+        finally {
+            cache0.removeAll(new HashSet<>(primaryKeys));
+            cache0.removeAll(new HashSet<>(backupKeys));
+        }
+
+        checkEmpty();
+    }
+
+    /**
      * @param exp Expected size.
      */
     private void checkPrimarySize(int exp) {
@@ -1167,4 +1628,4 @@ public abstract class IgniteCachePeekModesAbstractTest extends IgniteCacheAbstra
 
         assertTrue("Expected entries not found: " + allExp, allExp.isEmpty());
     }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/8af30781/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java b/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
index f2f69dd..36a56f5 100644
--- a/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
+++ b/modules/core/src/test/java/org/apache/ignite/testframework/junits/multijvm/IgniteCacheProcessProxy.java
@@ -207,6 +207,11 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
     }
 
     /** {@inheritDoc} */
+    @Override public long sizeLong(int partition, CachePeekMode... peekModes) throws CacheException {
+        return compute.call(new PartitionSizeLongTask(cacheName, isAsync, peekModes, partition, false));
+    }
+
+    /** {@inheritDoc} */
     @Override public int localSize(CachePeekMode... peekModes) {
         return compute.call(new SizeTask(cacheName, isAsync, peekModes, true));
     }
@@ -217,6 +222,11 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
     }
 
     /** {@inheritDoc} */
+    @Override public long localSizeLong(int partition, CachePeekMode... peekModes) {
+        return compute.call(new PartitionSizeLongTask(cacheName, isAsync, peekModes, partition, true));
+    }
+
+    /** {@inheritDoc} */
     @Override  public <T> Map<K, EntryProcessorResult<T>> invokeAll(
         Map<? extends K, ? extends EntryProcessor<K, V, T>> map,
         Object... args)
@@ -703,6 +713,40 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
     /**
      *
      */
+    private static class PartitionSizeLongTask extends CacheTaskAdapter<Void, Void, Long> {
+
+        /** Partition. */
+        int partition;
+
+        /** Peek modes. */
+        private final CachePeekMode[] peekModes;
+
+        /** Local. */
+        private final boolean loc;
+
+        /**
+         * @param cacheName Cache name.
+         * @param async Async.
+         * @param peekModes Peek modes.
+         * @param partition partition.
+         * @param loc Local.
+         */
+        public PartitionSizeLongTask(String cacheName, boolean async, CachePeekMode[] peekModes, int partition, boolean loc) {
+            super(cacheName, async, null);
+            this.loc = loc;
+            this.peekModes = peekModes;
+            this.partition = partition;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Long call() throws Exception {
+            return loc ? cache().localSizeLong(partition, peekModes) : cache().sizeLong(partition, peekModes);
+        }
+    }
+
+    /**
+     *
+     */
     private static class GetTask<K, V> extends CacheTaskAdapter<K, V, V> {
         /** Key. */
         private final K key;
@@ -1499,4 +1543,4 @@ public class IgniteCacheProcessProxy<K, V> implements IgniteCache<K, V> {
             return async ? cache.withAsync() : cache;
         }
     }
-}
\ No newline at end of file
+}


[17/50] [abbrv] ignite git commit: Clarified READ_COMMITTED behavior in cases when a value is updated inside of a transaction

Posted by vo...@apache.org.
Clarified READ_COMMITTED behavior in cases when a value is updated inside of a transaction


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 005ce0f3d05f529b0a1de64d7f6b59efb6612ee0
Parents: 8af3078
Author: Denis Magda <dm...@gridgain.com>
Authored: Fri Jul 8 12:58:43 2016 +0300
Committer: Denis Magda <dm...@gridgain.com>
Committed: Fri Jul 8 12:58:43 2016 +0300

----------------------------------------------------------------------
 .../main/java/org/apache/ignite/transactions/Transaction.java   | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/005ce0f3/modules/core/src/main/java/org/apache/ignite/transactions/Transaction.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/transactions/Transaction.java b/modules/core/src/main/java/org/apache/ignite/transactions/Transaction.java
index e2e7100..450b626 100644
--- a/modules/core/src/main/java/org/apache/ignite/transactions/Transaction.java
+++ b/modules/core/src/main/java/org/apache/ignite/transactions/Transaction.java
@@ -38,7 +38,10 @@ import org.apache.ignite.lang.IgniteUuid;
  *  will be provided for read operations. With this isolation level values are always read
  *  from cache global memory or persistent store every time a value is accessed. In other words,
  *  if the same key is accessed more than once within the same transaction, it may have different
- *  value every time since global cache memory may be updated concurrently by other threads.
+ *  value every time since global cache memory may be updated concurrently by other threads. However note that if an
+ *  update happens inside of a transaction then the new value belonging to a key will be stored in the local
+ *  transactional map and all subsequent reads using the key will return this new value avoiding requests to global
+ *  cache memory.
  * </li>
  * <li>
  *  {@link TransactionIsolation#REPEATABLE_READ} isolation level means that if a value was read once


[39/50] [abbrv] ignite git commit: Merge branch 'gridgain-7.5.30' into ignite-1849

Posted by vo...@apache.org.
Merge branch 'gridgain-7.5.30' into ignite-1849


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

Branch: refs/heads/ignite-1.5.31-1
Commit: b81dbbf23b7941bfbaac18ce9004ef06b0f1f4f8
Parents: 5ae31fa 448571b
Author: Alexander Paschenko <al...@gmail.com>
Authored: Tue Jul 19 19:55:11 2016 +0300
Committer: Alexander Paschenko <al...@gmail.com>
Committed: Tue Jul 19 19:55:11 2016 +0300

----------------------------------------------------------------------
 .../ignite/internal/binary/BinaryContext.java   |   6 +-
 .../internal/binary/BinaryObjectImpl.java       |   8 +
 .../internal/binary/GridBinaryMarshaller.java   |  11 +-
 .../GridAffinityFunctionContextImpl.java        |   9 +
 .../processors/cache/GridCacheProcessor.java    |  65 +-
 .../affinity/PlatformAffinityFunction.java      | 277 ++++++
 .../PlatformAffinityFunctionTarget.java         | 113 +++
 .../cache/affinity/PlatformAffinityUtils.java   | 116 +++
 .../callback/PlatformCallbackGateway.java       |  89 ++
 .../callback/PlatformCallbackUtils.java         |  49 ++
 .../PlatformDotNetConfigurationClosure.java     | 115 ++-
 .../dotnet/PlatformDotNetAffinityFunction.java  | 171 ++++
 .../binary/BinaryMarshallerSelfTest.java        |  41 +
 .../processors/igfs/IgfsIgniteMock.java         | 492 +++++++++++
 .../internal/processors/igfs/IgfsMock.java      | 397 +++++++++
 .../mapreduce/IgniteHadoopMapReducePlanner.java |  48 +-
 .../IgniteHadoopWeightedMapReducePlanner.java   | 846 +++++++++++++++++++
 .../internal/processors/hadoop/HadoopUtils.java |  81 ++
 .../planner/HadoopAbstractMapReducePlanner.java | 116 +++
 .../planner/HadoopMapReducePlanGroup.java       | 150 ++++
 .../planner/HadoopMapReducePlanTopology.java    |  89 ++
 .../HadoopDefaultMapReducePlannerSelfTest.java  | 451 +---------
 .../processors/hadoop/HadoopMapReduceTest.java  |  16 +-
 .../processors/hadoop/HadoopPlannerMockJob.java | 168 ++++
 .../HadoopWeightedMapReducePlannerTest.java     | 599 +++++++++++++
 .../HadoopWeightedPlannerMapReduceTest.java     |  38 +
 .../testsuites/IgniteHadoopTestSuite.java       |   8 +-
 .../cpp/common/include/ignite/common/java.h     |  18 +
 modules/platforms/cpp/common/src/java.cpp       |  36 +-
 .../Apache.Ignite.Core.Tests.csproj             |   9 +-
 .../Affinity/AffinityFunctionSpringTest.cs      | 184 ++++
 .../Config/Cache/Affinity/affinity-function.xml | 129 +++
 .../Cache/Affinity/affinity-function2.xml       |  49 ++
 .../Apache.Ignite.Core.Tests/TestRunner.cs      |   3 +-
 .../Apache.Ignite.Core.csproj                   |  14 +-
 .../Cache/Affinity/AffinityFunctionContext.cs   | 120 +++
 .../Cache/Affinity/AffinityTopologyVersion.cs   | 138 +++
 .../Cache/Affinity/Fair/FairAffinityFunction.cs |  33 +
 .../Cache/Affinity/Fair/Package-Info.cs         |  26 +
 .../Cache/Affinity/IAffinityFunction.cs         |  82 ++
 .../Cache/Affinity/Package-Info.cs              |  26 +
 .../Cache/Affinity/Rendezvous/Package-Info.cs   |  26 +
 .../Rendezvous/RendezvousAffinityFunction.cs    |  32 +
 .../Apache.Ignite.Core/Events/EventReader.cs    |   8 +-
 .../dotnet/Apache.Ignite.Core/Ignition.cs       |  38 +-
 .../Impl/Binary/BinaryReaderExtensions.cs       |  14 +
 .../Impl/Binary/Marshaller.cs                   |   6 +-
 .../Impl/Cache/Affinity/AffinityFunctionBase.cs | 140 +++
 .../Affinity/AffinityFunctionSerializer.cs      | 277 ++++++
 .../Cache/Affinity/PlatformAffinityFunction.cs  |  74 ++
 .../Impl/Common/ObjectInfoHolder.cs             |  86 ++
 .../Apache.Ignite.Core/Impl/IgniteUtils.cs      |  10 +-
 .../Impl/Unmanaged/UnmanagedCallbackHandlers.cs |   6 +
 .../Impl/Unmanaged/UnmanagedCallbacks.cs        | 133 ++-
 54 files changed, 5756 insertions(+), 530 deletions(-)
----------------------------------------------------------------------



[45/50] [abbrv] ignite git commit: IGNITE-2649: Ensured correct local Ignite instance processing during serialization and deserialization.

Posted by vo...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
index 7f0e230..0066368 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/IgniteH2Indexing.java
@@ -76,6 +76,7 @@ import org.apache.ignite.lang.IgniteBiPredicate;
 import org.apache.ignite.lang.IgniteBiTuple;
 import org.apache.ignite.lang.IgniteFuture;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.resources.LoggerResource;
 import org.apache.ignite.spi.IgniteSpiCloseableIterator;
@@ -1535,13 +1536,19 @@ public class IgniteH2Indexing implements GridQueryIndexing {
     protected JavaObjectSerializer h2Serializer() {
         return new JavaObjectSerializer() {
                 @Override public byte[] serialize(Object obj) throws Exception {
-                    return marshaller.marshal(obj);
+                    if (ctx != null)
+                        return MarshallerUtils.marshal(ctx, obj);
+                    else
+                        return marshaller.marshal(obj);
                 }
 
                 @Override public Object deserialize(byte[] bytes) throws Exception {
-                    ClassLoader clsLdr = ctx != null ? U.resolveClassLoader(ctx.config()) : null;
-
-                    return marshaller.unmarshal(bytes, clsLdr);
+                    if (ctx != null) {
+                        return MarshallerUtils.unmarshal(ctx.gridName(), marshaller, bytes,
+                            U.resolveClassLoader(ctx.config()));
+                    }
+                    else
+                        return marshaller.unmarshal(bytes, null);
                 }
             };
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
index 47ab083..1fa3368 100644
--- a/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
+++ b/modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/twostep/GridReduceQueryExecutor.java
@@ -564,7 +564,7 @@ public class GridReduceQueryExecutor {
                     Marshaller m = ctx.config().getMarshaller();
 
                     for (GridCacheSqlQuery mapQry : mapQrys)
-                        mapQry.marshallParams(m);
+                        mapQry.marshallParams(m, ctx);
                 }
 
                 boolean retry = false;

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/web/src/main/java/org/apache/ignite/cache/websession/WebSessionFilter.java
----------------------------------------------------------------------
diff --git a/modules/web/src/main/java/org/apache/ignite/cache/websession/WebSessionFilter.java b/modules/web/src/main/java/org/apache/ignite/cache/websession/WebSessionFilter.java
index 2b7442f..17c0a29 100644
--- a/modules/web/src/main/java/org/apache/ignite/cache/websession/WebSessionFilter.java
+++ b/modules/web/src/main/java/org/apache/ignite/cache/websession/WebSessionFilter.java
@@ -514,8 +514,10 @@ public class WebSessionFilter implements Filter {
                 try {
                     final WebSessionEntity entity = binaryCache.get(sesId);
 
-                    if (entity != null)
-                        cached = new WebSessionV2(sesId, httpReq.getSession(false), false, ctx, entity, marshaller);
+                    if (entity != null) {
+                        cached = new WebSessionV2(sesId, httpReq.getSession(false), false, ctx, entity, marshaller,
+                            webSesIgnite.name());
+                    }
 
                     break;
                 }
@@ -698,7 +700,7 @@ public class WebSessionFilter implements Filter {
         if (log.isDebugEnabled())
             log.debug("Session created: " + sesId);
 
-        WebSessionV2 cached = new WebSessionV2(sesId, ses, true, ctx, null, marshaller);
+        WebSessionV2 cached = new WebSessionV2(sesId, ses, true, ctx, null, marshaller, webSesIgnite.name());
 
         final WebSessionEntity marshaledEntity = cached.marshalAttributes();
 
@@ -710,9 +712,9 @@ public class WebSessionFilter implements Filter {
                 final WebSessionEntity old = cache0.getAndPutIfAbsent(sesId, marshaledEntity);
 
                 if (old != null)
-                    cached = new WebSessionV2(sesId, ses, false, ctx, old, marshaller);
+                    cached = new WebSessionV2(sesId, ses, false, ctx, old, marshaller, webSesIgnite.name());
                 else
-                    cached = new WebSessionV2(sesId, ses, false, ctx, marshaledEntity, marshaller);
+                    cached = new WebSessionV2(sesId, ses, false, ctx, marshaledEntity, marshaller, webSesIgnite.name());
 
                 break;
             }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/web/src/main/java/org/apache/ignite/cache/websession/WebSessionV2.java
----------------------------------------------------------------------
diff --git a/modules/web/src/main/java/org/apache/ignite/cache/websession/WebSessionV2.java b/modules/web/src/main/java/org/apache/ignite/cache/websession/WebSessionV2.java
index b6540b2..2e2531d 100644
--- a/modules/web/src/main/java/org/apache/ignite/cache/websession/WebSessionV2.java
+++ b/modules/web/src/main/java/org/apache/ignite/cache/websession/WebSessionV2.java
@@ -23,6 +23,7 @@ import org.apache.ignite.internal.util.tostring.GridToStringExclude;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.websession.WebSessionEntity;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.jetbrains.annotations.Nullable;
 
 import javax.servlet.ServletContext;
@@ -87,13 +88,16 @@ class WebSessionV2 implements HttpSession {
     /** Original session to delegate invalidation. */
     private final HttpSession genuineSes;
 
+    /** Ignite config. */
+    private final String gridName;
+
     /**
      * @param id Session ID.
      * @param ses Session.
      * @param isNew Is new flag.
      */
     WebSessionV2(final String id, final @Nullable HttpSession ses, final boolean isNew, final ServletContext ctx,
-        @Nullable WebSessionEntity entity, final Marshaller marshaller) {
+        @Nullable WebSessionEntity entity, final Marshaller marshaller, final String gridName) {
         assert id != null;
         assert marshaller != null;
         assert ctx != null;
@@ -103,6 +107,7 @@ class WebSessionV2 implements HttpSession {
         this.ctx = ctx;
         this.isNew = isNew;
         this.genuineSes = ses;
+        this.gridName = gridName;
 
         accessTime = System.currentTimeMillis();
 
@@ -333,7 +338,7 @@ class WebSessionV2 implements HttpSession {
     @Nullable private <T> T unmarshal(final byte[] bytes) throws IOException {
         if (marshaller != null) {
             try {
-                return marshaller.unmarshal(bytes, getClass().getClassLoader());
+                return MarshallerUtils.unmarshal(gridName, marshaller, bytes, getClass().getClassLoader());
             }
             catch (IgniteCheckedException e) {
                 throw new IOException(e);
@@ -353,7 +358,7 @@ class WebSessionV2 implements HttpSession {
     @Nullable private byte[] marshal(final Object obj) throws IOException {
         if (marshaller != null) {
             try {
-                return marshaller.marshal(obj);
+                return MarshallerUtils.marshal(gridName, marshaller, obj);
             }
             catch (IgniteCheckedException e) {
                 throw new IOException(e);


[22/50] [abbrv] ignite git commit: ignite-3413 Use cache node filter for continuous query registration

Posted by vo...@apache.org.
ignite-3413 Use cache node filter for continuous query registration


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 89d64e74b697054a88c3a91433aaaf4f7fdd0284
Parents: a056954
Author: sboikov <sb...@gridgain.com>
Authored: Wed Jul 13 12:41:18 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Wed Jul 13 12:41:18 2016 +0300

----------------------------------------------------------------------
 .../continuous/CacheContinuousQueryManager.java |   4 +-
 ...eContinuousQueryMultiNodesFilteringTest.java | 278 +++++++++++++++++++
 ...dCacheContinuousQueryNodesFilteringTest.java | 168 +++++++++++
 .../IgniteCacheQuerySelfTestSuite3.java         |   4 +
 4 files changed, 453 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/89d64e74/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java
index c966527..195f3ae 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java
@@ -642,7 +642,9 @@ public class CacheContinuousQueryManager extends GridCacheManagerAdapter {
         hnd.localCache(cctx.isLocal());
 
         IgnitePredicate<ClusterNode> pred = (loc || cctx.config().getCacheMode() == CacheMode.LOCAL) ?
-            F.nodeForNodeId(cctx.localNodeId()) : F.<ClusterNode>alwaysTrue();
+            F.nodeForNodeId(cctx.localNodeId()) : cctx.config().getNodeFilter();
+
+        assert pred != null : cctx.config();
 
         UUID id = cctx.kernalContext().continuous().startRoutine(
             hnd,

http://git-wip-us.apache.org/repos/asf/ignite/blob/89d64e74/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryMultiNodesFilteringTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryMultiNodesFilteringTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryMultiNodesFilteringTest.java
new file mode 100644
index 0000000..7000446
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryMultiNodesFilteringTest.java
@@ -0,0 +1,278 @@
+/*
+ * 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.query.continuous;
+
+import java.util.Collections;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import javax.cache.configuration.Factory;
+import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
+import javax.cache.event.CacheEntryCreatedListener;
+import javax.cache.event.CacheEntryEvent;
+import javax.cache.event.CacheEntryEventFilter;
+import javax.cache.event.CacheEntryListener;
+import javax.cache.event.CacheEntryListenerException;
+import javax.cache.event.CacheEntryRemovedListener;
+import javax.cache.event.CacheEntryUpdatedListener;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.cache.query.ContinuousQuery;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.util.lang.GridAbsPredicate;
+import org.apache.ignite.lang.IgnitePredicate;
+import org.apache.ignite.resources.IgniteInstanceResource;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.jsr166.ConcurrentHashMap8;
+
+import static org.apache.ignite.cache.CacheMode.PARTITIONED;
+import static org.apache.ignite.cache.CacheMode.REPLICATED;
+
+/** */
+@SuppressWarnings("unchecked")
+public class GridCacheContinuousQueryMultiNodesFilteringTest extends GridCommonAbstractTest {
+    /** */
+    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
+
+    /** */
+    private static final int SERVER_GRIDS_COUNT = 6;
+
+    /** Cache entry operations' counts. */
+    private static final ConcurrentMap<String, AtomicInteger> opCounts = new ConcurrentHashMap8<>();
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopAllGrids();
+
+        super.afterTest();
+    }
+
+    /** */
+    public void testFiltersAndListeners() throws Exception {
+        for (int i = 1; i <= SERVER_GRIDS_COUNT; i++)
+            startGrid(i, false);
+
+        startGrid(SERVER_GRIDS_COUNT + 1, true);
+
+        for (int i = 1; i <= SERVER_GRIDS_COUNT + 1; i++) {
+            for (int j = 0; j < i; j++) {
+                jcache(i, "part" + i).put("k" + j, "v0");
+                jcache(i, "repl" + i).put("k" + j, "v0");
+
+                // Should trigger updates
+                jcache(i, "part" + i).put("k" + j, "v1");
+                jcache(i, "repl" + i).put("k" + j, "v1");
+
+                jcache(i, "part" + i).remove("k" + j);
+                jcache(i, "repl" + i).remove("k" + j);
+            }
+        }
+
+        for (int i = 1; i <= SERVER_GRIDS_COUNT + 1; i++) {
+            // For each i, we did 3 ops on 2 caches on i keys, hence expected number.
+            final int expTotal = i * 3 * 2;
+            final int i0 = i;
+
+            GridTestUtils.waitForCondition(new GridAbsPredicate() {
+                @Override public boolean apply() {
+                    return opCounts.get("qry"  + i0 + "_total").get() == expTotal;
+                }
+            }, 5000);
+
+            int partInserts = opCounts.get("part" + i + "_ins").get();
+            int replInserts = opCounts.get("repl" + i + "_ins").get();
+            int partUpdates = opCounts.get("part" + i + "_upd").get();
+            int replUpdates = opCounts.get("repl" + i + "_upd").get();
+            int partRemoves = opCounts.get("part" + i + "_rmv").get();
+            int replRemoves = opCounts.get("repl" + i + "_rmv").get();
+            int totalQryOps = opCounts.get("qry"  + i + "_total").get();
+
+            assertEquals(i, partInserts);
+            assertEquals(i, replInserts);
+
+            assertEquals(i, partUpdates);
+            assertEquals(i, replUpdates);
+
+            assertEquals(i, partRemoves);
+            assertEquals(i, replRemoves);
+
+            assertEquals(expTotal, totalQryOps);
+
+            assertEquals(totalQryOps, partInserts + replInserts + partUpdates + replUpdates + partRemoves + replRemoves);
+        }
+    }
+
+    /** */
+    private Ignite startGrid(final int idx, boolean isClientMode) throws Exception {
+        String gridName = getTestGridName(idx);
+
+        IgniteConfiguration cfg = optimize(getConfiguration(gridName)).setClientMode(isClientMode);
+
+        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(IP_FINDER);
+
+        cfg.setUserAttributes(Collections.singletonMap("idx", idx));
+
+        Ignite node = startGrid(gridName, cfg);
+
+        IgnitePredicate<ClusterNode> nodeFilter = new NodeFilter(idx);
+
+        String partCacheName = "part" + idx;
+
+        IgniteCache partCache = node.createCache(defaultCacheConfiguration().setName("part" + idx)
+            .setCacheMode(PARTITIONED).setBackups(1).setNodeFilter(nodeFilter));
+
+        opCounts.put(partCacheName + "_ins", new AtomicInteger());
+        opCounts.put(partCacheName + "_upd", new AtomicInteger());
+        opCounts.put(partCacheName + "_rmv", new AtomicInteger());
+
+        partCache.registerCacheEntryListener(new ListenerConfiguration(partCacheName, ListenerConfiguration.Op.INSERT));
+        partCache.registerCacheEntryListener(new ListenerConfiguration(partCacheName, ListenerConfiguration.Op.UPDATE));
+        partCache.registerCacheEntryListener(new ListenerConfiguration(partCacheName, ListenerConfiguration.Op.REMOVE));
+
+        String replCacheName = "repl" + idx;
+
+        IgniteCache replCache = node.createCache(defaultCacheConfiguration().setName("repl" + idx)
+            .setCacheMode(REPLICATED).setNodeFilter(nodeFilter));
+
+        opCounts.put(replCacheName + "_ins", new AtomicInteger());
+        opCounts.put(replCacheName + "_upd", new AtomicInteger());
+        opCounts.put(replCacheName + "_rmv", new AtomicInteger());
+
+        replCache.registerCacheEntryListener(new ListenerConfiguration(replCacheName, ListenerConfiguration.Op.INSERT));
+        replCache.registerCacheEntryListener(new ListenerConfiguration(replCacheName, ListenerConfiguration.Op.UPDATE));
+        replCache.registerCacheEntryListener(new ListenerConfiguration(replCacheName, ListenerConfiguration.Op.REMOVE));
+
+        opCounts.put("qry" + idx + "_total", new AtomicInteger());
+
+        ContinuousQuery qry = new ContinuousQuery();
+        qry.setRemoteFilterFactory(new EntryEventFilterFactory(idx));
+        qry.setLocalListener(new CacheEntryUpdatedListener() {
+            /** {@inheritDoc} */
+            @Override public void onUpdated(Iterable evts) {
+                opCounts.get("qry" + idx + "_total").incrementAndGet();
+            }
+        });
+
+        partCache.query(qry);
+        replCache.query(qry);
+
+        return node;
+    }
+
+    /** */
+    private final static class ListenerConfiguration extends MutableCacheEntryListenerConfiguration {
+        /** Operation. */
+        enum Op {
+            /** Insert. */
+            INSERT,
+
+            /** Update. */
+            UPDATE,
+
+            /** Remove. */
+            REMOVE
+        }
+
+        /** */
+        ListenerConfiguration(final String cacheName, final Op op) {
+            super(new Factory<CacheEntryListener>() {
+                /** {@inheritDoc} */
+                @Override public CacheEntryListener create() {
+                    switch (op) {
+                        case INSERT:
+                            return new CacheEntryCreatedListener() {
+                                /** {@inheritDoc} */
+                                @Override public void onCreated(Iterable iterable) {
+                                    for (Object evt : iterable)
+                                        opCounts.get(cacheName + "_ins").getAndIncrement();
+                                }
+                            };
+                        case UPDATE:
+                            return new CacheEntryUpdatedListener() {
+                                /** {@inheritDoc} */
+                                @Override public void onUpdated(Iterable iterable) {
+                                    for (Object evt : iterable)
+                                        opCounts.get(cacheName + "_upd").getAndIncrement();
+                                }
+                            };
+                        case REMOVE:
+                            return new CacheEntryRemovedListener() {
+                                /** {@inheritDoc} */
+                                @Override public void onRemoved(Iterable iterable) {
+                                    for (Object evt : iterable)
+                                        opCounts.get(cacheName + "_rmv").getAndIncrement();
+                                }
+                            };
+                        default:
+                            throw new IgniteException(new IllegalArgumentException());
+                    }
+                }
+            }, null, true, false);
+        }
+    }
+
+    /** */
+    private final static class EntryEventFilterFactory implements Factory<CacheEntryEventFilter> {
+        /** */
+        @IgniteInstanceResource
+        private Ignite ignite;
+
+        /** Grid index to determine whether node filter has been invoked. */
+        private final int idx;
+
+        /** */
+        private EntryEventFilterFactory(int idx) {
+            this.idx = idx;
+        }
+
+        /** {@inheritDoc} */
+        @Override public CacheEntryEventFilter create() {
+            return new CacheEntryEventFilter() {
+                /** {@inheritDoc} */
+                @Override public boolean evaluate(CacheEntryEvent evt) throws CacheEntryListenerException {
+                    int evtNodeIdx = (Integer)(ignite.cluster().localNode().attributes().get("idx"));
+
+                    assertTrue(evtNodeIdx % 2 == idx % 2);
+
+                    return true;
+                }
+            };
+        }
+    }
+
+    /** */
+    private final static class NodeFilter implements IgnitePredicate<ClusterNode> {
+        /** */
+        private final int idx;
+
+        /** */
+        private NodeFilter(int idx) {
+            this.idx = idx;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean apply(ClusterNode clusterNode) {
+            return ((Integer)clusterNode.attributes().get("idx") % 2) == idx % 2;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/89d64e74/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryNodesFilteringTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryNodesFilteringTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryNodesFilteringTest.java
new file mode 100644
index 0000000..dccde65
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryNodesFilteringTest.java
@@ -0,0 +1,168 @@
+/*
+ * 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.query.continuous;
+
+import java.io.Serializable;
+import java.util.Collections;
+import javax.cache.configuration.Factory;
+import javax.cache.event.CacheEntryEvent;
+import javax.cache.event.CacheEntryEventFilter;
+import javax.cache.event.CacheEntryUpdatedListener;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.cache.query.ContinuousQuery;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.lang.IgnitePredicate;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.GridStringLogger;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+/** */
+@SuppressWarnings("unused")
+public class GridCacheContinuousQueryNodesFilteringTest extends GridCommonAbstractTest implements Serializable {
+    /** */
+    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
+
+    /** */
+    private static final String ENTRY_FILTER_CLS_NAME = "org.apache.ignite.tests.p2p.CacheDeploymentEntryEventFilter";
+
+    /**
+     * Tests that node not matched by filter really does not try to participate in the query.
+     *
+     * @throws Exception if failed.
+     */
+    @SuppressWarnings("EmptyTryBlock")
+    public void testNodeWithoutAttributeExclusion() throws Exception {
+        try (Ignite node1 = startNodeWithCache()) {
+            try (Ignite node2 = startGrid("node2", getConfiguration("node2", false, null))) {
+                assertEquals(2, node2.cluster().nodes().size());
+            }
+        }
+    }
+
+    /**
+     * Test that node matched by filter and having filter instantiation problems fails for sure.
+     *
+     * @throws Exception if failed.
+     */
+    public void testNodeWithAttributeFailure() throws Exception {
+        try (Ignite node1 = startNodeWithCache()) {
+            GridStringLogger log = new GridStringLogger();
+
+            try (Ignite node2 = startGrid("node2", getConfiguration("node2", true, log))) {
+                fail();
+            }
+            catch (IgniteException e) {
+                assertTrue(log.toString().contains("Class not found for continuous query remote filter " +
+                    "[name=org.apache.ignite.tests.p2p.CacheDeploymentEntryEventFilter]"));
+            }
+        }
+    }
+
+    /**
+     * Start first, attribute-bearing, node, create new cache and launch continuous query on it.
+     *
+     * @return Node.
+     * @throws Exception if failed.
+     */
+    private Ignite startNodeWithCache() throws Exception {
+        Ignite node1 = startGrid("node1", getConfiguration("node1", true, null));
+
+        CacheConfiguration<Integer, Integer> ccfg = new CacheConfiguration<>();
+        ccfg.setName("attrsTestCache");
+        ccfg.setNodeFilter(new IgnitePredicate<ClusterNode>() {
+            /** {@inheritDoc} */
+            @Override public boolean apply(ClusterNode node) {
+                return "data".equals(node.attribute("node-type"));
+            }
+        });
+
+        IgniteCache<Integer, Integer> cache = node1.createCache(ccfg);
+
+        ContinuousQuery<Integer, Integer> qry = new ContinuousQuery<>();
+
+        qry.setRemoteFilterFactory(new RemoteFilterFactory());
+        qry.setLocalListener(new CacheEntryUpdatedListener<Integer, Integer>() {
+            /** {@inheritDoc} */
+            @Override public void onUpdated(Iterable<CacheEntryEvent<? extends Integer, ? extends Integer>> evts) {
+                // No-op.
+            }
+        });
+
+        RemoteFilterFactory.clsLdr = getExternalClassLoader();
+
+        cache.query(qry);
+
+        // Switch class loader before starting the second node.
+        RemoteFilterFactory.clsLdr = getClass().getClassLoader();
+
+        return node1;
+    }
+
+    /**
+     * @param name Node name.
+     * @param setAttr Flag indicating whether node user attribute should be set.
+     * @param log Logger.
+     * @return Node configuration w/specified name.
+     * @throws Exception If failed.
+     */
+    private IgniteConfiguration getConfiguration(String name, boolean setAttr, GridStringLogger log) throws Exception {
+        IgniteConfiguration cfg = optimize(getConfiguration(name));
+
+        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(IP_FINDER);
+
+        if (setAttr)
+            cfg.setUserAttributes(Collections.singletonMap("node-type", "data"));
+
+        cfg.setGridLogger(log);
+
+        return cfg;
+    }
+
+    /**
+     *
+     */
+    private static class RemoteFilterFactory implements Factory<CacheEntryEventFilter<Integer, Integer>> {
+        /** */
+        private static ClassLoader clsLdr;
+
+        /** {@inheritDoc} */
+        @SuppressWarnings("unchecked")
+        @Override public CacheEntryEventFilter<Integer, Integer> create() {
+            try {
+                Class<?> filterCls = clsLdr.loadClass(ENTRY_FILTER_CLS_NAME);
+
+                assert CacheEntryEventFilter.class.isAssignableFrom(filterCls);
+
+                return ((Class<CacheEntryEventFilter>)filterCls).newInstance();
+            }
+            catch (ClassNotFoundException e) {
+                throw new IgniteException("Class not found for continuous query remote filter [name=" +
+                    e.getMessage() + "]");
+            }
+            catch (Exception e) { // We really don't expect anything else fancy here.
+                throw new AssertionError("Unexpected exception", e);
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/89d64e74/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheQuerySelfTestSuite3.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheQuerySelfTestSuite3.java b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheQuerySelfTestSuite3.java
index a1a32a1..abf4ac3 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheQuerySelfTestSuite3.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheQuerySelfTestSuite3.java
@@ -43,6 +43,8 @@ import org.apache.ignite.internal.processors.cache.query.continuous.GridCacheCon
 import org.apache.ignite.internal.processors.cache.query.continuous.GridCacheContinuousQueryConcurrentTest;
 import org.apache.ignite.internal.processors.cache.query.continuous.GridCacheContinuousQueryLocalAtomicSelfTest;
 import org.apache.ignite.internal.processors.cache.query.continuous.GridCacheContinuousQueryLocalSelfTest;
+import org.apache.ignite.internal.processors.cache.query.continuous.GridCacheContinuousQueryMultiNodesFilteringTest;
+import org.apache.ignite.internal.processors.cache.query.continuous.GridCacheContinuousQueryNodesFilteringTest;
 import org.apache.ignite.internal.processors.cache.query.continuous.GridCacheContinuousQueryPartitionAtomicOneNodeTest;
 import org.apache.ignite.internal.processors.cache.query.continuous.GridCacheContinuousQueryPartitionTxOneNodeTest;
 import org.apache.ignite.internal.processors.cache.query.continuous.GridCacheContinuousQueryPartitionedOnlySelfTest;
@@ -115,6 +117,8 @@ public class IgniteCacheQuerySelfTestSuite3 extends TestSuite {
         suite.addTestSuite(CacheContinuousQueryExecuteInPrimaryTest.class);
         suite.addTestSuite(CacheContinuousQueryLostPartitionTest.class);
         suite.addTestSuite(ContinuousQueryRemoteFilterMissingInClassPathSelfTest.class);
+        suite.addTestSuite(GridCacheContinuousQueryNodesFilteringTest.class);
+        suite.addTestSuite(GridCacheContinuousQueryMultiNodesFilteringTest.class);
         suite.addTestSuite(IgniteCacheContinuousQueryImmutableEntryTest.class);
         suite.addTestSuite(CacheKeepBinaryIterationTest.class);
         suite.addTestSuite(CacheKeepBinaryIterationStoreEnabledTest.class);


[37/50] [abbrv] ignite git commit: IGNITE-3414: Hadoop: implemented new weight-based map-reduce planner.

Posted by vo...@apache.org.
IGNITE-3414: Hadoop: implemented new weight-based map-reduce planner.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 736493865c1e3a56f864a01583d38e50d02b2c56
Parents: 5f57cc8
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Tue Jul 19 15:16:21 2016 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Tue Jul 19 15:16:21 2016 +0300

----------------------------------------------------------------------
 .../processors/igfs/IgfsIgniteMock.java         | 492 +++++++++++
 .../internal/processors/igfs/IgfsMock.java      | 397 +++++++++
 .../mapreduce/IgniteHadoopMapReducePlanner.java |  48 +-
 .../IgniteHadoopWeightedMapReducePlanner.java   | 846 +++++++++++++++++++
 .../internal/processors/hadoop/HadoopUtils.java |  81 ++
 .../planner/HadoopAbstractMapReducePlanner.java | 116 +++
 .../planner/HadoopMapReducePlanGroup.java       | 150 ++++
 .../planner/HadoopMapReducePlanTopology.java    |  89 ++
 .../HadoopDefaultMapReducePlannerSelfTest.java  | 451 +---------
 .../processors/hadoop/HadoopMapReduceTest.java  |  16 +-
 .../processors/hadoop/HadoopPlannerMockJob.java | 168 ++++
 .../HadoopWeightedMapReducePlannerTest.java     | 599 +++++++++++++
 .../HadoopWeightedPlannerMapReduceTest.java     |  38 +
 .../testsuites/IgniteHadoopTestSuite.java       |   8 +-
 14 files changed, 3022 insertions(+), 477 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsIgniteMock.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsIgniteMock.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsIgniteMock.java
new file mode 100644
index 0000000..0c55595
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsIgniteMock.java
@@ -0,0 +1,492 @@
+/*
+ * 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.igfs;
+
+import org.apache.ignite.IgniteAtomicLong;
+import org.apache.ignite.IgniteAtomicReference;
+import org.apache.ignite.IgniteAtomicSequence;
+import org.apache.ignite.IgniteAtomicStamped;
+import org.apache.ignite.IgniteBinary;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.IgniteCompute;
+import org.apache.ignite.IgniteCountDownLatch;
+import org.apache.ignite.IgniteDataStreamer;
+import org.apache.ignite.IgniteEvents;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.IgniteFileSystem;
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.IgniteMessaging;
+import org.apache.ignite.IgniteQueue;
+import org.apache.ignite.IgniteScheduler;
+import org.apache.ignite.IgniteSemaphore;
+import org.apache.ignite.IgniteServices;
+import org.apache.ignite.IgniteSet;
+import org.apache.ignite.IgniteTransactions;
+import org.apache.ignite.cache.affinity.Affinity;
+import org.apache.ignite.cluster.ClusterGroup;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.CollectionConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.configuration.NearCacheConfiguration;
+import org.apache.ignite.internal.GridKernalContext;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.cluster.IgniteClusterEx;
+import org.apache.ignite.internal.processors.cache.GridCacheUtilityKey;
+import org.apache.ignite.internal.processors.cache.IgniteInternalCache;
+import org.apache.ignite.internal.processors.hadoop.Hadoop;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.lang.IgnitePredicate;
+import org.apache.ignite.lang.IgniteProductVersion;
+import org.apache.ignite.plugin.IgnitePlugin;
+import org.apache.ignite.plugin.PluginNotFoundException;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.concurrent.ExecutorService;
+
+/**
+ * Mocked Ignite implementation for IGFS tests.
+ */
+public class IgfsIgniteMock implements IgniteEx {
+    /** Name. */
+    private final String name;
+
+    /** IGFS. */
+    private final IgniteFileSystem igfs;
+
+    /**
+     * Constructor.
+     *
+     * @param igfs IGFS instance.
+     */
+    public IgfsIgniteMock(@Nullable String name, IgniteFileSystem igfs) {
+        this.name = name;
+        this.igfs = igfs;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K extends GridCacheUtilityKey, V> IgniteInternalCache<K, V> utilityCache() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <K, V> IgniteInternalCache<K, V> cachex(@Nullable String name) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public <K, V> IgniteInternalCache<K, V> cachex() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @SuppressWarnings("unchecked")
+    @Override public Collection<IgniteInternalCache<?, ?>> cachesx(
+        @Nullable IgnitePredicate<? super IgniteInternalCache<?, ?>>... p) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean eventUserRecordable(int type) {
+        throwUnsupported();
+
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean allEventsUserRecordable(int[] types) {
+        throwUnsupported();
+
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isJmxRemoteEnabled() {
+        throwUnsupported();
+
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isRestartEnabled() {
+        throwUnsupported();
+
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public IgniteFileSystem igfsx(@Nullable String name) {
+        return F.eq(name, igfs.name()) ? igfs : null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Hadoop hadoop() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteClusterEx cluster() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public String latestVersion() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public ClusterNode localNode() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public GridKernalContext context() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return name;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteLogger log() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteConfiguration configuration() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteCompute compute() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteCompute compute(ClusterGroup grp) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteMessaging message() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteMessaging message(ClusterGroup grp) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteEvents events() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteEvents events(ClusterGroup grp) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteServices services() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteServices services(ClusterGroup grp) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public ExecutorService executorService() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public ExecutorService executorService(ClusterGroup grp) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteProductVersion version() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteScheduler scheduler() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> IgniteCache<K, V> createCache(CacheConfiguration<K, V> cacheCfg) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> IgniteCache<K, V> createCache(String cacheName) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> IgniteCache<K, V> getOrCreateCache(String cacheName) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> void addCacheConfiguration(CacheConfiguration<K, V> cacheCfg) {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> IgniteCache<K, V> createCache(CacheConfiguration<K, V> cacheCfg,
+        NearCacheConfiguration<K, V> nearCfg) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg,
+        NearCacheConfiguration<K, V> nearCfg) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> IgniteCache<K, V> createNearCache(@Nullable String cacheName,
+        NearCacheConfiguration<K, V> nearCfg) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> IgniteCache<K, V> getOrCreateNearCache(@Nullable String cacheName,
+        NearCacheConfiguration<K, V> nearCfg) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void destroyCache(String cacheName) {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> IgniteCache<K, V> cache(@Nullable String name) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Collection<String> cacheNames() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteTransactions transactions() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K, V> IgniteDataStreamer<K, V> dataStreamer(@Nullable String cacheName) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteFileSystem fileSystem(String name) {
+        IgniteFileSystem res = igfsx(name);
+
+        if (res == null)
+            throw new IllegalArgumentException("IGFS is not configured: " + name);
+
+        return res;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Collection<IgniteFileSystem> fileSystems() {
+        return Collections.singleton(igfs);
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteAtomicSequence atomicSequence(String name, long initVal, boolean create)
+        throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteAtomicLong atomicLong(String name, long initVal, boolean create) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> IgniteAtomicReference<T> atomicReference(String name, @Nullable T initVal, boolean create)
+        throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, @Nullable T initVal,
+        @Nullable S initStamp, boolean create) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteCountDownLatch countDownLatch(String name, int cnt, boolean autoDel, boolean create)
+        throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteSemaphore semaphore(String name, int cnt, boolean failoverSafe, boolean create)
+        throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> IgniteQueue<T> queue(String name, int cap, @Nullable CollectionConfiguration cfg)
+        throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> IgniteSet<T> set(String name, @Nullable CollectionConfiguration cfg) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T extends IgnitePlugin> T plugin(String name) throws PluginNotFoundException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteBinary binary() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void close() throws IgniteException {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public <K> Affinity<K> affinity(String cacheName) {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /**
+     * Throw {@link UnsupportedOperationException}.
+     */
+    private static void throwUnsupported() {
+        throw new UnsupportedOperationException("Should not be called!");
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsMock.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsMock.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsMock.java
new file mode 100644
index 0000000..dccab4a
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/igfs/IgfsMock.java
@@ -0,0 +1,397 @@
+/*
+ * 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.igfs;
+
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.IgniteFileSystem;
+import org.apache.ignite.configuration.FileSystemConfiguration;
+import org.apache.ignite.igfs.IgfsBlockLocation;
+import org.apache.ignite.igfs.IgfsFile;
+import org.apache.ignite.igfs.IgfsMetrics;
+import org.apache.ignite.igfs.IgfsOutputStream;
+import org.apache.ignite.igfs.IgfsPath;
+import org.apache.ignite.igfs.IgfsPathSummary;
+import org.apache.ignite.igfs.mapreduce.IgfsRecordResolver;
+import org.apache.ignite.igfs.mapreduce.IgfsTask;
+import org.apache.ignite.igfs.secondary.IgfsSecondaryFileSystem;
+import org.apache.ignite.lang.IgniteFuture;
+import org.apache.ignite.lang.IgniteUuid;
+import org.jetbrains.annotations.Nullable;
+
+import java.net.URI;
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * Mocked IGFS implementation for IGFS tests.
+ */
+public class IgfsMock implements IgfsEx {
+    /** Name. */
+    private final String name;
+
+    /**
+     * Constructor.
+     *
+     * @param name Name.
+     */
+    public IgfsMock(@Nullable String name) {
+        this.name = name;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void stop(boolean cancel) {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsContext context() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsPaths proxyPaths() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsInputStreamAdapter open(IgfsPath path, int bufSize, int seqReadsBeforePrefetch) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsInputStreamAdapter open(IgfsPath path) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsInputStreamAdapter open(IgfsPath path, int bufSize) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsStatus globalSpace() throws IgniteCheckedException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void globalSampling(@Nullable Boolean val) throws IgniteCheckedException {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public Boolean globalSampling() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsLocalMetrics localMetrics() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long groupBlockSize() {
+        throwUnsupported();
+
+        return 0;
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public String clientLogDirectory() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void clientLogDirectory(String logDir) {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean evictExclude(IgfsPath path, boolean primary) {
+        throwUnsupported();
+
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteUuid nextAffinityKey() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isProxy(URI path) {
+        throwUnsupported();
+
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsSecondaryFileSystem asSecondary() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return name;
+    }
+
+    /** {@inheritDoc} */
+    @Override public FileSystemConfiguration configuration() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsPathSummary summary(IgfsPath path) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsOutputStream create(IgfsPath path, boolean overwrite) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsOutputStream create(IgfsPath path, int bufSize, boolean overwrite, int replication,
+        long blockSize, @Nullable Map<String, String> props) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsOutputStream create(IgfsPath path, int bufSize, boolean overwrite, @Nullable IgniteUuid affKey,
+        int replication, long blockSize, @Nullable Map<String, String> props) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsOutputStream append(IgfsPath path, boolean create) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsOutputStream append(IgfsPath path, int bufSize, boolean create,
+        @Nullable Map<String, String> props) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void setTimes(IgfsPath path, long accessTime, long modificationTime) throws IgniteException {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public Collection<IgfsBlockLocation> affinity(IgfsPath path, long start, long len)
+        throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Collection<IgfsBlockLocation> affinity(IgfsPath path, long start, long len, long maxLen)
+        throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsMetrics metrics() throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void resetMetrics() throws IgniteException {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public long size(IgfsPath path) throws IgniteException {
+        throwUnsupported();
+
+        return 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void format() throws IgniteException {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T, R> R execute(IgfsTask<T, R> task, @Nullable IgfsRecordResolver rslvr,
+        Collection<IgfsPath> paths, @Nullable T arg) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T, R> R execute(IgfsTask<T, R> task, @Nullable IgfsRecordResolver rslvr,
+        Collection<IgfsPath> paths, boolean skipNonExistentFiles, long maxRangeLen, @Nullable T arg)
+        throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T, R> R execute(Class<? extends IgfsTask<T, R>> taskCls, @Nullable IgfsRecordResolver rslvr,
+        Collection<IgfsPath> paths, @Nullable T arg) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T, R> R execute(Class<? extends IgfsTask<T, R>> taskCls, @Nullable IgfsRecordResolver rslvr,
+        Collection<IgfsPath> paths, boolean skipNonExistentFiles, long maxRangeLen, @Nullable T arg)
+        throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean exists(IgfsPath path) {
+        throwUnsupported();
+
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgfsFile update(IgfsPath path, Map<String, String> props) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void rename(IgfsPath src, IgfsPath dest) throws IgniteException {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean delete(IgfsPath path, boolean recursive) throws IgniteException {
+        throwUnsupported();
+
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void mkdirs(IgfsPath path) throws IgniteException {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void mkdirs(IgfsPath path, @Nullable Map<String, String> props) throws IgniteException {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public Collection<IgfsPath> listPaths(IgfsPath path) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Collection<IgfsFile> listFiles(IgfsPath path) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Nullable @Override public IgfsFile info(IgfsPath path) throws IgniteException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long usedSpaceSize() throws IgniteException {
+        throwUnsupported();
+
+        return 0;
+    }
+
+    /** {@inheritDoc} */
+    @Override public IgniteFileSystem withAsync() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isAsync() {
+        throwUnsupported();
+
+        return false;
+    }
+
+    /** {@inheritDoc} */
+    @Override public <R> IgniteFuture<R> future() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /**
+     * Throw {@link UnsupportedOperationException}.
+     */
+    private static void throwUnsupported() {
+        throw new UnsupportedOperationException("Should not be called!");
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/hadoop/src/main/java/org/apache/ignite/hadoop/mapreduce/IgniteHadoopMapReducePlanner.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/main/java/org/apache/ignite/hadoop/mapreduce/IgniteHadoopMapReducePlanner.java b/modules/hadoop/src/main/java/org/apache/ignite/hadoop/mapreduce/IgniteHadoopMapReducePlanner.java
index 287b5ec..d4a44fa 100644
--- a/modules/hadoop/src/main/java/org/apache/ignite/hadoop/mapreduce/IgniteHadoopMapReducePlanner.java
+++ b/modules/hadoop/src/main/java/org/apache/ignite/hadoop/mapreduce/IgniteHadoopMapReducePlanner.java
@@ -26,10 +26,9 @@ import java.util.List;
 import java.util.ListIterator;
 import java.util.Map;
 import java.util.UUID;
-import org.apache.ignite.Ignite;
+
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteException;
-import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.cluster.ClusterNode;
 import org.apache.ignite.igfs.IgfsBlockLocation;
 import org.apache.ignite.igfs.IgfsPath;
@@ -38,14 +37,11 @@ import org.apache.ignite.internal.processors.hadoop.HadoopFileBlock;
 import org.apache.ignite.internal.processors.hadoop.HadoopInputSplit;
 import org.apache.ignite.internal.processors.hadoop.HadoopJob;
 import org.apache.ignite.internal.processors.hadoop.HadoopMapReducePlan;
-import org.apache.ignite.internal.processors.hadoop.HadoopMapReducePlanner;
 import org.apache.ignite.internal.processors.hadoop.igfs.HadoopIgfsEndpoint;
 import org.apache.ignite.internal.processors.hadoop.planner.HadoopDefaultMapReducePlan;
+import org.apache.ignite.internal.processors.hadoop.planner.HadoopAbstractMapReducePlanner;
 import org.apache.ignite.internal.processors.igfs.IgfsEx;
 import org.apache.ignite.internal.util.typedef.F;
-import org.apache.ignite.internal.util.typedef.internal.U;
-import org.apache.ignite.resources.IgniteInstanceResource;
-import org.apache.ignite.resources.LoggerResource;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -54,16 +50,7 @@ import static org.apache.ignite.IgniteFileSystem.IGFS_SCHEME;
 /**
  * Default map-reduce planner implementation.
  */
-public class IgniteHadoopMapReducePlanner implements HadoopMapReducePlanner {
-    /** Injected grid. */
-    @IgniteInstanceResource
-    private Ignite ignite;
-
-    /** Logger. */
-    @SuppressWarnings("UnusedDeclaration")
-    @LoggerResource
-    private IgniteLogger log;
-
+public class IgniteHadoopMapReducePlanner extends HadoopAbstractMapReducePlanner {
     /** {@inheritDoc} */
     @Override public HadoopMapReducePlan preparePlan(HadoopJob job, Collection<ClusterNode> top,
         @Nullable HadoopMapReducePlan oldPlan) throws IgniteCheckedException {
@@ -98,7 +85,7 @@ public class IgniteHadoopMapReducePlanner implements HadoopMapReducePlanner {
         Iterable<HadoopInputSplit> splits) throws IgniteCheckedException {
         Map<UUID, Collection<HadoopInputSplit>> mappers = new HashMap<>();
 
-        Map<String, Collection<UUID>> nodes = hosts(top);
+        Map<String, Collection<UUID>> nodes = groupByHost(top);
 
         Map<UUID, Integer> nodeLoads = new HashMap<>(top.size(), 1.0f); // Track node load.
 
@@ -129,33 +116,6 @@ public class IgniteHadoopMapReducePlanner implements HadoopMapReducePlanner {
     }
 
     /**
-     * Groups nodes by host names.
-     *
-     * @param top Topology to group.
-     * @return Map.
-     */
-    private static Map<String, Collection<UUID>> hosts(Collection<ClusterNode> top) {
-        Map<String, Collection<UUID>> grouped = U.newHashMap(top.size());
-
-        for (ClusterNode node : top) {
-            for (String host : node.hostNames()) {
-                Collection<UUID> nodeIds = grouped.get(host);
-
-                if (nodeIds == null) {
-                    // Expecting 1-2 nodes per host.
-                    nodeIds = new ArrayList<>(2);
-
-                    grouped.put(host, nodeIds);
-                }
-
-                nodeIds.add(node.id());
-            }
-        }
-
-        return grouped;
-    }
-
-    /**
      * Determine the best node for this split.
      *
      * @param split Split.

http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/hadoop/src/main/java/org/apache/ignite/hadoop/mapreduce/IgniteHadoopWeightedMapReducePlanner.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/main/java/org/apache/ignite/hadoop/mapreduce/IgniteHadoopWeightedMapReducePlanner.java b/modules/hadoop/src/main/java/org/apache/ignite/hadoop/mapreduce/IgniteHadoopWeightedMapReducePlanner.java
new file mode 100644
index 0000000..27ffc19
--- /dev/null
+++ b/modules/hadoop/src/main/java/org/apache/ignite/hadoop/mapreduce/IgniteHadoopWeightedMapReducePlanner.java
@@ -0,0 +1,846 @@
+/*
+ * 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.hadoop.mapreduce;
+
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.IgniteFileSystem;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.igfs.IgfsBlockLocation;
+import org.apache.ignite.igfs.IgfsPath;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.processors.hadoop.HadoopFileBlock;
+import org.apache.ignite.internal.processors.hadoop.HadoopInputSplit;
+import org.apache.ignite.internal.processors.hadoop.HadoopJob;
+import org.apache.ignite.internal.processors.hadoop.HadoopMapReducePlan;
+import org.apache.ignite.internal.processors.hadoop.HadoopUtils;
+import org.apache.ignite.internal.processors.hadoop.igfs.HadoopIgfsEndpoint;
+import org.apache.ignite.internal.processors.hadoop.planner.HadoopAbstractMapReducePlanner;
+import org.apache.ignite.internal.processors.hadoop.planner.HadoopDefaultMapReducePlan;
+import org.apache.ignite.internal.processors.hadoop.planner.HadoopMapReducePlanGroup;
+import org.apache.ignite.internal.processors.hadoop.planner.HadoopMapReducePlanTopology;
+import org.apache.ignite.internal.processors.igfs.IgfsEx;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.UUID;
+import java.util.concurrent.ThreadLocalRandom;
+
+/**
+ * Map-reduce planner which assigns mappers and reducers based on their "weights". Weight describes how much resources
+ * are required to execute particular map or reduce task.
+ * <p>
+ * Plan creation consists of two steps: assigning mappers and assigning reducers.
+ * <p>
+ * Mappers are assigned based on input split data location. For each input split we search for nodes where
+ * its data is stored. Planner tries to assign mappers to their affinity nodes first. This process is governed by two
+ * properties:
+ * <ul>
+ *     <li><b>{@code localMapperWeight}</b> - weight of a map task when it is executed on an affinity node;</li>
+ *     <li><b>{@code remoteMapperWeight}</b> - weight of a map task when it is executed on a non-affinity node.</li>
+ * </ul>
+ * Planning algorithm assign mappers so that total resulting weight on all nodes is minimum possible.
+ * <p>
+ * Reducers are assigned differently. First we try to distribute reducers across nodes with mappers. This approach
+ * could minimize expensive data transfer over network. Reducer assigned to a node with mapper is considered
+ * <b>{@code local}</b>. Otherwise it is considered <b>{@code remote}</b>. This process continue until certain weight
+ * threshold is reached what means that current node is already too busy and it should not have higher priority over
+ * other nodes any more. Threshold can be configured using <b>{@code preferLocalReducerThresholdWeight}</b> property.
+ * <p>
+ * When local reducer threshold is reached on all nodes, we distribute remaining reducers based on their local and
+ * remote weights in the same way as it is done for mappers. This process is governed by two
+ * properties:
+ * <ul>
+ *     <li><b>{@code localReducerWeight}</b> - weight of a reduce task when it is executed on a node with mappers;</li>
+ *     <li><b>{@code remoteReducerWeight}</b> - weight of a map task when it is executed on a node without mappers.</li>
+ * </ul>
+ */
+public class IgniteHadoopWeightedMapReducePlanner extends HadoopAbstractMapReducePlanner {
+    /** Default local mapper weight. */
+    public static final int DFLT_LOC_MAPPER_WEIGHT = 100;
+
+    /** Default remote mapper weight. */
+    public static final int DFLT_RMT_MAPPER_WEIGHT = 100;
+
+    /** Default local reducer weight. */
+    public static final int DFLT_LOC_REDUCER_WEIGHT = 100;
+
+    /** Default remote reducer weight. */
+    public static final int DFLT_RMT_REDUCER_WEIGHT = 100;
+
+    /** Default reducer migration threshold weight. */
+    public static final int DFLT_PREFER_LOCAL_REDUCER_THRESHOLD_WEIGHT = 200;
+
+    /** Local mapper weight. */
+    private int locMapperWeight = DFLT_LOC_MAPPER_WEIGHT;
+
+    /** Remote mapper weight. */
+    private int rmtMapperWeight = DFLT_RMT_MAPPER_WEIGHT;
+
+    /** Local reducer weight. */
+    private int locReducerWeight = DFLT_LOC_REDUCER_WEIGHT;
+
+    /** Remote reducer weight. */
+    private int rmtReducerWeight = DFLT_RMT_REDUCER_WEIGHT;
+
+    /** Reducer migration threshold weight. */
+    private int preferLocReducerThresholdWeight = DFLT_PREFER_LOCAL_REDUCER_THRESHOLD_WEIGHT;
+
+    /** {@inheritDoc} */
+    @Override public HadoopMapReducePlan preparePlan(HadoopJob job, Collection<ClusterNode> nodes,
+        @Nullable HadoopMapReducePlan oldPlan) throws IgniteCheckedException {
+        List<HadoopInputSplit> splits = HadoopUtils.sortInputSplits(job.input());
+        int reducerCnt = job.info().reducers();
+
+        if (reducerCnt < 0)
+            throw new IgniteCheckedException("Number of reducers must be non-negative, actual: " + reducerCnt);
+
+        HadoopMapReducePlanTopology top = topology(nodes);
+
+        Mappers mappers = assignMappers(splits, top);
+
+        Map<UUID, int[]> reducers = assignReducers(splits, top, mappers, reducerCnt);
+
+        return new HadoopDefaultMapReducePlan(mappers.nodeToSplits, reducers);
+    }
+
+    /**
+     * Assign mappers to nodes.
+     *
+     * @param splits Input splits.
+     * @param top Topology.
+     * @return Mappers.
+     * @throws IgniteCheckedException If failed.
+     */
+    private Mappers assignMappers(Collection<HadoopInputSplit> splits,
+        HadoopMapReducePlanTopology top) throws IgniteCheckedException {
+        Mappers res = new Mappers();
+
+        for (HadoopInputSplit split : splits) {
+            // Try getting IGFS affinity.
+            Collection<UUID> nodeIds = affinityNodesForSplit(split, top);
+
+            // Get best node.
+            UUID node = bestMapperNode(nodeIds, top);
+
+            assert node != null;
+
+            res.add(split, node);
+        }
+
+        return res;
+    }
+
+    /**
+     * Get affinity nodes for the given input split.
+     * <p>
+     * Order in the returned collection *is* significant, meaning that nodes containing more data
+     * go first. This way, the 1st nodes in the collection considered to be preferable for scheduling.
+     *
+     * @param split Split.
+     * @param top Topology.
+     * @return Affintiy nodes.
+     * @throws IgniteCheckedException If failed.
+     */
+    private Collection<UUID> affinityNodesForSplit(HadoopInputSplit split, HadoopMapReducePlanTopology top)
+        throws IgniteCheckedException {
+        Collection<UUID> igfsNodeIds = igfsAffinityNodesForSplit(split);
+
+        if (igfsNodeIds != null)
+            return igfsNodeIds;
+
+        Map<NodeIdAndLength, UUID> res = new TreeMap<>();
+
+        for (String host : split.hosts()) {
+            long len = split instanceof HadoopFileBlock ? ((HadoopFileBlock)split).length() : 0L;
+
+            HadoopMapReducePlanGroup grp = top.groupForHost(host);
+
+            if (grp != null) {
+                for (int i = 0; i < grp.nodeCount(); i++) {
+                    UUID nodeId = grp.nodeId(i);
+
+                    res.put(new NodeIdAndLength(nodeId, len), nodeId);
+                }
+            }
+        }
+
+        return new LinkedHashSet<>(res.values());
+    }
+
+    /**
+     * Get IGFS affinity nodes for split if possible.
+     * <p>
+     * Order in the returned collection *is* significant, meaning that nodes containing more data
+     * go first. This way, the 1st nodes in the collection considered to be preferable for scheduling.
+     *
+     * @param split Input split.
+     * @return IGFS affinity or {@code null} if IGFS is not available.
+     * @throws IgniteCheckedException If failed.
+     */
+    @Nullable private Collection<UUID> igfsAffinityNodesForSplit(HadoopInputSplit split) throws IgniteCheckedException {
+        if (split instanceof HadoopFileBlock) {
+            HadoopFileBlock split0 = (HadoopFileBlock)split;
+
+            if (IgniteFileSystem.IGFS_SCHEME.equalsIgnoreCase(split0.file().getScheme())) {
+                HadoopIgfsEndpoint endpoint = new HadoopIgfsEndpoint(split0.file().getAuthority());
+
+                IgfsEx igfs = null;
+
+                if (F.eq(ignite.name(), endpoint.grid()))
+                    igfs = (IgfsEx)((IgniteEx)ignite).igfsx(endpoint.igfs());
+
+                if (igfs != null && !igfs.isProxy(split0.file())) {
+                    IgfsPath path = new IgfsPath(split0.file());
+
+                    if (igfs.exists(path)) {
+                        Collection<IgfsBlockLocation> blocks;
+
+                        try {
+                            blocks = igfs.affinity(path, split0.start(), split0.length());
+                        }
+                        catch (IgniteException e) {
+                            throw new IgniteCheckedException("Failed to get IGFS file block affinity [path=" + path +
+                                ", start=" + split0.start() + ", len=" + split0.length() + ']', e);
+                        }
+
+                        assert blocks != null;
+
+                        if (blocks.size() == 1)
+                            return blocks.iterator().next().nodeIds();
+                        else {
+                            // The most "local" nodes go first.
+                            Map<UUID, Long> idToLen = new HashMap<>();
+
+                            for (IgfsBlockLocation block : blocks) {
+                                for (UUID id : block.nodeIds()) {
+                                    Long len = idToLen.get(id);
+
+                                    idToLen.put(id, len == null ? block.length() : block.length() + len);
+                                }
+                            }
+
+                            // Sort the nodes in non-ascending order by contained data lengths.
+                            Map<NodeIdAndLength, UUID> res = new TreeMap<>();
+
+                            for (Map.Entry<UUID, Long> idToLenEntry : idToLen.entrySet()) {
+                                UUID id = idToLenEntry.getKey();
+
+                                res.put(new NodeIdAndLength(id, idToLenEntry.getValue()), id);
+                            }
+
+                            return new LinkedHashSet<>(res.values());
+                        }
+                    }
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Find best mapper node.
+     *
+     * @param affIds Affinity node IDs.
+     * @param top Topology.
+     * @return Result.
+     */
+    private UUID bestMapperNode(@Nullable Collection<UUID> affIds, HadoopMapReducePlanTopology top) {
+        // Priority node.
+        UUID prioAffId = F.first(affIds);
+
+        // Find group with the least weight.
+        HadoopMapReducePlanGroup resGrp = null;
+        MapperPriority resPrio = MapperPriority.NORMAL;
+        int resWeight = Integer.MAX_VALUE;
+
+        for (HadoopMapReducePlanGroup grp : top.groups()) {
+            MapperPriority prio = groupPriority(grp, affIds, prioAffId);
+
+            int weight = grp.weight() + (prio == MapperPriority.NORMAL ? rmtMapperWeight : locMapperWeight);
+
+            if (resGrp == null || weight < resWeight || weight == resWeight && prio.value() > resPrio.value()) {
+                resGrp = grp;
+                resPrio = prio;
+                resWeight = weight;
+            }
+        }
+
+        assert resGrp != null;
+
+        // Update group weight for further runs.
+        resGrp.weight(resWeight);
+
+        // Return the best node from the group.
+        return bestMapperNodeForGroup(resGrp, resPrio, affIds, prioAffId);
+    }
+
+    /**
+     * Get best node in the group.
+     *
+     * @param grp Group.
+     * @param priority Priority.
+     * @param affIds Affinity IDs.
+     * @param prioAffId Priority affinity IDs.
+     * @return Best node ID in the group.
+     */
+    private static UUID bestMapperNodeForGroup(HadoopMapReducePlanGroup grp, MapperPriority priority,
+        @Nullable Collection<UUID> affIds, @Nullable UUID prioAffId) {
+        // Return the best node from the group.
+        int idx = 0;
+
+        // This is rare situation when several nodes are started on the same host.
+        if (!grp.single()) {
+            switch (priority) {
+                case NORMAL: {
+                    // Pick any node.
+                    idx = ThreadLocalRandom.current().nextInt(grp.nodeCount());
+
+                    break;
+                }
+                case HIGH: {
+                    // Pick any affinity node.
+                    assert affIds != null;
+
+                    List<Integer> cands = new ArrayList<>();
+
+                    for (int i = 0; i < grp.nodeCount(); i++) {
+                        UUID id = grp.nodeId(i);
+
+                        if (affIds.contains(id))
+                            cands.add(i);
+                    }
+
+                    idx = cands.get(ThreadLocalRandom.current().nextInt(cands.size()));
+
+                    break;
+                }
+                default: {
+                    // Find primary node.
+                    assert prioAffId != null;
+
+                    for (int i = 0; i < grp.nodeCount(); i++) {
+                        UUID id = grp.nodeId(i);
+
+                        if (F.eq(id, prioAffId)) {
+                            idx = i;
+
+                            break;
+                        }
+                    }
+
+                    assert priority == MapperPriority.HIGHEST;
+                }
+            }
+        }
+
+        return grp.nodeId(idx);
+    }
+
+    /**
+     * Generate reducers.
+     *
+     * @param splits Input splits.
+     * @param top Topology.
+     * @param mappers Mappers.
+     * @param reducerCnt Reducer count.
+     * @return Reducers.
+     */
+    private Map<UUID, int[]> assignReducers(Collection<HadoopInputSplit> splits, HadoopMapReducePlanTopology top,
+        Mappers mappers, int reducerCnt) {
+        Map<UUID, Integer> reducers = assignReducers0(top, splits, mappers, reducerCnt);
+
+        int cnt = 0;
+
+        Map<UUID, int[]> res = new HashMap<>(reducers.size());
+
+        for (Map.Entry<UUID, Integer> reducerEntry : reducers.entrySet()) {
+            int[] arr = new int[reducerEntry.getValue()];
+
+            for (int i = 0; i < arr.length; i++)
+                arr[i] = cnt++;
+
+            res.put(reducerEntry.getKey(), arr);
+        }
+
+        assert reducerCnt == cnt : reducerCnt + " != " + cnt;
+
+        return res;
+    }
+
+    /**
+     * Generate reducers.
+     *
+     * @param top Topology.
+     * @param splits Input splits.
+     * @param mappers Mappers.
+     * @param reducerCnt Reducer count.
+     * @return Reducers.
+     */
+    private Map<UUID, Integer> assignReducers0(HadoopMapReducePlanTopology top, Collection<HadoopInputSplit> splits,
+        Mappers mappers, int reducerCnt) {
+        Map<UUID, Integer> res = new HashMap<>();
+
+        // Assign reducers to splits.
+        Map<HadoopInputSplit, Integer> splitToReducerCnt = assignReducersToSplits(splits, reducerCnt);
+
+        // Assign as much local reducers as possible.
+        int remaining = 0;
+
+        for (Map.Entry<HadoopInputSplit, Integer> entry : splitToReducerCnt.entrySet()) {
+            HadoopInputSplit split = entry.getKey();
+            int cnt = entry.getValue();
+
+            if (cnt > 0) {
+                int assigned = assignLocalReducers(split, cnt, top, mappers, res);
+
+                assert assigned <= cnt;
+
+                remaining += cnt - assigned;
+            }
+        }
+
+        // Assign the rest reducers.
+        if (remaining > 0)
+            assignRemoteReducers(remaining, top, mappers, res);
+
+        return res;
+    }
+
+    /**
+     * Assign local split reducers.
+     *
+     * @param split Split.
+     * @param cnt Reducer count.
+     * @param top Topology.
+     * @param mappers Mappers.
+     * @param resMap Reducers result map.
+     * @return Number of locally assigned reducers.
+     */
+    private int assignLocalReducers(HadoopInputSplit split, int cnt, HadoopMapReducePlanTopology top, Mappers mappers,
+        Map<UUID, Integer> resMap) {
+        // Dereference node.
+        UUID nodeId = mappers.splitToNode.get(split);
+
+        assert nodeId != null;
+
+        // Dereference group.
+        HadoopMapReducePlanGroup grp = top.groupForId(nodeId);
+
+        assert grp != null;
+
+        // Assign more reducers to the node until threshold is reached.
+        int res = 0;
+
+        while (res < cnt && grp.weight() < preferLocReducerThresholdWeight) {
+            res++;
+
+            grp.weight(grp.weight() + locReducerWeight);
+        }
+
+        // Update result map.
+        if (res > 0) {
+            Integer reducerCnt = resMap.get(nodeId);
+
+            resMap.put(nodeId, reducerCnt == null ? res : reducerCnt + res);
+        }
+
+        return res;
+    }
+
+    /**
+     * Assign remote reducers. Assign to the least loaded first.
+     *
+     * @param cnt Count.
+     * @param top Topology.
+     * @param mappers Mappers.
+     * @param resMap Reducers result map.
+     */
+    private void assignRemoteReducers(int cnt, HadoopMapReducePlanTopology top, Mappers mappers,
+        Map<UUID, Integer> resMap) {
+
+        TreeSet<HadoopMapReducePlanGroup> set = new TreeSet<>(new GroupWeightComparator());
+
+        set.addAll(top.groups());
+
+        while (cnt-- > 0) {
+            // The least loaded machine.
+            HadoopMapReducePlanGroup grp = set.first();
+
+            // Look for nodes with assigned splits.
+            List<UUID> splitNodeIds = null;
+
+            for (int i = 0; i < grp.nodeCount(); i++) {
+                UUID nodeId = grp.nodeId(i);
+
+                if (mappers.nodeToSplits.containsKey(nodeId)) {
+                    if (splitNodeIds == null)
+                        splitNodeIds = new ArrayList<>(2);
+
+                    splitNodeIds.add(nodeId);
+                }
+            }
+
+            // Select best node.
+            UUID id;
+            int newWeight;
+
+            if (splitNodeIds != null) {
+                id = splitNodeIds.get(ThreadLocalRandom.current().nextInt(splitNodeIds.size()));
+
+                newWeight = grp.weight() + locReducerWeight;
+            }
+            else {
+                id = grp.nodeId(ThreadLocalRandom.current().nextInt(grp.nodeCount()));
+
+                newWeight = grp.weight() + rmtReducerWeight;
+            }
+
+            // Re-add entry with new weight.
+            boolean rmv = set.remove(grp);
+
+            assert rmv;
+
+            grp.weight(newWeight);
+
+            boolean add = set.add(grp);
+
+            assert add;
+
+            // Update result map.
+            Integer res = resMap.get(id);
+
+            resMap.put(id, res == null ? 1 : res + 1);
+        }
+    }
+
+    /**
+     * Comparator based on group's weight.
+     */
+    private static class GroupWeightComparator implements Comparator<HadoopMapReducePlanGroup> {
+        /** {@inheritDoc} */
+        @Override public int compare(HadoopMapReducePlanGroup first, HadoopMapReducePlanGroup second) {
+            int res = first.weight() - second.weight();
+
+            if (res < 0)
+                return -1;
+            else if (res > 0)
+                return 1;
+            else
+                return first.macs().compareTo(second.macs());
+        }
+    }
+
+    /**
+     * Distribute reducers between splits.
+     *
+     * @param splits Splits.
+     * @param reducerCnt Reducer count.
+     * @return Map from input split to reducer count.
+     */
+    private Map<HadoopInputSplit, Integer> assignReducersToSplits(Collection<HadoopInputSplit> splits,
+        int reducerCnt) {
+        Map<HadoopInputSplit, Integer> res = new IdentityHashMap<>(splits.size());
+
+        int base = reducerCnt / splits.size();
+        int remainder = reducerCnt % splits.size();
+
+        for (HadoopInputSplit split : splits) {
+            int val = base;
+
+            if (remainder > 0) {
+                val++;
+
+                remainder--;
+            }
+
+            res.put(split, val);
+        }
+
+        assert remainder == 0;
+
+        return res;
+    }
+
+    /**
+     * Calculate group priority.
+     *
+     * @param grp Group.
+     * @param affIds Affinity IDs.
+     * @param prioAffId Priority affinity ID.
+     * @return Group priority.
+     */
+    private static MapperPriority groupPriority(HadoopMapReducePlanGroup grp, @Nullable Collection<UUID> affIds,
+        @Nullable UUID prioAffId) {
+        assert F.isEmpty(affIds) ? prioAffId == null : prioAffId == F.first(affIds);
+        assert grp != null;
+
+        MapperPriority prio = MapperPriority.NORMAL;
+
+        if (!F.isEmpty(affIds)) {
+            for (int i = 0; i < grp.nodeCount(); i++) {
+                UUID id = grp.nodeId(i);
+
+                if (affIds.contains(id)) {
+                    prio = MapperPriority.HIGH;
+
+                    if (F.eq(prioAffId, id)) {
+                        prio = MapperPriority.HIGHEST;
+
+                        break;
+                    }
+                }
+            }
+        }
+
+        return prio;
+    }
+
+    /**
+     * Get local mapper weight. This weight is added to a node when a mapper is assigned and it's input split data is
+     * located on this node (at least partially).
+     * <p>
+     * Defaults to {@link #DFLT_LOC_MAPPER_WEIGHT}.
+     *
+     * @return Remote mapper weight.
+     */
+    public int getLocalMapperWeight() {
+        return locMapperWeight;
+    }
+
+    /**
+     * Set local mapper weight. See {@link #getLocalMapperWeight()} for more information.
+     *
+     * @param locMapperWeight Local mapper weight.
+     */
+    public void setLocalMapperWeight(int locMapperWeight) {
+        this.locMapperWeight = locMapperWeight;
+    }
+
+    /**
+     * Get remote mapper weight. This weight is added to a node when a mapper is assigned, but it's input
+     * split data is not located on this node.
+     * <p>
+     * Defaults to {@link #DFLT_RMT_MAPPER_WEIGHT}.
+     *
+     * @return Remote mapper weight.
+     */
+    public int getRemoteMapperWeight() {
+        return rmtMapperWeight;
+    }
+
+    /**
+     * Set remote mapper weight. See {@link #getRemoteMapperWeight()} for more information.
+     *
+     * @param rmtMapperWeight Remote mapper weight.
+     */
+    public void setRemoteMapperWeight(int rmtMapperWeight) {
+        this.rmtMapperWeight = rmtMapperWeight;
+    }
+
+    /**
+     * Get local reducer weight. This weight is added to a node when a reducer is assigned and the node have at least
+     * one assigned mapper.
+     * <p>
+     * Defaults to {@link #DFLT_LOC_REDUCER_WEIGHT}.
+     *
+     * @return Local reducer weight.
+     */
+    public int getLocalReducerWeight() {
+        return locReducerWeight;
+    }
+
+    /**
+     * Set local reducer weight. See {@link #getLocalReducerWeight()} for more information.
+     *
+     * @param locReducerWeight Local reducer weight.
+     */
+    public void setLocalReducerWeight(int locReducerWeight) {
+        this.locReducerWeight = locReducerWeight;
+    }
+
+    /**
+     * Get remote reducer weight. This weight is added to a node when a reducer is assigned, but the node doesn't have
+     * any assigned mappers.
+     * <p>
+     * Defaults to {@link #DFLT_RMT_REDUCER_WEIGHT}.
+     *
+     * @return Remote reducer weight.
+     */
+    public int getRemoteReducerWeight() {
+        return rmtReducerWeight;
+    }
+
+    /**
+     * Set remote reducer weight. See {@link #getRemoteReducerWeight()} for more information.
+     *
+     * @param rmtReducerWeight Remote reducer weight.
+     */
+    public void setRemoteReducerWeight(int rmtReducerWeight) {
+        this.rmtReducerWeight = rmtReducerWeight;
+    }
+
+    /**
+     * Get reducer migration threshold weight. When threshold is reached, a node with mappers is no longer considered
+     * as preferred for further reducer assignments.
+     * <p>
+     * Defaults to {@link #DFLT_PREFER_LOCAL_REDUCER_THRESHOLD_WEIGHT}.
+     *
+     * @return Reducer migration threshold weight.
+     */
+    public int getPreferLocalReducerThresholdWeight() {
+        return preferLocReducerThresholdWeight;
+    }
+
+    /**
+     * Set reducer migration threshold weight. See {@link #getPreferLocalReducerThresholdWeight()} for more
+     * information.
+     *
+     * @param reducerMigrationThresholdWeight Reducer migration threshold weight.
+     */
+    public void setPreferLocalReducerThresholdWeight(int reducerMigrationThresholdWeight) {
+        this.preferLocReducerThresholdWeight = reducerMigrationThresholdWeight;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(IgniteHadoopWeightedMapReducePlanner.class, this);
+    }
+
+    /**
+     * Node ID and length.
+     */
+    private static class NodeIdAndLength implements Comparable<NodeIdAndLength> {
+        /** Node ID. */
+        private final UUID id;
+
+        /** Length. */
+        private final long len;
+
+        /**
+         * Constructor.
+         *
+         * @param id Node ID.
+         * @param len Length.
+         */
+        public NodeIdAndLength(UUID id, long len) {
+            this.id = id;
+            this.len = len;
+        }
+
+        /** {@inheritDoc} */
+        @SuppressWarnings("NullableProblems")
+        @Override public int compareTo(NodeIdAndLength obj) {
+            long res = len - obj.len;
+
+            if (res > 0)
+                return -1;
+            else if (res < 0)
+                return 1;
+            else
+                return id.compareTo(obj.id);
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return id.hashCode();
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object obj) {
+            return obj instanceof NodeIdAndLength && F.eq(id, ((NodeIdAndLength)obj).id);
+        }
+    }
+
+    /**
+     * Mappers.
+     */
+    private static class Mappers {
+        /** Node-to-splits map. */
+        private final Map<UUID, Collection<HadoopInputSplit>> nodeToSplits = new HashMap<>();
+
+        /** Split-to-node map. */
+        private final Map<HadoopInputSplit, UUID> splitToNode = new IdentityHashMap<>();
+
+        /**
+         * Add mapping.
+         *
+         * @param split Split.
+         * @param node Node.
+         */
+        public void add(HadoopInputSplit split, UUID node) {
+            Collection<HadoopInputSplit> nodeSplits = nodeToSplits.get(node);
+
+            if (nodeSplits == null) {
+                nodeSplits = new HashSet<>();
+
+                nodeToSplits.put(node, nodeSplits);
+            }
+
+            nodeSplits.add(split);
+
+            splitToNode.put(split, node);
+        }
+    }
+
+    /**
+     * Mapper priority enumeration.
+     */
+    private enum MapperPriority {
+        /** Normal node. */
+        NORMAL(0),
+
+        /** (likely) Affinity node. */
+        HIGH(1),
+
+        /** (likely) Affinity node with the highest priority (e.g. because it hosts more data than other nodes). */
+        HIGHEST(2);
+
+        /** Value. */
+        private final int val;
+
+        /**
+         * Constructor.
+         *
+         * @param val Value.
+         */
+        MapperPriority(int val) {
+            this.val = val;
+        }
+
+        /**
+         * @return Value.
+         */
+        public int value() {
+            return val;
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/HadoopUtils.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/HadoopUtils.java b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/HadoopUtils.java
index 3fa963f..44d871a 100644
--- a/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/HadoopUtils.java
+++ b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/HadoopUtils.java
@@ -25,8 +25,12 @@ import java.io.ObjectInputStream;
 import java.io.ObjectOutput;
 import java.io.ObjectOutputStream;
 import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.Collection;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
+import java.util.TreeSet;
 import java.util.UUID;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.Path;
@@ -352,4 +356,81 @@ public class HadoopUtils {
         }
     }
 
+    /**
+     * Sort input splits by length.
+     *
+     * @param splits Splits.
+     * @return Sorted splits.
+     */
+    public static List<HadoopInputSplit> sortInputSplits(Collection<HadoopInputSplit> splits) {
+        int id = 0;
+
+        TreeSet<SplitSortWrapper> sortedSplits = new TreeSet<>();
+
+        for (HadoopInputSplit split : splits) {
+            long len = split instanceof HadoopFileBlock ? ((HadoopFileBlock)split).length() : 0;
+
+            sortedSplits.add(new SplitSortWrapper(id++, split, len));
+        }
+
+        ArrayList<HadoopInputSplit> res = new ArrayList<>(sortedSplits.size());
+
+        for (SplitSortWrapper sortedSplit : sortedSplits)
+            res.add(sortedSplit.split);
+
+        return res;
+    }
+
+    /**
+     * Split wrapper for sorting.
+     */
+    private static class SplitSortWrapper implements Comparable<SplitSortWrapper> {
+        /** Unique ID. */
+        private final int id;
+
+        /** Split. */
+        private final HadoopInputSplit split;
+
+        /** Split length. */
+        private final long len;
+
+        /**
+         * Constructor.
+         *
+         * @param id Unique ID.
+         * @param split Split.
+         * @param len Split length.
+         */
+        public SplitSortWrapper(int id, HadoopInputSplit split, long len) {
+            this.id = id;
+            this.split = split;
+            this.len = len;
+        }
+
+        /** {@inheritDoc} */
+        @SuppressWarnings("NullableProblems")
+        @Override public int compareTo(SplitSortWrapper other) {
+            assert other != null;
+
+            long res = len - other.len;
+
+            if (res > 0)
+                return -1;
+            else if (res < 0)
+                return 1;
+            else
+                return id - other.id;
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return id;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(Object obj) {
+            return obj instanceof SplitSortWrapper && id == ((SplitSortWrapper)obj).id;
+        }
+    }
+
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/planner/HadoopAbstractMapReducePlanner.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/planner/HadoopAbstractMapReducePlanner.java b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/planner/HadoopAbstractMapReducePlanner.java
new file mode 100644
index 0000000..f01f72b
--- /dev/null
+++ b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/planner/HadoopAbstractMapReducePlanner.java
@@ -0,0 +1,116 @@
+/*
+ * 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.hadoop.planner;
+
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.internal.processors.hadoop.HadoopMapReducePlanner;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.resources.IgniteInstanceResource;
+import org.apache.ignite.resources.LoggerResource;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MACS;
+
+/**
+ * Base class for map-reduce planners.
+ */
+public abstract class HadoopAbstractMapReducePlanner implements HadoopMapReducePlanner {
+    /** Injected grid. */
+    @IgniteInstanceResource
+    protected Ignite ignite;
+
+    /** Logger. */
+    @SuppressWarnings("UnusedDeclaration")
+    @LoggerResource
+    protected IgniteLogger log;
+
+    /**
+     * Create plan topology.
+     *
+     * @param nodes Topology nodes.
+     * @return Plan topology.
+     */
+    protected static HadoopMapReducePlanTopology topology(Collection<ClusterNode> nodes) {
+        Map<String, HadoopMapReducePlanGroup> macsMap = new HashMap<>(nodes.size());
+
+        Map<UUID, HadoopMapReducePlanGroup> idToGrp = new HashMap<>(nodes.size());
+        Map<String, HadoopMapReducePlanGroup> hostToGrp = new HashMap<>(nodes.size());
+
+        for (ClusterNode node : nodes) {
+            String macs = node.attribute(ATTR_MACS);
+
+            HadoopMapReducePlanGroup grp = macsMap.get(macs);
+
+            if (grp == null) {
+                grp = new HadoopMapReducePlanGroup(node, macs);
+
+                macsMap.put(macs, grp);
+            }
+            else
+                grp.add(node);
+
+            idToGrp.put(node.id(), grp);
+
+            for (String host : node.addresses()) {
+                HadoopMapReducePlanGroup hostGrp = hostToGrp.get(host);
+
+                if (hostGrp == null)
+                    hostToGrp.put(host, grp);
+                else
+                    assert hostGrp == grp;
+            }
+        }
+
+        return new HadoopMapReducePlanTopology(new ArrayList<>(macsMap.values()), idToGrp, hostToGrp);
+    }
+
+
+    /**
+     * Groups nodes by host names.
+     *
+     * @param top Topology to group.
+     * @return Map.
+     */
+    protected static Map<String, Collection<UUID>> groupByHost(Collection<ClusterNode> top) {
+        Map<String, Collection<UUID>> grouped = U.newHashMap(top.size());
+
+        for (ClusterNode node : top) {
+            for (String host : node.hostNames()) {
+                Collection<UUID> nodeIds = grouped.get(host);
+
+                if (nodeIds == null) {
+                    // Expecting 1-2 nodes per host.
+                    nodeIds = new ArrayList<>(2);
+
+                    grouped.put(host, nodeIds);
+                }
+
+                nodeIds.add(node.id());
+            }
+        }
+
+        return grouped;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/planner/HadoopMapReducePlanGroup.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/planner/HadoopMapReducePlanGroup.java b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/planner/HadoopMapReducePlanGroup.java
new file mode 100644
index 0000000..2fe8682
--- /dev/null
+++ b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/planner/HadoopMapReducePlanGroup.java
@@ -0,0 +1,150 @@
+/*
+ * 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.hadoop.planner;
+
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+
+import java.util.ArrayList;
+import java.util.UUID;
+
+/**
+ * Map-reduce plan group of nodes on a single physical machine.
+ */
+public class HadoopMapReducePlanGroup {
+    /** Node. */
+    private ClusterNode node;
+
+    /** Nodes. */
+    private ArrayList<ClusterNode> nodes;
+
+    /** MAC addresses. */
+    private final String macs;
+
+    /** Weight. */
+    private int weight;
+
+    /**
+     * Constructor.
+     *
+     * @param node First node in the group.
+     * @param macs MAC addresses.
+     */
+    public HadoopMapReducePlanGroup(ClusterNode node, String macs) {
+        assert node != null;
+        assert macs != null;
+
+        this.node = node;
+        this.macs = macs;
+    }
+
+    /**
+     * Add node to the group.
+     *
+     * @param newNode New node.
+     */
+    public void add(ClusterNode newNode) {
+        if (node != null) {
+            nodes = new ArrayList<>(2);
+
+            nodes.add(node);
+
+            node = null;
+        }
+
+        nodes.add(newNode);
+    }
+
+    /**
+     * @return MAC addresses.
+     */
+    public String macs() {
+        return macs;
+    }
+
+    /**
+     * @return {@code True} if only sinle node present.
+     */
+    public boolean single() {
+        return nodeCount() == 1;
+    }
+
+    /**
+     * Get node ID by index.
+     *
+     * @param idx Index.
+     * @return Node.
+     */
+    public UUID nodeId(int idx) {
+        ClusterNode res;
+
+        if (node != null) {
+            assert idx == 0;
+
+            res = node;
+        }
+        else {
+            assert nodes != null;
+            assert idx < nodes.size();
+
+            res = nodes.get(idx);
+        }
+
+        assert res != null;
+
+        return res.id();
+    }
+
+    /**
+     * @return Node count.
+     */
+    public int nodeCount() {
+        return node != null ? 1 : nodes.size();
+    }
+
+    /**
+     * @return weight.
+     */
+    public int weight() {
+        return weight;
+    }
+
+    /**
+     * @param weight weight.
+     */
+    public void weight(int weight) {
+        this.weight = weight;
+    }
+
+
+    /** {@inheritDoc} */
+    @Override public int hashCode() {
+        return macs.hashCode();
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean equals(Object obj) {
+        return obj instanceof HadoopMapReducePlanGroup && F.eq(macs, ((HadoopMapReducePlanGroup)obj).macs);
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(HadoopMapReducePlanGroup.class, this);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/planner/HadoopMapReducePlanTopology.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/planner/HadoopMapReducePlanTopology.java b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/planner/HadoopMapReducePlanTopology.java
new file mode 100644
index 0000000..fa5c469
--- /dev/null
+++ b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/planner/HadoopMapReducePlanTopology.java
@@ -0,0 +1,89 @@
+/*
+ * 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.hadoop.planner;
+
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ * Map-reduce plan topology.
+ */
+public class HadoopMapReducePlanTopology {
+    /** All groups. */
+    private final List<HadoopMapReducePlanGroup> grps;
+
+    /** Node ID to group map. */
+    private final Map<UUID, HadoopMapReducePlanGroup> idToGrp;
+
+    /** Host to group map. */
+    private final Map<String, HadoopMapReducePlanGroup> hostToGrp;
+
+    /**
+     * Constructor.
+     *
+     * @param grps All groups.
+     * @param idToGrp ID to group map.
+     * @param hostToGrp Host to group map.
+     */
+    public HadoopMapReducePlanTopology(List<HadoopMapReducePlanGroup> grps,
+        Map<UUID, HadoopMapReducePlanGroup> idToGrp, Map<String, HadoopMapReducePlanGroup> hostToGrp) {
+        assert grps != null;
+        assert idToGrp != null;
+        assert hostToGrp != null;
+
+        this.grps = grps;
+        this.idToGrp = idToGrp;
+        this.hostToGrp = hostToGrp;
+    }
+
+    /**
+     * @return All groups.
+     */
+    public List<HadoopMapReducePlanGroup> groups() {
+        return grps;
+    }
+
+    /**
+     * Get group for node ID.
+     *
+     * @param id Node ID.
+     * @return Group.
+     */
+    public HadoopMapReducePlanGroup groupForId(UUID id) {
+        return idToGrp.get(id);
+    }
+
+    /**
+     * Get group for host.
+     *
+     * @param host Host.
+     * @return Group.
+     */
+    @Nullable public HadoopMapReducePlanGroup groupForHost(String host) {
+        return hostToGrp.get(host);
+    }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        return S.toString(HadoopMapReducePlanTopology.class, this);
+    }
+}


[42/50] [abbrv] ignite git commit: IGNITE-3476 Node started within SpringCacheManager does not inject Spring resources

Posted by vo...@apache.org.
IGNITE-3476 Node started within SpringCacheManager does not inject Spring resources


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

Branch: refs/heads/ignite-1.5.31-1
Commit: a39770aa48412fad57712a4cb580b028cb111eb9
Parents: 71ef652
Author: EdShangGG <es...@gridgain.com>
Authored: Tue Jul 26 12:46:05 2016 +0300
Committer: EdShangGG <es...@gridgain.com>
Committed: Tue Jul 26 12:46:05 2016 +0300

----------------------------------------------------------------------
 .../ignite/cache/spring/SpringCacheManager.java |  17 ++-
 .../spring/SpringTransactionManager.java        |  59 +++++----
 .../test/java/config/spring-transactions.xml    |   4 +-
 .../ignite/TestInjectionLifecycleBean.java      |  42 +++++++
 .../org/apache/ignite/spring-injection-test.xml |  43 +++++++
 .../SpringCacheManagerContextInjectionTest.java | 126 +++++++++++++++++++
 .../testsuites/IgniteSpringTestSuite.java       |   5 +
 ...gTransactionManagerContextInjectionTest.java | 125 ++++++++++++++++++
 8 files changed, 393 insertions(+), 28 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/a39770aa/modules/spring/src/main/java/org/apache/ignite/cache/spring/SpringCacheManager.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/main/java/org/apache/ignite/cache/spring/SpringCacheManager.java b/modules/spring/src/main/java/org/apache/ignite/cache/spring/SpringCacheManager.java
index 71b723f..6d1a9b6 100644
--- a/modules/spring/src/main/java/org/apache/ignite/cache/spring/SpringCacheManager.java
+++ b/modules/spring/src/main/java/org/apache/ignite/cache/spring/SpringCacheManager.java
@@ -21,6 +21,7 @@ import java.util.ArrayList;
 import java.util.Collection;
 import java.util.concurrent.ConcurrentMap;
 import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteSpring;
 import org.apache.ignite.Ignition;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
@@ -28,6 +29,8 @@ import org.apache.ignite.configuration.NearCacheConfiguration;
 import org.jsr166.ConcurrentHashMap8;
 import org.springframework.beans.factory.InitializingBean;
 import org.springframework.cache.CacheManager;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
 
 /**
  * Implementation of Spring cache abstraction based on Ignite cache.
@@ -133,7 +136,7 @@ import org.springframework.cache.CacheManager;
  * Ignite distribution, and all these nodes will participate
  * in caching the data.
  */
-public class SpringCacheManager implements CacheManager, InitializingBean {
+public class SpringCacheManager implements CacheManager, InitializingBean, ApplicationContextAware {
     /** Caches map. */
     private final ConcurrentMap<String, SpringCache> caches = new ConcurrentHashMap8<>();
 
@@ -155,6 +158,14 @@ public class SpringCacheManager implements CacheManager, InitializingBean {
     /** Ignite instance. */
     private Ignite ignite;
 
+    /** Spring context */
+    private ApplicationContext springCtx;
+
+    /** {@inheritDoc} */
+    @Override public void setApplicationContext(ApplicationContext ctx) {
+        this.springCtx = ctx;
+    }
+
     /**
      * Gets configuration file path.
      *
@@ -257,9 +268,9 @@ public class SpringCacheManager implements CacheManager, InitializingBean {
         }
 
         if (cfgPath != null)
-            ignite = Ignition.start(cfgPath);
+            ignite = IgniteSpring.start(cfgPath, springCtx);
         else if (cfg != null)
-            ignite = Ignition.start(cfg);
+            ignite = IgniteSpring.start(cfg, springCtx);
         else
             ignite = Ignition.ignite(gridName);
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/a39770aa/modules/spring/src/main/java/org/apache/ignite/transactions/spring/SpringTransactionManager.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/main/java/org/apache/ignite/transactions/spring/SpringTransactionManager.java b/modules/spring/src/main/java/org/apache/ignite/transactions/spring/SpringTransactionManager.java
index d8bbbbd..32a7b43 100644
--- a/modules/spring/src/main/java/org/apache/ignite/transactions/spring/SpringTransactionManager.java
+++ b/modules/spring/src/main/java/org/apache/ignite/transactions/spring/SpringTransactionManager.java
@@ -21,12 +21,15 @@ import java.util.concurrent.TimeUnit;
 import org.apache.ignite.Ignite;
 import org.apache.ignite.IgniteException;
 import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.IgniteSpring;
 import org.apache.ignite.Ignition;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.transactions.Transaction;
 import org.apache.ignite.transactions.TransactionConcurrency;
 import org.apache.ignite.transactions.TransactionIsolation;
 import org.springframework.beans.factory.InitializingBean;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
 import org.springframework.transaction.CannotCreateTransactionException;
 import org.springframework.transaction.InvalidIsolationLevelException;
 import org.springframework.transaction.PlatformTransactionManager;
@@ -194,7 +197,7 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
  * </pre>
  */
 public class SpringTransactionManager extends AbstractPlatformTransactionManager
-    implements ResourceTransactionManager, PlatformTransactionManager, InitializingBean {
+    implements ResourceTransactionManager, PlatformTransactionManager, InitializingBean, ApplicationContextAware {
     /**
      * Logger.
      */
@@ -225,6 +228,14 @@ public class SpringTransactionManager extends AbstractPlatformTransactionManager
      */
     private Ignite ignite;
 
+    /** Spring context */
+    private ApplicationContext springCtx;
+
+    /** {@inheritDoc} */
+    @Override public void setApplicationContext(ApplicationContext ctx) {
+        this.springCtx = ctx;
+    }
+
     /**
      * Constructs the transaction manager with no target Ignite instance. An
      * instance must be set before use.
@@ -319,9 +330,9 @@ public class SpringTransactionManager extends AbstractPlatformTransactionManager
         }
 
         if (cfgPath != null)
-            ignite = Ignition.start(cfgPath);
+            ignite = IgniteSpring.start(cfgPath, springCtx);
         else if (cfg != null)
-            ignite = Ignition.start(cfg);
+            ignite = IgniteSpring.start(cfg, springCtx);
         else
             ignite = Ignition.ignite(gridName);
 
@@ -335,12 +346,12 @@ public class SpringTransactionManager extends AbstractPlatformTransactionManager
      * {@inheritDoc}
      */
     @Override protected Object doGetTransaction() throws TransactionException {
-        IgniteTransactionObject txObject = new IgniteTransactionObject();
+        IgniteTransactionObject txObj = new IgniteTransactionObject();
 
-        txObject.setTransactionHolder(
+        txObj.setTransactionHolder(
             (IgniteTransactionHolder)TransactionSynchronizationManager.getResource(this.ignite), false);
 
-        return txObject;
+        return txObj;
     }
 
     /**
@@ -350,11 +361,11 @@ public class SpringTransactionManager extends AbstractPlatformTransactionManager
         if (definition.getIsolationLevel() == TransactionDefinition.ISOLATION_READ_UNCOMMITTED)
             throw new InvalidIsolationLevelException("Ignite does not support READ_UNCOMMITTED isolation level.");
 
-        IgniteTransactionObject txObject = (IgniteTransactionObject)transaction;
+        IgniteTransactionObject txObj = (IgniteTransactionObject)transaction;
         Transaction tx = null;
 
         try {
-            if (txObject.getTransactionHolder() == null || txObject.getTransactionHolder().isSynchronizedWithTransaction()) {
+            if (txObj.getTransactionHolder() == null || txObj.getTransactionHolder().isSynchronizedWithTransaction()) {
                 long timeout = ignite.configuration().getTransactionConfiguration().getDefaultTxTimeout();
 
                 if (definition.getTimeout() > 0)
@@ -366,17 +377,17 @@ public class SpringTransactionManager extends AbstractPlatformTransactionManager
                 if (log.isDebugEnabled())
                     log.debug("Started Ignite transaction: " + newTx);
 
-                txObject.setTransactionHolder(new IgniteTransactionHolder(newTx), true);
+                txObj.setTransactionHolder(new IgniteTransactionHolder(newTx), true);
             }
 
-            txObject.getTransactionHolder().setSynchronizedWithTransaction(true);
-            txObject.getTransactionHolder().setTransactionActive(true);
+            txObj.getTransactionHolder().setSynchronizedWithTransaction(true);
+            txObj.getTransactionHolder().setTransactionActive(true);
 
-            tx = txObject.getTransactionHolder().getTransaction();
+            tx = txObj.getTransactionHolder().getTransaction();
 
             // Bind the session holder to the thread.
-            if (txObject.isNewTransactionHolder())
-                TransactionSynchronizationManager.bindResource(this.ignite, txObject.getTransactionHolder());
+            if (txObj.isNewTransactionHolder())
+                TransactionSynchronizationManager.bindResource(this.ignite, txObj.getTransactionHolder());
         }
         catch (Exception ex) {
             if (tx != null)
@@ -390,8 +401,8 @@ public class SpringTransactionManager extends AbstractPlatformTransactionManager
      * {@inheritDoc}
      */
     @Override protected void doCommit(DefaultTransactionStatus status) throws TransactionException {
-        IgniteTransactionObject txObject = (IgniteTransactionObject)status.getTransaction();
-        Transaction tx = txObject.getTransactionHolder().getTransaction();
+        IgniteTransactionObject txObj = (IgniteTransactionObject)status.getTransaction();
+        Transaction tx = txObj.getTransactionHolder().getTransaction();
 
         if (status.isDebug() && log.isDebugEnabled())
             log.debug("Committing Ignite transaction: " + tx);
@@ -408,8 +419,8 @@ public class SpringTransactionManager extends AbstractPlatformTransactionManager
      * {@inheritDoc}
      */
     @Override protected void doRollback(DefaultTransactionStatus status) throws TransactionException {
-        IgniteTransactionObject txObject = (IgniteTransactionObject)status.getTransaction();
-        Transaction tx = txObject.getTransactionHolder().getTransaction();
+        IgniteTransactionObject txObj = (IgniteTransactionObject)status.getTransaction();
+        Transaction tx = txObj.getTransactionHolder().getTransaction();
 
         if (status.isDebug() && log.isDebugEnabled())
             log.debug("Rolling back Ignite transaction: " + tx);
@@ -426,27 +437,27 @@ public class SpringTransactionManager extends AbstractPlatformTransactionManager
      * {@inheritDoc}
      */
     @Override protected void doCleanupAfterCompletion(Object transaction) {
-        IgniteTransactionObject txObject = (IgniteTransactionObject)transaction;
+        IgniteTransactionObject txObj = (IgniteTransactionObject)transaction;
 
         // Remove the transaction holder from the thread, if exposed.
-        if (txObject.isNewTransactionHolder()) {
-            Transaction tx = txObject.getTransactionHolder().getTransaction();
+        if (txObj.isNewTransactionHolder()) {
+            Transaction tx = txObj.getTransactionHolder().getTransaction();
             TransactionSynchronizationManager.unbindResource(this.ignite);
 
             if (log.isDebugEnabled())
                 log.debug("Releasing Ignite transaction: " + tx);
         }
 
-        txObject.getTransactionHolder().clear();
+        txObj.getTransactionHolder().clear();
     }
 
     /**
      * {@inheritDoc}
      */
     @Override protected boolean isExistingTransaction(Object transaction) throws TransactionException {
-        IgniteTransactionObject txObject = (IgniteTransactionObject)transaction;
+        IgniteTransactionObject txObj = (IgniteTransactionObject)transaction;
 
-        return (txObject.getTransactionHolder() != null && txObject.getTransactionHolder().isTransactionActive());
+        return (txObj.getTransactionHolder() != null && txObj.getTransactionHolder().isTransactionActive());
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/a39770aa/modules/spring/src/test/java/config/spring-transactions.xml
----------------------------------------------------------------------
diff --git a/modules/spring/src/test/java/config/spring-transactions.xml b/modules/spring/src/test/java/config/spring-transactions.xml
index ba90cb0..392bd84 100644
--- a/modules/spring/src/test/java/config/spring-transactions.xml
+++ b/modules/spring/src/test/java/config/spring-transactions.xml
@@ -27,7 +27,9 @@
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
 
     <tx:annotation-driven/>
-    <context:component-scan base-package="org.apache.ignite.transactions.spring"/>
+    <context:component-scan base-package="org.apache.ignite.transactions.spring">
+        <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
+    </context:component-scan>
 
     <bean id="transactionManager" class="org.apache.ignite.transactions.spring.SpringTransactionManager">
         <property name="transactionConcurrency" value="OPTIMISTIC"/>

http://git-wip-us.apache.org/repos/asf/ignite/blob/a39770aa/modules/spring/src/test/java/org/apache/ignite/TestInjectionLifecycleBean.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/test/java/org/apache/ignite/TestInjectionLifecycleBean.java b/modules/spring/src/test/java/org/apache/ignite/TestInjectionLifecycleBean.java
new file mode 100644
index 0000000..2b8c932
--- /dev/null
+++ b/modules/spring/src/test/java/org/apache/ignite/TestInjectionLifecycleBean.java
@@ -0,0 +1,42 @@
+/*
+ * 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;
+
+import org.apache.ignite.lifecycle.LifecycleBean;
+import org.apache.ignite.lifecycle.LifecycleEventType;
+import org.apache.ignite.resources.SpringApplicationContextResource;
+import org.springframework.context.ApplicationContext;
+
+import static org.junit.Assert.assertNotNull;
+
+/** Lifecycle bean for testing. */
+public class TestInjectionLifecycleBean implements LifecycleBean {
+    /** */
+    @SpringApplicationContextResource
+    private ApplicationContext appCtx;
+
+    /** Checks that context was injected. */
+    public void checkState() {
+        assertNotNull(appCtx);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void onLifecycleEvent(LifecycleEventType evt) {
+        checkState();
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/a39770aa/modules/spring/src/test/java/org/apache/ignite/spring-injection-test.xml
----------------------------------------------------------------------
diff --git a/modules/spring/src/test/java/org/apache/ignite/spring-injection-test.xml b/modules/spring/src/test/java/org/apache/ignite/spring-injection-test.xml
new file mode 100644
index 0000000..b8368a3
--- /dev/null
+++ b/modules/spring/src/test/java/org/apache/ignite/spring-injection-test.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+  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.
+-->
+
+<!--
+    GridGain Spring configuration file to startup grid cache.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:util="http://www.springframework.org/schema/util"
+       xsi:schemaLocation="
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans.xsd
+        http://www.springframework.org/schema/util
+        http://www.springframework.org/schema/util/spring-util.xsd">
+    <bean id="grid.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
+        <property name="lifecycleBeans">
+            <array>
+                <bean id="bean1" class="org.apache.ignite.TestInjectionLifecycleBean"/>
+                <bean id="bean2" class="org.apache.ignite.TestInjectionLifecycleBean"/>
+            </array>
+        </property>
+
+        <property name="localHost" value="127.0.0.1"/>
+
+        <property name="gridName" value="springInjectionTest"/>
+    </bean>
+</beans>

http://git-wip-us.apache.org/repos/asf/ignite/blob/a39770aa/modules/spring/src/test/java/org/apache/ignite/spring/SpringCacheManagerContextInjectionTest.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/test/java/org/apache/ignite/spring/SpringCacheManagerContextInjectionTest.java b/modules/spring/src/test/java/org/apache/ignite/spring/SpringCacheManagerContextInjectionTest.java
new file mode 100644
index 0000000..1554198
--- /dev/null
+++ b/modules/spring/src/test/java/org/apache/ignite/spring/SpringCacheManagerContextInjectionTest.java
@@ -0,0 +1,126 @@
+/*
+ *  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.spring;
+
+import org.apache.ignite.Ignite;
+import org.apache.ignite.TestInjectionLifecycleBean;
+import org.apache.ignite.cache.spring.SpringCacheManager;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgnitionEx;
+import org.apache.ignite.lifecycle.LifecycleBean;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.springframework.beans.factory.BeanFactory;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ *
+ */
+public class SpringCacheManagerContextInjectionTest extends GridCommonAbstractTest {
+    /**
+     * @throws Exception If failed.
+     */
+    public void testBeanInjectionUsingConfigPath() throws Exception {
+        new AnnotationConfigApplicationContext(TestPathConfiguration.class);
+
+        Ignite grid = IgnitionEx.grid("springInjectionTest");
+
+        IgniteConfiguration cfg = grid.configuration();
+
+        LifecycleBean[] beans = cfg.getLifecycleBeans();
+
+        assertEquals(2, beans.length);
+
+        TestInjectionLifecycleBean bean1 = (TestInjectionLifecycleBean)beans[0];
+        TestInjectionLifecycleBean bean2 = (TestInjectionLifecycleBean)beans[1];
+
+        bean1.checkState();
+        bean2.checkState();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testBeanInjectionUsingConfiguration() throws Exception {
+        BeanFactory factory = new AnnotationConfigApplicationContext(TestCfgConfiguration.class);
+
+        TestInjectionLifecycleBean bean1 = (TestInjectionLifecycleBean)factory.getBean("bean1");
+        TestInjectionLifecycleBean bean2 = (TestInjectionLifecycleBean)factory.getBean("bean2");
+
+        bean1.checkState();
+        bean2.checkState();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopAllGrids();
+
+        super.afterTest();
+    }
+
+    /** */
+    @SuppressWarnings("WeakerAccess")
+    @Configuration
+    static class TestPathConfiguration {
+        /** */
+        @Bean(name = "mgr")
+        public SpringCacheManager springCacheManager() {
+            SpringCacheManager mgr = new SpringCacheManager();
+
+            mgr.setConfigurationPath("org/apache/ignite/spring-injection-test.xml");
+
+            return mgr;
+        }
+    }
+
+    /** */
+    @SuppressWarnings("WeakerAccess")
+    @Configuration
+    static class TestCfgConfiguration {
+        /** */
+        @Bean(name = "mgr")
+        public SpringCacheManager springCacheManager() {
+            IgniteConfiguration cfg = new IgniteConfiguration();
+
+            cfg.setLocalHost("127.0.0.1");
+
+            cfg.setGridName("scmt");
+
+            cfg.setLifecycleBeans(bean1(), bean2());
+
+            SpringCacheManager mgr = new SpringCacheManager();
+
+            mgr.setConfiguration(cfg);
+
+            return mgr;
+        }
+
+        /** */
+        @Bean(name = "bean1")
+        LifecycleBean bean1() {
+            return new TestInjectionLifecycleBean();
+        }
+
+        /** */
+        @Bean(name = "bean2")
+        LifecycleBean bean2() {
+            return new TestInjectionLifecycleBean();
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/a39770aa/modules/spring/src/test/java/org/apache/ignite/testsuites/IgniteSpringTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/test/java/org/apache/ignite/testsuites/IgniteSpringTestSuite.java b/modules/spring/src/test/java/org/apache/ignite/testsuites/IgniteSpringTestSuite.java
index 4fc159e..9ae3423 100644
--- a/modules/spring/src/test/java/org/apache/ignite/testsuites/IgniteSpringTestSuite.java
+++ b/modules/spring/src/test/java/org/apache/ignite/testsuites/IgniteSpringTestSuite.java
@@ -28,8 +28,10 @@ import org.apache.ignite.p2p.GridP2PUserVersionChangeSelfTest;
 import org.apache.ignite.spring.GridSpringCacheManagerSelfTest;
 import org.apache.ignite.spring.IgniteExcludeInConfigurationTest;
 import org.apache.ignite.spring.IgniteStartFromStreamConfigurationTest;
+import org.apache.ignite.spring.SpringCacheManagerContextInjectionTest;
 import org.apache.ignite.spring.injection.GridServiceInjectionSpringResourceTest;
 import org.apache.ignite.transactions.spring.GridSpringTransactionManagerSelfTest;
+import org.apache.ignite.transactions.spring.SpringTransactionManagerContextInjectionTest;
 
 /**
  * Spring tests.
@@ -68,6 +70,9 @@ public class IgniteSpringTestSuite extends TestSuite {
 
         suite.addTestSuite(GridServiceInjectionSpringResourceTest.class);
 
+        suite.addTestSuite(SpringCacheManagerContextInjectionTest.class);
+        suite.addTestSuite(SpringTransactionManagerContextInjectionTest.class);
+
         return suite;
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/a39770aa/modules/spring/src/test/java/org/apache/ignite/transactions/spring/SpringTransactionManagerContextInjectionTest.java
----------------------------------------------------------------------
diff --git a/modules/spring/src/test/java/org/apache/ignite/transactions/spring/SpringTransactionManagerContextInjectionTest.java b/modules/spring/src/test/java/org/apache/ignite/transactions/spring/SpringTransactionManagerContextInjectionTest.java
new file mode 100644
index 0000000..467be20
--- /dev/null
+++ b/modules/spring/src/test/java/org/apache/ignite/transactions/spring/SpringTransactionManagerContextInjectionTest.java
@@ -0,0 +1,125 @@
+/*
+ *  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.transactions.spring;
+
+import org.apache.ignite.Ignite;
+import org.apache.ignite.TestInjectionLifecycleBean;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgnitionEx;
+import org.apache.ignite.lifecycle.LifecycleBean;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.springframework.beans.factory.BeanFactory;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ *
+ */
+public class SpringTransactionManagerContextInjectionTest extends GridCommonAbstractTest {
+    /**
+     * @throws Exception If failed.
+     */
+    public void testBeanInjectionUsingConfigPath() throws Exception {
+        BeanFactory factory = new AnnotationConfigApplicationContext(TestPathConfiguration.class);
+
+        Ignite grid = IgnitionEx.grid("springInjectionTest");
+
+        IgniteConfiguration cfg = grid.configuration();
+
+        LifecycleBean[] beans = cfg.getLifecycleBeans();
+
+        assertEquals(2, beans.length);
+
+        TestInjectionLifecycleBean bean1 = (TestInjectionLifecycleBean)beans[0];
+        TestInjectionLifecycleBean bean2 = (TestInjectionLifecycleBean)beans[1];
+
+        bean1.checkState();
+        bean2.checkState();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testBeanInjectionUsingConfig() throws Exception {
+        BeanFactory factory = new AnnotationConfigApplicationContext(TestCfgConfiguration.class);
+
+        TestInjectionLifecycleBean bean1 = (TestInjectionLifecycleBean)factory.getBean("bean1");
+        TestInjectionLifecycleBean bean2 = (TestInjectionLifecycleBean)factory.getBean("bean2");
+
+        bean1.checkState();
+        bean2.checkState();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopAllGrids();
+
+        super.afterTest();
+    }
+
+    /** */
+    @SuppressWarnings("WeakerAccess")
+    @Configuration
+    static class TestPathConfiguration {
+        /** */
+        @Bean(name = "mgr")
+        public SpringTransactionManager springTransactionManager() {
+            SpringTransactionManager mgr = new SpringTransactionManager();
+
+            mgr.setConfigurationPath("org/apache/ignite/spring-injection-test.xml");
+
+            return mgr;
+        }
+    }
+
+    /** */
+    @SuppressWarnings("WeakerAccess")
+    @Configuration
+    static class TestCfgConfiguration {
+        /** */
+        @Bean(name = "mgr")
+        public SpringTransactionManager springTransactionManager() {
+            IgniteConfiguration cfg = new IgniteConfiguration();
+
+            cfg.setLocalHost("127.0.0.1");
+
+            cfg.setGridName("stmcit");
+
+            cfg.setLifecycleBeans(bean1(), bean2());
+
+            SpringTransactionManager mgr = new SpringTransactionManager();
+
+            mgr.setConfiguration(cfg);
+
+            return mgr;
+        }
+
+        /** */
+        @Bean(name = "bean1")
+        LifecycleBean bean1() {
+            return new TestInjectionLifecycleBean();
+        }
+
+        /** */
+        @Bean(name = "bean2")
+        LifecycleBean bean2() {
+            return new TestInjectionLifecycleBean();
+        }
+    }
+}
\ No newline at end of file


[47/50] [abbrv] ignite git commit: IGNITE-2649: Ensured correct local Ignite instance processing during serialization and deserialization.

Posted by vo...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsFullMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsFullMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsFullMessage.java
index 6194552..0498c20 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsFullMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsFullMessage.java
@@ -28,7 +28,9 @@ import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
@@ -133,10 +135,10 @@ public class GridDhtPartitionsFullMessage extends GridDhtPartitionsAbstractMessa
         super.prepareMarshal(ctx);
 
         if (parts != null && partsBytes == null)
-            partsBytes = ctx.marshaller().marshal(parts);
+            partsBytes = CU.marshal(ctx, parts);
 
         if (partCntrs != null)
-            partCntrsBytes = ctx.marshaller().marshal(partCntrs);
+            partCntrsBytes = CU.marshal(ctx, partCntrs);
     }
 
     /**
@@ -157,14 +159,18 @@ public class GridDhtPartitionsFullMessage extends GridDhtPartitionsAbstractMessa
     @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
         super.finishUnmarshal(ctx, ldr);
 
-        if (partsBytes != null && parts == null)
-            parts = ctx.marshaller().unmarshal(partsBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (partsBytes != null && parts == null) {
+            parts = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), partsBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
 
         if (parts == null)
             parts = new HashMap<>();
 
-        if (partCntrsBytes != null && partCntrs == null)
-            partCntrs = ctx.marshaller().unmarshal(partCntrsBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (partCntrsBytes != null && partCntrs == null) {
+            partCntrs = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), partCntrsBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
 
         if (partCntrs == null)
             partCntrs = new HashMap<>();

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleMessage.java
index 0fe4259..38307e1 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsSingleMessage.java
@@ -27,7 +27,9 @@ import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
@@ -137,21 +139,25 @@ public class GridDhtPartitionsSingleMessage extends GridDhtPartitionsAbstractMes
         super.prepareMarshal(ctx);
 
         if (partsBytes == null && parts != null)
-            partsBytes = ctx.marshaller().marshal(parts);
+            partsBytes = CU.marshal(ctx, parts);
 
         if (partCntrs != null)
-            partCntrsBytes = ctx.marshaller().marshal(partCntrs);
+            partCntrsBytes = CU.marshal(ctx, partCntrs);
     }
 
     /** {@inheritDoc} */
     @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
         super.finishUnmarshal(ctx, ldr);
 
-        if (partsBytes != null && parts == null)
-            parts = ctx.marshaller().unmarshal(partsBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (partsBytes != null && parts == null) {
+            parts = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), partsBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
 
-        if (partCntrsBytes != null)
-            partCntrs = ctx.marshaller().unmarshal(partCntrsBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (partCntrsBytes != null) {
+            partCntrs = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), partCntrsBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetResponse.java
index be92551..03ddf43 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearGetResponse.java
@@ -34,9 +34,11 @@ import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersionable;
 import org.apache.ignite.internal.util.GridLeanSet;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteUuid;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
@@ -190,7 +192,7 @@ public class GridNearGetResponse extends GridCacheMessage implements GridCacheDe
         }
 
         if (err != null)
-            errBytes = ctx.marshaller().marshal(err);
+            errBytes = CU.marshal(ctx, err);
     }
 
     /** {@inheritDoc} */
@@ -204,8 +206,10 @@ public class GridNearGetResponse extends GridCacheMessage implements GridCacheDe
                 info.unmarshal(cctx, ldr);
         }
 
-        if (errBytes != null)
-            err = ctx.marshaller().unmarshal(errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (errBytes != null) {
+            err = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), errBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearSingleGetResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearSingleGetResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearSingleGetResponse.java
index e8d164f..19b2163 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearSingleGetResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearSingleGetResponse.java
@@ -27,7 +27,9 @@ import org.apache.ignite.internal.processors.cache.GridCacheDeployable;
 import org.apache.ignite.internal.processors.cache.GridCacheEntryInfo;
 import org.apache.ignite.internal.processors.cache.GridCacheMessage;
 import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.Message;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
@@ -169,7 +171,7 @@ public class GridNearSingleGetResponse extends GridCacheMessage implements GridC
         }
 
         if (err != null)
-            errBytes = ctx.marshaller().marshal(err);
+            errBytes = CU.marshal(ctx, err);
     }
 
     /** {@inheritDoc} */
@@ -187,8 +189,10 @@ public class GridNearSingleGetResponse extends GridCacheMessage implements GridC
                 ((GridCacheEntryInfo)res).unmarshal(cctx, ldr);
         }
 
-        if (errBytes != null && err == null)
-            err = ctx.marshaller().unmarshal(errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (errBytes != null && err == null) {
+            err = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), errBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishResponse.java
index 4055b2a..e01eb9d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishResponse.java
@@ -24,9 +24,11 @@ import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.distributed.GridDistributedTxFinishResponse;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteUuid;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
 import org.jetbrains.annotations.Nullable;
@@ -101,15 +103,17 @@ public class GridNearTxFinishResponse extends GridDistributedTxFinishResponse {
         super.prepareMarshal(ctx);
 
         if (err != null)
-            errBytes = ctx.marshaller().marshal(err);
+            errBytes = CU.marshal(ctx, err);
     }
 
     /** {@inheritDoc} */
     @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
         super.finishUnmarshal(ctx, ldr);
 
-        if (errBytes != null)
-            err = ctx.marshaller().unmarshal(errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (errBytes != null) {
+            err = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), errBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheLocalQueryFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheLocalQueryFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheLocalQueryFuture.java
index 91ae12c..7f33220 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheLocalQueryFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheLocalQueryFuture.java
@@ -26,6 +26,7 @@ import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteClosure;
 import org.apache.ignite.lang.IgniteReducer;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 
 /**
  * Local query future.
@@ -113,11 +114,11 @@ public class GridCacheLocalQueryFuture<K, V, R> extends GridCacheQueryFutureAdap
             Marshaller marsh = cctx.marshaller();
 
             IgniteReducer<Object, Object> rdc = qry.reducer() != null ?
-                marsh.<IgniteReducer<Object, Object>>unmarshal(marsh.marshal(qry.reducer()),
+                MarshallerUtils.marshalUnmarshal(cctx.gridName(), marsh, qry.reducer(),
                     U.resolveClassLoader(cctx.gridConfig())) : null;
 
             IgniteClosure<Object, Object> trans = qry.transform() != null ?
-                marsh.<IgniteClosure<Object, Object>>unmarshal(marsh.marshal(qry.transform()),
+                MarshallerUtils.marshalUnmarshal(cctx.gridName(), marsh, qry.transform(),
                     U.resolveClassLoader(cctx.gridConfig())) : null;
 
             return new GridCacheQueryInfo(

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryRequest.java
index 88ebe99..08cbb29 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryRequest.java
@@ -35,6 +35,7 @@ import org.apache.ignite.lang.IgniteBiPredicate;
 import org.apache.ignite.lang.IgniteClosure;
 import org.apache.ignite.lang.IgniteReducer;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
 import org.jetbrains.annotations.Nullable;
@@ -316,19 +317,25 @@ public class GridCacheQueryRequest extends GridCacheMessage implements GridCache
     @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
         super.finishUnmarshal(ctx, ldr);
 
-        Marshaller mrsh = ctx.marshaller();
+        Marshaller marsh = ctx.marshaller();
 
-        if (keyValFilterBytes != null)
-            keyValFilter = mrsh.unmarshal(keyValFilterBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (keyValFilterBytes != null) {
+            keyValFilter = MarshallerUtils.unmarshal(ctx.gridName(), marsh, keyValFilterBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
 
         if (rdcBytes != null)
-            rdc = mrsh.unmarshal(rdcBytes, ldr);
+            rdc = MarshallerUtils.unmarshal(ctx.gridName(), marsh, rdcBytes, ldr);
 
-        if (transBytes != null)
-            trans = mrsh.unmarshal(transBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (transBytes != null) {
+            trans = MarshallerUtils.unmarshal(ctx.gridName(), marsh, transBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
 
-        if (argsBytes != null)
-            args = mrsh.unmarshal(argsBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (argsBytes != null) {
+            args = MarshallerUtils.unmarshal(ctx.gridName(), marsh, argsBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
     }
 
     /** {@inheritDoc} */
@@ -343,9 +350,10 @@ public class GridCacheQueryRequest extends GridCacheMessage implements GridCache
     void beforeLocalExecution(GridCacheContext ctx) throws IgniteCheckedException {
         Marshaller marsh = ctx.marshaller();
 
-        rdc = rdc != null ? marsh.<IgniteReducer<Object, Object>>unmarshal(marsh.marshal(rdc),
+        rdc = rdc != null ? MarshallerUtils.marshalUnmarshal(ctx.gridName(), marsh, rdc,
             U.resolveClassLoader(ctx.gridConfig())) : null;
-        trans = trans != null ? marsh.<IgniteClosure<Object, Object>>unmarshal(marsh.marshal(trans),
+
+        trans = trans != null ? MarshallerUtils.marshalUnmarshal(ctx.gridName(), marsh, trans,
             U.resolveClassLoader(ctx.gridConfig())) : null;
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryResponse.java
index 2cde8f4..a015ac5 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheQueryResponse.java
@@ -32,7 +32,9 @@ import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.query.GridQueryFieldMetadata;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
@@ -124,7 +126,7 @@ public class GridCacheQueryResponse extends GridCacheMessage implements GridCach
         GridCacheContext cctx = ctx.cacheContext(cacheId);
 
         if (err != null)
-            errBytes = ctx.marshaller().marshal(err);
+            errBytes = CU.marshal(ctx, err);
 
         metaDataBytes = marshalCollection(metadata, cctx);
         dataBytes = marshalCollection(data, cctx);
@@ -145,8 +147,10 @@ public class GridCacheQueryResponse extends GridCacheMessage implements GridCach
     @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
         super.finishUnmarshal(ctx, ldr);
 
-        if (errBytes != null)
-            err = ctx.marshaller().unmarshal(errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (errBytes != null) {
+            err = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), errBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
 
         metadata = unmarshalCollection(metaDataBytes, ctx, ldr);
         data = unmarshalCollection(dataBytes, ctx, ldr);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheSqlQuery.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheSqlQuery.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheSqlQuery.java
index 0733827..7a77ea5 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheSqlQuery.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/GridCacheSqlQuery.java
@@ -28,6 +28,7 @@ import org.apache.ignite.internal.util.typedef.internal.A;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.Message;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
@@ -132,19 +133,21 @@ public class GridCacheSqlQuery implements Message {
 
     /**
      * @param m Marshaller.
+     * @param kernalCtx kernal context.
      * @throws IgniteCheckedException If failed.
      */
-    public void marshallParams(Marshaller m) throws IgniteCheckedException {
+    public void marshallParams(Marshaller m, final GridKernalContext kernalCtx) throws IgniteCheckedException {
         if (paramsBytes != null)
             return;
 
         assert params != null;
 
-        paramsBytes = m.marshal(params);
+        paramsBytes = MarshallerUtils.marshal(kernalCtx.gridName(), m, params);
     }
 
     /**
      * @param m Marshaller.
+     * @param ctx kernal context.
      * @throws IgniteCheckedException If failed.
      */
     public void unmarshallParams(Marshaller m, GridKernalContext ctx) throws IgniteCheckedException {
@@ -153,7 +156,7 @@ public class GridCacheSqlQuery implements Message {
 
         assert paramsBytes != null;
 
-        params = m.unmarshal(paramsBytes, U.resolveClassLoader(ctx.config()));
+        params = MarshallerUtils.unmarshal(ctx.gridName(), m, paramsBytes, U.resolveClassLoader(ctx.config()));
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryHandler.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryHandler.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryHandler.java
index fc38eba..627a04b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryHandler.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryHandler.java
@@ -77,6 +77,7 @@ import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteAsyncCallback;
 import org.apache.ignite.lang.IgniteBiTuple;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.thread.IgniteStripedThreadPoolExecutor;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -1541,7 +1542,7 @@ public class CacheContinuousQueryHandler<K, V> implements GridContinuousHandler
 
             depInfo = new GridDeploymentInfoBean(dep);
 
-            bytes = ctx.config().getMarshaller().marshal(obj);
+            bytes = MarshallerUtils.marshal(ctx, obj);
         }
 
         /**
@@ -1559,7 +1560,8 @@ public class CacheContinuousQueryHandler<K, V> implements GridContinuousHandler
             if (dep == null)
                 throw new IgniteDeploymentCheckedException("Failed to obtain deployment for class: " + clsName);
 
-            return ctx.config().getMarshaller().unmarshal(bytes, U.resolveClassLoader(dep.classLoader(), ctx.config()));
+            return MarshallerUtils.unmarshal(ctx.gridName(), ctx.config().getMarshaller(), bytes,
+                U.resolveClassLoader(dep.classLoader(), ctx.config()));
         }
 
         /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/jdbc/GridCacheQueryJdbcMetadataTask.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/jdbc/GridCacheQueryJdbcMetadataTask.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/jdbc/GridCacheQueryJdbcMetadataTask.java
index a8b2da4..d659f10 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/jdbc/GridCacheQueryJdbcMetadataTask.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/jdbc/GridCacheQueryJdbcMetadataTask.java
@@ -41,6 +41,7 @@ import org.apache.ignite.internal.processors.cache.query.GridCacheSqlMetadata;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.resources.IgniteInstanceResource;
 import org.apache.ignite.resources.LoggerResource;
@@ -153,7 +154,7 @@ public class GridCacheQueryJdbcMetadataTask extends ComputeTaskAdapter<String, b
 
                 status = 0;
 
-                data = MARSHALLER.marshal(F.asList(schemasMap, indexesInfo));
+                data = MarshallerUtils.marshal(ignite.name(), MARSHALLER, F.asList(schemasMap, indexesInfo));
             }
             catch (Throwable t) {
                 U.error(log, "Failed to get metadata for JDBC.", t);
@@ -163,7 +164,7 @@ public class GridCacheQueryJdbcMetadataTask extends ComputeTaskAdapter<String, b
                 status = 1;
 
                 try {
-                    data = MARSHALLER.marshal(err);
+                    data = MarshallerUtils.marshal(ignite.name(), MARSHALLER, err);
                 }
                 catch (IgniteCheckedException e) {
                     throw new IgniteException(e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/jdbc/GridCacheQueryJdbcTask.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/jdbc/GridCacheQueryJdbcTask.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/jdbc/GridCacheQueryJdbcTask.java
index 5c60762..a6c5f14 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/jdbc/GridCacheQueryJdbcTask.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/jdbc/GridCacheQueryJdbcTask.java
@@ -52,6 +52,7 @@ import org.apache.ignite.internal.util.typedef.CAX;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.resources.IgniteInstanceResource;
 import org.apache.ignite.resources.LoggerResource;
@@ -82,7 +83,7 @@ public class GridCacheQueryJdbcTask extends ComputeTaskAdapter<byte[], byte[]> {
         try {
             assert arg != null;
 
-            Map<String, Object> args = MARSHALLER.unmarshal(arg, null);
+            Map<String, Object> args = MarshallerUtils.unmarshal(ignite.name(), MARSHALLER, arg, null);
 
             boolean first = true;
 
@@ -130,12 +131,13 @@ public class GridCacheQueryJdbcTask extends ComputeTaskAdapter<byte[], byte[]> {
             if (res.getException() == null) {
                 status = 0;
 
-                bytes = MARSHALLER.marshal(res.getData());
+                bytes = MarshallerUtils.marshal(ignite.name(), MARSHALLER, res.getData());
             }
             else {
                 status = 1;
 
-                bytes = MARSHALLER.marshal(new SQLException(res.getException().getMessage()));
+                bytes = MarshallerUtils.marshal(ignite.name(), MARSHALLER, new SQLException(res.getException().getMessage())
+                );
             }
 
             byte[] packet = new byte[bytes.length + 1];

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxEntry.java
index 3258ce9..e7fc5de 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxEntry.java
@@ -48,6 +48,7 @@ import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.T2;
 import org.apache.ignite.internal.util.typedef.internal.CU;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.Message;
 import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
@@ -878,8 +879,8 @@ public class IgniteTxEntry implements GridPeerDeployAware, Message {
 
         // Unmarshal transform closure anyway if it exists.
         if (transformClosBytes != null && entryProcessorsCol == null)
-            entryProcessorsCol = ctx.marshaller().unmarshal(transformClosBytes,
-                U.resolveClassLoader(clsLdr, ctx.gridConfig()));
+            entryProcessorsCol = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(),
+                    transformClosBytes, U.resolveClassLoader(clsLdr, ctx.gridConfig()));
 
         if (filters == null)
             filters = CU.empty0();
@@ -894,8 +895,10 @@ public class IgniteTxEntry implements GridPeerDeployAware, Message {
 
         val.unmarshal(this.ctx, clsLdr);
 
-        if (expiryPlcBytes != null)
-            expiryPlc = ctx.marshaller().unmarshal(expiryPlcBytes, U.resolveClassLoader(clsLdr, ctx.gridConfig()));
+        if (expiryPlcBytes != null) {
+            expiryPlc = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), expiryPlcBytes,
+                U.resolveClassLoader(clsLdr, ctx.gridConfig()));
+        }
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheRawVersionedEntry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheRawVersionedEntry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheRawVersionedEntry.java
index 4c5a704..98c651b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheRawVersionedEntry.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/version/GridCacheRawVersionedEntry.java
@@ -31,6 +31,7 @@ import org.apache.ignite.internal.processors.datastreamer.DataStreamerEntry;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
 import org.jetbrains.annotations.Nullable;
@@ -191,7 +192,8 @@ public class GridCacheRawVersionedEntry<K, V> extends DataStreamerEntry implemen
         unmarshalKey(ctx, marsh);
 
         if (val == null && valBytes != null) {
-            val = marsh.unmarshal(valBytes, U.resolveClassLoader(ctx.kernalContext().config()));
+            val = MarshallerUtils.unmarshal(ctx.kernalContext().gridName(), marsh, valBytes,
+                U.resolveClassLoader(ctx.kernalContext().config()));
 
             val.finishUnmarshal(ctx, null);
         }
@@ -222,7 +224,8 @@ public class GridCacheRawVersionedEntry<K, V> extends DataStreamerEntry implemen
         if (key == null) {
             assert keyBytes != null;
 
-            key = marsh.unmarshal(keyBytes, U.resolveClassLoader(ctx.kernalContext().config()));
+            key = MarshallerUtils.unmarshal(ctx.kernalContext().gridName(), marsh, keyBytes,
+                U.resolveClassLoader(ctx.kernalContext().config()));
 
             key.finishUnmarshal(ctx, null);
         }
@@ -239,13 +242,13 @@ public class GridCacheRawVersionedEntry<K, V> extends DataStreamerEntry implemen
         if (keyBytes == null) {
             key.prepareMarshal(ctx);
 
-            keyBytes = marsh.marshal(key);
+            keyBytes = MarshallerUtils.marshal(ctx.kernalContext().gridName(), marsh, key);
         }
 
         if (valBytes == null && val != null) {
             val.prepareMarshal(ctx);
 
-            valBytes = marsh.marshal(val);
+            valBytes = MarshallerUtils.marshal(ctx.kernalContext().gridName(), marsh, val);
         }
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessorImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessorImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessorImpl.java
index 6630c7a..a3070e8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessorImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cacheobject/IgniteCacheObjectProcessorImpl.java
@@ -43,6 +43,7 @@ import org.apache.ignite.internal.util.IgniteUtils;
 import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteUuid;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.jetbrains.annotations.Nullable;
 
 import static org.apache.ignite.cache.CacheMemoryMode.OFFHEAP_VALUES;
@@ -107,8 +108,8 @@ public class IgniteCacheObjectProcessorImpl extends GridProcessorAdapter impleme
     @Override public Object unmarshal(CacheObjectContext ctx, byte[] bytes, ClassLoader clsLdr)
         throws IgniteCheckedException
     {
-        return ctx.kernalContext().cache().context().marshaller().unmarshal(bytes, U.resolveClassLoader(clsLdr,
-            ctx.kernalContext().config()));
+        return MarshallerUtils.unmarshal(ctx.kernalContext().gridName(), ctx.kernalContext().cache().context().marshaller(),
+                bytes, U.resolveClassLoader(clsLdr, ctx.kernalContext().config()));
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/closure/GridClosureProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/closure/GridClosureProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/closure/GridClosureProcessor.java
index 1a96954..fb5c2c8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/closure/GridClosureProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/closure/GridClosureProcessor.java
@@ -70,6 +70,7 @@ import org.apache.ignite.lang.IgniteClosure;
 import org.apache.ignite.lang.IgniteProductVersion;
 import org.apache.ignite.lang.IgniteReducer;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.resources.LoadBalancerResource;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -1144,16 +1145,18 @@ public class GridClosureProcessor extends GridProcessorAdapter {
                         if (closureBytes == null) {
                             closure = c.job;
 
-                            closureBytes = marsh.marshal(c.job);
+                            closureBytes = MarshallerUtils.marshal(ctx, c.job);
                         }
 
                         if (c.job == closure)
-                            c.job = marsh.unmarshal(closureBytes, U.resolveClassLoader(ctx.config()));
+                            c.job = MarshallerUtils.unmarshal(ctx.gridName(), marsh, closureBytes, U.resolveClassLoader(ctx.config()));
                         else
-                            c.job = marsh.unmarshal(marsh.marshal(c.job), U.resolveClassLoader(ctx.config()));
+                            c.job = MarshallerUtils.marshalUnmarshal(ctx.gridName(), marsh, c.job,
+                                U.resolveClassLoader(ctx.config()));
                     }
                     else
-                        job = marsh.unmarshal(marsh.marshal(job), U.resolveClassLoader(ctx.config()));
+                        job = MarshallerUtils.marshalUnmarshal(ctx.gridName(), marsh, job,
+                            U.resolveClassLoader(ctx.config()));
                 }
                 else
                     hadLocNode = true;

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousProcessor.java
index e96e646..28df19f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/GridContinuousProcessor.java
@@ -77,6 +77,7 @@ import org.apache.ignite.lang.IgnitePredicate;
 import org.apache.ignite.lang.IgniteProductVersion;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.Message;
 import org.apache.ignite.thread.IgniteThread;
 import org.jetbrains.annotations.Nullable;
@@ -288,7 +289,8 @@ public class GridContinuousProcessor extends GridProcessorAdapter {
 
                 if (msg.data() == null && msg.dataBytes() != null) {
                     try {
-                        msg.data(marsh.unmarshal(msg.dataBytes(), U.resolveClassLoader(ctx.config())));
+                        msg.data(MarshallerUtils.unmarshal(ctx.gridName(), marsh, msg.dataBytes(),
+                            U.resolveClassLoader(ctx.config())));
                     }
                     catch (IgniteCheckedException e) {
                         U.error(log, "Failed to process message (ignoring): " + msg, e);
@@ -676,7 +678,7 @@ public class GridContinuousProcessor extends GridProcessorAdapter {
                     reqData.className(clsName);
                     reqData.deploymentInfo(new GridDeploymentInfoBean(dep));
 
-                    reqData.p2pMarshal(marsh);
+                    reqData.p2pMarshal(marsh, ctx);
                 }
 
                 // Handle peer deployment for other handler-specific objects.
@@ -733,7 +735,8 @@ public class GridContinuousProcessor extends GridProcessorAdapter {
 
                     if (msg.data() == null && msg.dataBytes() != null) {
                         try {
-                            msg.data(marsh.unmarshal(msg.dataBytes(), U.resolveClassLoader(ctx.config())));
+                            msg.data(MarshallerUtils.unmarshal(ctx.gridName(), marsh, msg.dataBytes(),
+                                U.resolveClassLoader(ctx.config())));
                         }
                         catch (IgniteCheckedException e) {
                             U.error(log, "Failed to process message (ignoring): " + msg, e);
@@ -976,7 +979,7 @@ public class GridContinuousProcessor extends GridProcessorAdapter {
                     if (dep == null)
                         throw new IgniteDeploymentCheckedException("Failed to obtain deployment for class: " + clsName);
 
-                    data.p2pUnmarshal(marsh, U.resolveClassLoader(dep.classLoader(), ctx.config()));
+                    data.p2pUnmarshal(marsh, U.resolveClassLoader(dep.classLoader(), ctx.config()), ctx);
                 }
 
                 hnd.p2pUnmarshal(node.id(), ctx);
@@ -1321,7 +1324,7 @@ public class GridContinuousProcessor extends GridProcessorAdapter {
         if (!msg.messages() &&
             msg.data() != null &&
             (nodes.size() > 1 || !ctx.localNodeId().equals(F.first(nodes).id())))
-            msg.dataBytes(marsh.marshal(msg.data()));
+            msg.dataBytes(MarshallerUtils.marshal(ctx, msg.data()));
 
         for (ClusterNode node : nodes) {
             int cnt = 0;

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/StartRequestData.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/StartRequestData.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/StartRequestData.java
index cdfe0e1..619bd86 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/StartRequestData.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/continuous/StartRequestData.java
@@ -23,11 +23,13 @@ import java.io.ObjectInput;
 import java.io.ObjectOutput;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.internal.GridKernalContext;
 import org.apache.ignite.internal.managers.deployment.GridDeploymentInfo;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgnitePredicate;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.jetbrains.annotations.Nullable;
 
 /**
@@ -90,26 +92,29 @@ class StartRequestData implements Externalizable {
 
     /**
      * @param marsh Marshaller.
+     * @param kernalCtx Kernal context.
      * @throws org.apache.ignite.IgniteCheckedException In case of error.
      */
-    void p2pMarshal(Marshaller marsh) throws IgniteCheckedException {
+    void p2pMarshal(Marshaller marsh, final GridKernalContext kernalCtx) throws IgniteCheckedException {
         assert marsh != null;
 
-        prjPredBytes = marsh.marshal(prjPred);
+        prjPredBytes = MarshallerUtils.marshal(kernalCtx.gridName(), marsh, prjPred);
     }
 
     /**
      * @param marsh Marshaller.
      * @param ldr Class loader.
+     * @param kernalCtx Kernal context.
      * @throws org.apache.ignite.IgniteCheckedException In case of error.
      */
-    void p2pUnmarshal(Marshaller marsh, @Nullable ClassLoader ldr) throws IgniteCheckedException {
+    void p2pUnmarshal(Marshaller marsh, @Nullable ClassLoader ldr,
+        final GridKernalContext kernalCtx) throws IgniteCheckedException {
         assert marsh != null;
 
         assert prjPred == null;
         assert prjPredBytes != null;
 
-        prjPred = marsh.unmarshal(prjPredBytes, ldr);
+        prjPred = MarshallerUtils.unmarshal(kernalCtx.gridName(), marsh, prjPredBytes, ldr);
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamProcessor.java
index c7c1f5e..853d1a0 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamProcessor.java
@@ -37,6 +37,7 @@ import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.internal.util.worker.GridWorker;
 import org.apache.ignite.lang.IgniteFuture;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.stream.StreamReceiver;
 import org.apache.ignite.thread.IgniteThread;
 import org.jetbrains.annotations.Nullable;
@@ -90,7 +91,7 @@ public class DataStreamProcessor<K, V> extends GridProcessorAdapter {
         if (ctx.config().isDaemon())
             return;
 
-        marshErrBytes = marsh.marshal(new IgniteCheckedException("Failed to marshal response error, " +
+        marshErrBytes = MarshallerUtils.marshal(ctx, new IgniteCheckedException("Failed to marshal response error, " +
             "see node log for details."));
 
         flusher = new IgniteThread(new GridWorker(ctx.gridName(), "grid-data-loader-flusher", log) {
@@ -235,7 +236,8 @@ public class DataStreamProcessor<K, V> extends GridProcessorAdapter {
             Object topic;
 
             try {
-                topic = marsh.unmarshal(req.responseTopicBytes(), U.resolveClassLoader(null, ctx.config()));
+                topic = MarshallerUtils.unmarshal(ctx.gridName(), marsh, req.responseTopicBytes(),
+                    U.resolveClassLoader(null, ctx.config()));
             }
             catch (IgniteCheckedException e) {
                 U.error(log, "Failed to unmarshal topic from request: " + req, e);
@@ -275,7 +277,8 @@ public class DataStreamProcessor<K, V> extends GridProcessorAdapter {
             StreamReceiver<K, V> updater;
 
             try {
-                updater = marsh.unmarshal(req.updaterBytes(), U.resolveClassLoader(clsLdr, ctx.config()));
+                updater = MarshallerUtils.unmarshal(ctx.gridName(), marsh, req.updaterBytes(),
+                    U.resolveClassLoader(clsLdr, ctx.config()));
 
                 if (updater != null)
                     ctx.resource().injectGeneric(updater);
@@ -329,7 +332,7 @@ public class DataStreamProcessor<K, V> extends GridProcessorAdapter {
         byte[] errBytes;
 
         try {
-            errBytes = err != null ? marsh.marshal(err) : null;
+            errBytes = err != null ? MarshallerUtils.marshal(ctx, err) : null;
         }
         catch (Exception e) {
             U.error(log, "Failed to marshal error [err=" + err + ", marshErr=" + e + ']', e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerImpl.java
index 21df559..9d04a5f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerImpl.java
@@ -98,6 +98,7 @@ import org.apache.ignite.lang.IgniteClosure;
 import org.apache.ignite.lang.IgniteFuture;
 import org.apache.ignite.lang.IgniteInClosure;
 import org.apache.ignite.lang.IgniteUuid;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.security.SecurityPermission;
 import org.apache.ignite.stream.StreamReceiver;
 import org.jetbrains.annotations.Nullable;
@@ -1359,11 +1360,11 @@ public class DataStreamerImpl<K, V> implements IgniteDataStreamer<K, V>, Delayed
                     if (updaterBytes == null) {
                         assert rcvr != null;
 
-                        updaterBytes = ctx.config().getMarshaller().marshal(rcvr);
+                        updaterBytes = MarshallerUtils.marshal(ctx, rcvr);
                     }
 
                     if (topicBytes == null)
-                        topicBytes = ctx.config().getMarshaller().marshal(topic);
+                        topicBytes = MarshallerUtils.marshal(ctx, topic);
                 }
                 catch (IgniteCheckedException e) {
                     U.error(log, "Failed to marshal (request will not be sent).", e);
@@ -1494,8 +1495,7 @@ public class DataStreamerImpl<K, V> implements IgniteDataStreamer<K, V>, Delayed
                 try {
                     GridPeerDeployAware jobPda0 = jobPda;
 
-                    err = ctx.config().getMarshaller().unmarshal(
-                        errBytes,
+                    err = MarshallerUtils.unmarshal(ctx.gridName(), ctx.config().getMarshaller(), errBytes,
                         U.resolveClassLoader(jobPda0 != null ? jobPda0.classLoader() : null, ctx.config()));
                 }
                 catch (IgniteCheckedException e) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsAckMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsAckMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsAckMessage.java
index 0bf3dde..20c80bb 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsAckMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsAckMessage.java
@@ -21,8 +21,10 @@ import java.io.Externalizable;
 import java.nio.ByteBuffer;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.internal.GridDirectTransient;
+import org.apache.ignite.internal.GridKernalContext;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
 import org.jetbrains.annotations.Nullable;
@@ -92,19 +94,20 @@ public class IgfsAckMessage extends IgfsCommunicationMessage {
     }
 
     /** {@inheritDoc} */
-    @Override public void prepareMarshal(Marshaller marsh) throws IgniteCheckedException {
-        super.prepareMarshal(marsh);
+    @Override public void prepareMarshal(Marshaller marsh, GridKernalContext kernalCtx) throws IgniteCheckedException {
+        super.prepareMarshal(marsh, kernalCtx);
 
         if (err != null)
-            errBytes = marsh.marshal(err);
+            errBytes = MarshallerUtils.marshal(kernalCtx.gridName(), marsh, err);
     }
 
     /** {@inheritDoc} */
-    @Override public void finishUnmarshal(Marshaller marsh, @Nullable ClassLoader ldr) throws IgniteCheckedException {
-        super.finishUnmarshal(marsh, ldr);
+    @Override public void finishUnmarshal(Marshaller marsh, @Nullable ClassLoader ldr,
+        final GridKernalContext kernalCtx) throws IgniteCheckedException {
+        super.finishUnmarshal(marsh, ldr, kernalCtx);
 
         if (errBytes != null)
-            err = marsh.unmarshal(errBytes, ldr);
+            err = MarshallerUtils.unmarshal(kernalCtx.gridName(), marsh, errBytes, ldr);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsCommunicationMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsCommunicationMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsCommunicationMessage.java
index 412c45b..d1d40e7 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsCommunicationMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsCommunicationMessage.java
@@ -19,6 +19,7 @@ package org.apache.ignite.internal.processors.igfs;
 
 import java.nio.ByteBuffer;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.internal.GridKernalContext;
 import org.apache.ignite.marshaller.Marshaller;
 import org.apache.ignite.plugin.extensions.communication.Message;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
@@ -34,18 +35,21 @@ public abstract class IgfsCommunicationMessage implements Message {
 
     /**
      * @param marsh Marshaller.
+     * @param kernalCtx Kernal ctx.
      * @throws IgniteCheckedException In case of error.
      */
-    public void prepareMarshal(Marshaller marsh) throws IgniteCheckedException {
+    public void prepareMarshal(Marshaller marsh, final GridKernalContext kernalCtx) throws IgniteCheckedException {
         // No-op.
     }
 
     /**
      * @param marsh Marshaller.
      * @param ldr Class loader.
+     * @param kernalCtx Kernal ctx.
      * @throws IgniteCheckedException In case of error.
      */
-    public void finishUnmarshal(Marshaller marsh, @Nullable ClassLoader ldr) throws IgniteCheckedException {
+    public void finishUnmarshal(Marshaller marsh, @Nullable ClassLoader ldr,
+        final GridKernalContext kernalCtx) throws IgniteCheckedException {
         // No-op.
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsContext.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsContext.java
index a638bf3..76290e3 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsContext.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsContext.java
@@ -148,7 +148,7 @@ public class IgfsContext {
     public void send(UUID nodeId, Object topic, IgfsCommunicationMessage msg, byte plc)
         throws IgniteCheckedException {
         if (!kernalContext().localNodeId().equals(nodeId))
-            msg.prepareMarshal(kernalContext().config().getMarshaller());
+            msg.prepareMarshal(kernalContext().config().getMarshaller(), kernalContext());
 
         kernalContext().io().send(nodeId, topic, msg, plc);
     }
@@ -163,7 +163,7 @@ public class IgfsContext {
     public void send(ClusterNode node, Object topic, IgfsCommunicationMessage msg, byte plc)
         throws IgniteCheckedException {
         if (!kernalContext().localNodeId().equals(node.id()))
-            msg.prepareMarshal(kernalContext().config().getMarshaller());
+            msg.prepareMarshal(kernalContext().config().getMarshaller(), kernalContext());
 
         kernalContext().io().send(node, topic, msg, plc);
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDataManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDataManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDataManager.java
index bdf3b08..ed1f525 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDataManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDataManager.java
@@ -1149,7 +1149,7 @@ public class IgfsDataManager extends IgfsManager {
     @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
     private void processAckMessage(UUID nodeId, IgfsAckMessage ackMsg) {
         try {
-            ackMsg.finishUnmarshal(igfsCtx.kernalContext().config().getMarshaller(), null);
+            ackMsg.finishUnmarshal(igfsCtx.kernalContext().config().getMarshaller(), null, igfsCtx.kernalContext());
         }
         catch (IgniteCheckedException e) {
             U.error(log, "Failed to unmarshal message (will ignore): " + ackMsg, e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDeleteMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDeleteMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDeleteMessage.java
index e59b257..d0776bd 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDeleteMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsDeleteMessage.java
@@ -21,9 +21,11 @@ import java.io.Externalizable;
 import java.nio.ByteBuffer;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.internal.GridDirectTransient;
+import org.apache.ignite.internal.GridKernalContext;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
 import org.jetbrains.annotations.Nullable;
@@ -91,19 +93,20 @@ public class IgfsDeleteMessage extends IgfsCommunicationMessage {
     }
 
     /** {@inheritDoc} */
-    @Override public void prepareMarshal(Marshaller marsh) throws IgniteCheckedException {
-        super.prepareMarshal(marsh);
+    @Override public void prepareMarshal(Marshaller marsh, GridKernalContext kernalCtx) throws IgniteCheckedException {
+        super.prepareMarshal(marsh, kernalCtx);
 
         if (err != null)
-            errBytes = marsh.marshal(err);
+            errBytes = MarshallerUtils.marshal(kernalCtx.gridName(), marsh, err);
     }
 
     /** {@inheritDoc} */
-    @Override public void finishUnmarshal(Marshaller marsh, @Nullable ClassLoader ldr) throws IgniteCheckedException {
-        super.finishUnmarshal(marsh, ldr);
+    @Override public void finishUnmarshal(Marshaller marsh, @Nullable ClassLoader ldr,
+        final GridKernalContext kernalCtx) throws IgniteCheckedException {
+        super.finishUnmarshal(marsh, ldr, kernalCtx);
 
         if (errBytes != null)
-            err = marsh.unmarshal(errBytes, ldr);
+            err = MarshallerUtils.unmarshal(kernalCtx.gridName(), marsh, errBytes, ldr);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerManager.java
index d64c64a..e04445f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsFragmentizerManager.java
@@ -263,7 +263,7 @@ public class IgfsFragmentizerManager extends IgfsManager {
      */
     @SuppressWarnings("fallthrough")
     private void processFragmentizerRequest(IgfsFragmentizerRequest req) throws IgniteCheckedException {
-        req.finishUnmarshal(igfsCtx.kernalContext().config().getMarshaller(), null);
+        req.finishUnmarshal(igfsCtx.kernalContext().config().getMarshaller(), null, igfsCtx.kernalContext());
 
         Collection<IgfsFileAffinityRange> ranges = req.fragmentRanges();
         IgniteUuid fileId = req.fileId();

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsImpl.java
index 7234e52..a25d082 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsImpl.java
@@ -256,7 +256,7 @@ public final class IgfsImpl implements IgfsEx {
         if (secondaryFs instanceof HadoopPayloadAware)
             secondaryFsPayload = ((HadoopPayloadAware) secondaryFs).getPayload();
 
-        secondaryPaths = new IgfsPaths(secondaryFsPayload, dfltMode, modeRslvr.modesOrdered());
+        secondaryPaths = new IgfsPaths(secondaryFsPayload, dfltMode, modeRslvr.modesOrdered(), igfsCtx);
 
         // Check whether IGFS LRU eviction policy is set on data cache.
         String dataCacheName = igfsCtx.configuration().getDataCacheName();

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsPaths.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsPaths.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsPaths.java
index 4a79259..9892bc8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsPaths.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsPaths.java
@@ -31,6 +31,7 @@ import org.apache.ignite.igfs.IgfsMode;
 import org.apache.ignite.igfs.IgfsPath;
 import org.apache.ignite.internal.util.typedef.T2;
 import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.jetbrains.annotations.Nullable;
 
@@ -63,9 +64,11 @@ public class IgfsPaths implements Externalizable {
      * @param payload Payload.
      * @param dfltMode Default IGFS mode.
      * @param pathModes Path modes.
+     * @param igfsCtx Ignite FS context.
      * @throws IgniteCheckedException If failed.
      */
-    public IgfsPaths(Object payload, IgfsMode dfltMode, @Nullable List<T2<IgfsPath, IgfsMode>> pathModes)
+    public IgfsPaths(Object payload, IgfsMode dfltMode, @Nullable List<T2<IgfsPath, IgfsMode>> pathModes,
+        final IgfsContext igfsCtx)
         throws IgniteCheckedException {
         this.dfltMode = dfltMode;
         this.pathModes = pathModes;
@@ -75,7 +78,7 @@ public class IgfsPaths implements Externalizable {
         else {
             ByteArrayOutputStream out = new ByteArrayOutputStream();
 
-            new JdkMarshaller().marshal(payload, out);
+            MarshallerUtils.marshal(igfsCtx.kernalContext().gridName(), new JdkMarshaller(), payload, out);
 
             payloadBytes = out.toByteArray();
         }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobProcessor.java
index 906d298..5938eb0 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobProcessor.java
@@ -76,6 +76,7 @@ import org.apache.ignite.lang.IgniteBiTuple;
 import org.apache.ignite.lang.IgnitePredicate;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jsr166.ConcurrentHashMap8;
@@ -403,7 +404,7 @@ public class GridJobProcessor extends GridProcessorAdapter {
         boolean loc = ctx.localNodeId().equals(taskNode.id()) && !ctx.config().isMarshalLocalJobs();
 
         GridTaskSessionRequest req = new GridTaskSessionRequest(ses.getId(), ses.getJobId(),
-            loc ? null : marsh.marshal(attrs), attrs);
+            loc ? null : MarshallerUtils.marshal(ctx, attrs), attrs);
 
         Object topic = TOPIC_TASK.topic(ses.getJobId(), ctx.discovery().localNode().id());
 
@@ -454,7 +455,7 @@ public class GridJobProcessor extends GridProcessorAdapter {
 
                     if (res.jobSiblings() == null) {
                         try {
-                            res.unmarshalSiblings(marsh);
+                            res.unmarshalSiblings(marsh, ctx);
                         }
                         catch (IgniteCheckedException e) {
                             U.error(log, "Failed to unmarshal job siblings.", e);
@@ -516,7 +517,7 @@ public class GridJobProcessor extends GridProcessorAdapter {
             ctx.io().send(taskNode, TOPIC_JOB_SIBLINGS,
                 new GridJobSiblingsRequest(ses.getId(),
                     loc ? topic : null,
-                    loc ? null : marsh.marshal(topic)),
+                    loc ? null : MarshallerUtils.marshal(ctx, topic)),
                 SYSTEM_POOL);
 
             // 4. Listen to discovery events.
@@ -1018,7 +1019,8 @@ public class GridJobProcessor extends GridProcessorAdapter {
                             if (siblings0 == null) {
                                 assert req.getSiblingsBytes() != null;
 
-                                siblings0 = marsh.unmarshal(req.getSiblingsBytes(), U.resolveClassLoader(ctx.config()));
+                                siblings0 = MarshallerUtils.unmarshal(ctx.gridName(), marsh, req.getSiblingsBytes(),
+                                    U.resolveClassLoader(ctx.config()));
                             }
 
                             siblings = new ArrayList<>(siblings0);
@@ -1029,9 +1031,10 @@ public class GridJobProcessor extends GridProcessorAdapter {
                         if (req.isSessionFullSupport()) {
                             sesAttrs = req.getSessionAttributes();
 
-                            if (sesAttrs == null)
-                                sesAttrs = marsh.unmarshal(req.getSessionAttributesBytes(),
+                            if (sesAttrs == null) {
+                                sesAttrs = MarshallerUtils.unmarshal(ctx.gridName(), marsh, req.getSessionAttributesBytes(),
                                     U.resolveClassLoader(dep.classLoader(), ctx.config()));
+                            }
                         }
 
                         // Note that we unmarshal session/job attributes here with proper class loader.
@@ -1056,9 +1059,10 @@ public class GridJobProcessor extends GridProcessorAdapter {
 
                         Map<? extends Serializable, ? extends Serializable> jobAttrs = req.getJobAttributes();
 
-                        if (jobAttrs == null)
-                            jobAttrs = marsh.unmarshal(req.getJobAttributesBytes(),
+                        if (jobAttrs == null) {
+                            jobAttrs = MarshallerUtils.unmarshal(ctx.gridName(), marsh, req.getJobAttributesBytes(),
                                 U.resolveClassLoader(dep.classLoader(), ctx.config()));
+                        }
 
                         jobCtx = new GridJobContextImpl(ctx, req.getJobId(), jobAttrs);
                     }
@@ -1330,11 +1334,11 @@ public class GridJobProcessor extends GridProcessorAdapter {
                 locNodeId,
                 req.getSessionId(),
                 req.getJobId(),
-                loc ? null : marsh.marshal(ex),
+                loc ? null : MarshallerUtils.marshal(ctx, ex),
                 ex,
-                loc ? null : marsh.marshal(null),
+                loc ? null : MarshallerUtils.marshal(ctx, null),
                 null,
-                loc ? null : marsh.marshal(null),
+                loc ? null : MarshallerUtils.marshal(ctx, null),
                 null,
                 false);
 
@@ -1425,7 +1429,7 @@ public class GridJobProcessor extends GridProcessorAdapter {
             boolean loc = ctx.localNodeId().equals(nodeId) && !ctx.config().isMarshalLocalJobs();
 
             Map<?, ?> attrs = loc ? req.getAttributes() :
-                (Map<?, ?>)marsh.unmarshal(req.getAttributesBytes(),
+                (Map<?, ?>)MarshallerUtils.unmarshal(ctx.gridName(), marsh, req.getAttributesBytes(),
                     U.resolveClassLoader(ses.getClassLoader(), ctx.config()));
 
             if (ctx.event().isRecordable(EVT_TASK_SESSION_ATTR_SET)) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobWorker.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobWorker.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobWorker.java
index 164c9e7..39457e7 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobWorker.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/job/GridJobWorker.java
@@ -54,6 +54,7 @@ import org.apache.ignite.lang.IgniteBiTuple;
 import org.apache.ignite.lang.IgniteRunnable;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.jetbrains.annotations.Nullable;
 
 import static org.apache.ignite.events.EventType.EVT_JOB_CANCELLED;
@@ -406,7 +407,8 @@ public class GridJobWorker extends GridWorker implements GridTimeoutObject {
 
         try {
             if (job == null) {
-                job = marsh.unmarshal(jobBytes, U.resolveClassLoader(dep.classLoader(), ctx.config()));
+                job = MarshallerUtils.unmarshal(ctx.gridName(), marsh, jobBytes,
+                    U.resolveClassLoader(dep.classLoader(), ctx.config()));
 
                 // No need to hold reference any more.
                 jobBytes = null;
@@ -744,11 +746,11 @@ public class GridJobWorker extends GridWorker implements GridTimeoutObject {
                                 ctx.localNodeId(),
                                 ses.getId(),
                                 ses.getJobId(),
-                                loc ? null : marsh.marshal(ex),
+                                loc ? null : MarshallerUtils.marshal(ctx, ex),
                                 loc ? ex : null,
-                                loc ? null: marsh.marshal(res),
+                                loc ? null: MarshallerUtils.marshal(ctx, res),
                                 loc ? res : null,
-                                loc ? null : marsh.marshal(attrs),
+                                loc ? null : MarshallerUtils.marshal(ctx, attrs),
                                 loc ? attrs : null,
                                 isCancelled());
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/offheap/GridOffHeapProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/offheap/GridOffHeapProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/offheap/GridOffHeapProcessor.java
index d9d4421..1de7049 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/offheap/GridOffHeapProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/offheap/GridOffHeapProcessor.java
@@ -33,6 +33,7 @@ import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteBiPredicate;
 import org.apache.ignite.lang.IgniteBiTuple;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.jetbrains.annotations.Nullable;
 import org.jsr166.ConcurrentHashMap8;
 
@@ -108,7 +109,7 @@ public class GridOffHeapProcessor extends GridProcessorAdapter {
     private byte[] keyBytes(KeyCacheObject key, @Nullable byte[] keyBytes) throws IgniteCheckedException {
         assert key != null;
 
-        return keyBytes != null ? keyBytes : marsh.marshal(key);
+        return keyBytes != null ? keyBytes : MarshallerUtils.marshal(ctx, key);
     }
 
     /**
@@ -212,7 +213,7 @@ public class GridOffHeapProcessor extends GridProcessorAdapter {
         if (valBytes == null)
             return null;
 
-        return marsh.unmarshal(valBytes, U.resolveClassLoader(ldr, ctx.config()));
+        return MarshallerUtils.unmarshal(ctx.gridName(), marsh, valBytes, U.resolveClassLoader(ldr, ctx.config()));
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskCommandHandler.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskCommandHandler.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskCommandHandler.java
index 6937196..c052570 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskCommandHandler.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/handlers/task/GridTaskCommandHandler.java
@@ -63,6 +63,7 @@ import org.apache.ignite.internal.visor.util.VisorClusterGroupEmptyException;
 import org.apache.ignite.lang.IgniteBiTuple;
 import org.apache.ignite.lang.IgniteInClosure;
 import org.apache.ignite.lang.IgniteUuid;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.resources.IgniteInstanceResource;
 import org.jetbrains.annotations.Nullable;
 
@@ -135,13 +136,13 @@ public class GridTaskCommandHandler extends GridRestCommandHandlerAdapter {
                             res.error(err.getMessage());
                         else {
                             res.result(desc.result());
-                            res.resultBytes(ctx.config().getMarshaller().marshal(desc.result()));
+                            res.resultBytes(MarshallerUtils.marshal(ctx, desc.result()));
                         }
                     }
                     else
                         res.found(false);
 
-                    Object topic = ctx.config().getMarshaller().unmarshal(req.topicBytes(),
+                    Object topic = MarshallerUtils.unmarshal(ctx.gridName(), ctx.config().getMarshaller(), req.topicBytes(),
                         U.resolveClassLoader(ctx.config()));
 
                     ctx.io().send(nodeId, topic, res, SYSTEM_POOL);
@@ -440,7 +441,7 @@ public class GridTaskCommandHandler extends GridRestCommandHandlerAdapter {
                     res = (GridTaskResultResponse)msg;
 
                 try {
-                    res.result(ctx.config().getMarshaller().unmarshal(res.resultBytes(),
+                    res.result(MarshallerUtils.unmarshal(ctx.gridName(), ctx.config().getMarshaller(), res.resultBytes(),
                         U.resolveClassLoader(ctx.config())));
                 }
                 catch (IgniteCheckedException e) {
@@ -494,7 +495,7 @@ public class GridTaskCommandHandler extends GridRestCommandHandlerAdapter {
 
             // 2. Send message.
             try {
-                byte[] topicBytes = ctx.config().getMarshaller().marshal(topic);
+                byte[] topicBytes = MarshallerUtils.marshal(ctx, topic);
 
                 ctx.io().send(taskNode, TOPIC_REST, new GridTaskResultRequest(taskId, topic, topicBytes), SYSTEM_POOL);
             }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParser.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParser.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParser.java
index 5beff75..133d754 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParser.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestParser.java
@@ -39,6 +39,7 @@ import org.apache.ignite.internal.util.nio.GridNioSession;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.jetbrains.annotations.Nullable;
 
@@ -169,7 +170,7 @@ public class GridTcpRestParser implements GridNioParser {
         GridClientMessage msg = (GridClientMessage)msg0;
 
         if (msg instanceof GridMemcachedMessage)
-            return encodeMemcache((GridMemcachedMessage)msg);
+            return encodeMemcache((GridMemcachedMessage)msg, ses.gridName());
         else if (msg instanceof GridClientPingPacket)
             return ByteBuffer.wrap(GridClientPingPacket.PING_PACKET);
         else if (msg instanceof GridClientHandshakeRequest) {
@@ -533,10 +534,12 @@ public class GridTcpRestParser implements GridNioParser {
      * Encodes memcache message to a raw byte array.
      *
      * @param msg Message being serialized.
+     * @param gridName Grid name.
      * @return Serialized message.
      * @throws IgniteCheckedException If serialization failed.
      */
-    private ByteBuffer encodeMemcache(GridMemcachedMessage msg) throws IgniteCheckedException {
+    private ByteBuffer encodeMemcache(GridMemcachedMessage msg,
+        final String gridName) throws IgniteCheckedException {
         GridByteArrayList res = new GridByteArrayList(HDR_LEN);
 
         int keyLen = 0;
@@ -546,7 +549,7 @@ public class GridTcpRestParser implements GridNioParser {
         if (msg.key() != null) {
             ByteArrayOutputStream rawKey = new ByteArrayOutputStream();
 
-            keyFlags = encodeObj(msg.key(), rawKey);
+            keyFlags = encodeObj(msg.key(), rawKey, gridName);
 
             msg.key(rawKey.toByteArray());
 
@@ -560,7 +563,7 @@ public class GridTcpRestParser implements GridNioParser {
         if (msg.value() != null) {
             ByteArrayOutputStream rawVal = new ByteArrayOutputStream();
 
-            valFlags = encodeObj(msg.value(), rawVal);
+            valFlags = encodeObj(msg.value(), rawVal, gridName);
 
             msg.value(rawVal.toByteArray());
 
@@ -645,7 +648,7 @@ public class GridTcpRestParser implements GridNioParser {
                 byte[] rawKey = (byte[])req.key();
 
                 // Only values can be hessian-encoded.
-                req.key(decodeObj(keyFlags, rawKey));
+                req.key(decodeObj(keyFlags, rawKey, ses.gridName()));
             }
 
             if (req.value() != null) {
@@ -653,7 +656,7 @@ public class GridTcpRestParser implements GridNioParser {
 
                 byte[] rawVal = (byte[])req.value();
 
-                req.value(decodeObj(valFlags, rawVal));
+                req.value(decodeObj(valFlags, rawVal, ses.gridName()));
             }
         }
 
@@ -711,14 +714,16 @@ public class GridTcpRestParser implements GridNioParser {
      *
      * @param flags Flags.
      * @param bytes Byte array to decode.
+     * @param gridName Grid name.
      * @return Decoded value.
      * @throws IgniteCheckedException If deserialization failed.
      */
-    private Object decodeObj(short flags, byte[] bytes) throws IgniteCheckedException {
+    private Object decodeObj(short flags, byte[] bytes,
+        final String gridName) throws IgniteCheckedException {
         assert bytes != null;
 
         if ((flags & SERIALIZED_FLAG) != 0)
-            return jdkMarshaller.unmarshal(bytes, null);
+            return MarshallerUtils.unmarshal(gridName, jdkMarshaller, bytes, null);
 
         int masked = flags & 0xff00;
 
@@ -749,10 +754,11 @@ public class GridTcpRestParser implements GridNioParser {
      *
      * @param obj Object to serialize.
      * @param out Output stream to which object should be written.
+     * @param gridName Grid name.
      * @return Serialization flags.
      * @throws IgniteCheckedException If JDK serialization failed.
      */
-    private int encodeObj(Object obj, ByteArrayOutputStream out) throws IgniteCheckedException {
+    private int encodeObj(Object obj, ByteArrayOutputStream out, final String gridName) throws IgniteCheckedException {
         int flags = 0;
 
         byte[] data = null;
@@ -800,7 +806,7 @@ public class GridTcpRestParser implements GridNioParser {
             flags |= BYTE_ARR_FLAG;
         }
         else {
-            jdkMarshaller.marshal(obj, out);
+            MarshallerUtils.marshal(gridName, jdkMarshaller, obj, out);
 
             flags |= SERIALIZED_FLAG;
         }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java
index b418ba2..654114d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java
@@ -83,6 +83,7 @@ import org.apache.ignite.lang.IgniteProductVersion;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
 import org.apache.ignite.resources.IgniteInstanceResource;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.resources.JobContextResource;
 import org.apache.ignite.resources.LoggerResource;
 import org.apache.ignite.services.Service;
@@ -447,18 +448,16 @@ public class GridServiceProcessor extends GridProcessorAdapter {
         validate(cfg);
 
         if (!state.srvcCompatibility) {
-            Marshaller marsh = ctx.config().getMarshaller();
-
             LazyServiceConfiguration cfg0;
 
             try {
-                byte[] srvcBytes = marsh.marshal(cfg.getService());
+                byte[] srvcBytes = MarshallerUtils.marshal(ctx, cfg.getService());
 
                 cfg0 = new LazyServiceConfiguration(cfg, srvcBytes);
             }
             catch (IgniteCheckedException e) {
                 U.error(log, "Failed to marshal service with configured marshaller [srvc=" + cfg.getService()
-                    + ", marsh=" + marsh + "]", e);
+                    + ", marsh=" + ctx.config().getMarshaller() + "]", e);
 
                 return new GridFinishedFuture<>(e);
             }
@@ -1123,7 +1122,7 @@ public class GridServiceProcessor extends GridProcessorAdapter {
         if (cfg instanceof LazyServiceConfiguration) {
             byte[] bytes = ((LazyServiceConfiguration)cfg).serviceBytes();
 
-            Service srvc = m.unmarshal(bytes, U.resolveClassLoader(null, ctx.config()));
+            Service srvc = MarshallerUtils.unmarshal(ctx.gridName(), m, bytes, U.resolveClassLoader(null, ctx.config()));
 
             ctx.resource().inject(srvc);
 
@@ -1133,10 +1132,10 @@ public class GridServiceProcessor extends GridProcessorAdapter {
             Service svc = cfg.getService();
 
             try {
-                byte[] bytes = m.marshal(svc);
+                byte[] bytes = MarshallerUtils.marshal(ctx, svc);
 
-                Service cp = m.unmarshal(bytes,
-                    U.resolveClassLoader(svc.getClass().getClassLoader(), ctx.config()));
+                Service cp = MarshallerUtils.unmarshal(ctx.gridName(), m, bytes, U.resolveClassLoader(svc.getClass().getClassLoader(),
+                    ctx.config()));
 
                 ctx.resource().inject(cp);
 


[03/50] [abbrv] ignite git commit: ignite-3336 Added properties IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT, IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT. Refactored cache message logging.

Posted by vo...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxHandler.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxHandler.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxHandler.java
index 5b09760..5422672 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxHandler.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxHandler.java
@@ -92,6 +92,15 @@ public class IgniteTxHandler {
     /** Logger. */
     private IgniteLogger log;
 
+    /** */
+    private final IgniteLogger txPrepareMsgLog;
+
+    /** */
+    private final IgniteLogger txFinishMsgLog;
+
+    /** */
+    private final IgniteLogger txRecoveryMsgLog;
+
     /** Shared cache context. */
     private GridCacheSharedContext<?, ?> ctx;
 
@@ -102,6 +111,11 @@ public class IgniteTxHandler {
      */
     public IgniteInternalFuture<?> processNearTxPrepareRequest(final UUID nearNodeId,
         final GridNearTxPrepareRequest req) {
+        if (txPrepareMsgLog.isDebugEnabled()) {
+            txPrepareMsgLog.debug("Received near prepare request [txId=" + req.version() +
+                ", node=" + nearNodeId + ']');
+        }
+
         return prepareTx(nearNodeId, null, req);
     }
 
@@ -113,6 +127,10 @@ public class IgniteTxHandler {
 
         log = ctx.logger(IgniteTxHandler.class);
 
+        txRecoveryMsgLog = ctx.logger(CU.TX_MSG_RECOVERY_LOG_CATEGORY);
+        txPrepareMsgLog = ctx.logger(CU.TX_MSG_PREPARE_LOG_CATEGORY);
+        txFinishMsgLog = ctx.logger(CU.TX_MSG_FINISH_LOG_CATEGORY);
+
         ctx.io().addHandler(0, GridNearTxPrepareRequest.class, new CI2<UUID, GridCacheMessage>() {
             @Override public void apply(UUID nodeId, GridCacheMessage msg) {
                 processNearTxPrepareRequest(nodeId, (GridNearTxPrepareRequest)msg);
@@ -265,8 +283,11 @@ public class IgniteTxHandler {
         ClusterNode nearNode = ctx.node(nearNodeId);
 
         if (nearNode == null) {
-            if (log.isDebugEnabled())
-                log.debug("Received transaction request from node that left grid (will ignore): " + nearNodeId);
+            if (txPrepareMsgLog.isDebugEnabled()) {
+                txPrepareMsgLog.debug("Received near prepare from node that left grid (will ignore) [" +
+                    "txId=" + req.version() +
+                    ", node=" + nearNodeId + ']');
+            }
 
             return null;
         }
@@ -316,9 +337,11 @@ public class IgniteTxHandler {
 
             try {
                 if (top != null && needRemap(req.topologyVersion(), top.topologyVersion(), req)) {
-                    if (log.isDebugEnabled()) {
-                        log.debug("Client topology version mismatch, need remap transaction [" +
-                            "reqTopVer=" + req.topologyVersion() +
+                    if (txPrepareMsgLog.isDebugEnabled()) {
+                        txPrepareMsgLog.debug("Topology version mismatch for near prepare, need remap transaction [" +
+                            "txId=" + req.version() +
+                            ", node=" + nearNodeId +
+                            ", reqTopVer=" + req.topologyVersion() +
                             ", locTopVer=" + top.topologyVersion() +
                             ", req=" + req + ']');
                     }
@@ -336,15 +359,24 @@ public class IgniteTxHandler {
 
                     try {
                         ctx.io().send(nearNode, res, req.policy());
+
+                        if (txPrepareMsgLog.isDebugEnabled()) {
+                            txPrepareMsgLog.debug("Sent remap response for near prepare [txId=" + req.version() +
+                                ", node=" + nearNodeId + ']');
+                        }
                     }
                     catch (ClusterTopologyCheckedException ignored) {
-                        if (log.isDebugEnabled())
-                            log.debug("Failed to send client tx remap response, client node failed " +
-                                "[node=" + nearNode + ", req=" + req + ']');
+                        if (txPrepareMsgLog.isDebugEnabled()) {
+                            txPrepareMsgLog.debug("Failed to send remap response for near prepare, node failed [" +
+                                "txId=" + req.version() +
+                                ", node=" + nearNodeId + ']');
+                        }
                     }
                     catch (IgniteCheckedException e) {
-                        U.error(log, "Failed to send client tx remap response " +
-                            "[node=" + nearNode + ", req=" + req + ']', e);
+                        U.error(txPrepareMsgLog, "Failed to send remap response for near prepare " +
+                            "[txId=" + req.version() +
+                            ", node=" + nearNodeId +
+                            ", req=" + req + ']', e);
                     }
 
                     return new GridFinishedFuture<>(res);
@@ -479,11 +511,16 @@ public class IgniteTxHandler {
      * @param res Response.
      */
     private void processNearTxPrepareResponse(UUID nodeId, GridNearTxPrepareResponse res) {
+        if (txPrepareMsgLog.isDebugEnabled())
+            txPrepareMsgLog.debug("Received near prepare response [txId=" + res.version() + ", node=" + nodeId + ']');
+
         GridNearTxPrepareFutureAdapter fut = (GridNearTxPrepareFutureAdapter)ctx.mvcc()
             .<IgniteInternalTx>mvccFuture(res.version(), res.futureId());
 
         if (fut == null) {
-            U.warn(log, "Failed to find future for prepare response [sender=" + nodeId + ", res=" + res + ']');
+            U.warn(log, "Failed to find future for near prepare response [txId=" + res.version() +
+                ", node=" + nodeId +
+                ", res=" + res + ']');
 
             return;
         }
@@ -496,13 +533,19 @@ public class IgniteTxHandler {
      * @param res Response.
      */
     private void processNearTxFinishResponse(UUID nodeId, GridNearTxFinishResponse res) {
+        if (txFinishMsgLog.isDebugEnabled())
+            txFinishMsgLog.debug("Received near finish response [txId=" + res.xid() + ", node=" + nodeId + ']');
+
         ctx.tm().onFinishedRemote(nodeId, res.threadId());
 
         GridNearTxFinishFuture fut = (GridNearTxFinishFuture)ctx.mvcc().<IgniteInternalTx>future(res.futureId());
 
         if (fut == null) {
-            if (log.isDebugEnabled())
-                log.debug("Failed to find future for finish response [sender=" + nodeId + ", res=" + res + ']');
+            if (txFinishMsgLog.isDebugEnabled()) {
+                txFinishMsgLog.debug("Failed to find future for near finish response [txId=" + res.xid() +
+                    ", node=" + nodeId +
+                    ", res=" + res + ']');
+            }
 
             return;
         }
@@ -518,11 +561,17 @@ public class IgniteTxHandler {
         GridDhtTxPrepareFuture fut = (GridDhtTxPrepareFuture)ctx.mvcc().mvccFuture(res.version(), res.futureId());
 
         if (fut == null) {
-            if (log.isDebugEnabled())
-                log.debug("Received response for unknown future (will ignore): " + res);
+            if (txPrepareMsgLog.isDebugEnabled()) {
+                txPrepareMsgLog.debug("Failed to find future for dht prepare response [txId=null" +
+                    ", dhtTxId=" + res.version() +
+                    ", node=" + nodeId +
+                    ", res=" + res + ']');
+            }
 
             return;
         }
+        else if (txPrepareMsgLog.isDebugEnabled())
+            txPrepareMsgLog.debug("Received dht prepare response [txId=" + fut.tx().nearXidVersion() + ", node=" + nodeId + ']');
 
         fut.onResult(nodeId, res);
     }
@@ -539,11 +588,20 @@ public class IgniteTxHandler {
             GridNearTxFinishFuture fut = (GridNearTxFinishFuture)ctx.mvcc().<IgniteInternalTx>future(res.futureId());
 
             if (fut == null) {
-                if (log.isDebugEnabled())
-                    log.debug("Received response for unknown future (will ignore): " + res);
+                if (txFinishMsgLog.isDebugEnabled()) {
+                    txFinishMsgLog.debug("Failed to find future for dht finish check committed response [txId=null" +
+                        ", dhtTxId=" + res.xid() +
+                        ", node=" + nodeId +
+                        ", res=" + res + ']');
+                }
 
                 return;
             }
+            else if (txFinishMsgLog.isDebugEnabled()) {
+                txFinishMsgLog.debug("Received dht finish check committed response [txId=" + fut.tx().nearXidVersion() +
+                    ", dhtTxId=" + res.xid() +
+                    ", node=" + nodeId + ']');
+            }
 
             fut.onResult(nodeId, res);
         }
@@ -551,11 +609,21 @@ public class IgniteTxHandler {
             GridDhtTxFinishFuture fut = (GridDhtTxFinishFuture)ctx.mvcc().<IgniteInternalTx>future(res.futureId());
 
             if (fut == null) {
-                if (log.isDebugEnabled())
-                    log.debug("Received response for unknown future (will ignore): " + res);
+                if (txFinishMsgLog.isDebugEnabled()) {
+                    txFinishMsgLog.debug("Failed to find future for dht finish response [txId=null" +
+                        ", dhtTxId=" + res.xid() +
+                        ", node=" + nodeId +
+                        ", res=" + res);
+                }
 
                 return;
             }
+            else if (txFinishMsgLog.isDebugEnabled()) {
+                txFinishMsgLog.debug("Received dht finish response [txId=" + fut.tx().nearXidVersion() +
+                    ", dhtTxId=" + res.xid() +
+                    ", node=" + nodeId + ']');
+            }
+
 
             fut.onResult(nodeId, res);
         }
@@ -568,6 +636,9 @@ public class IgniteTxHandler {
      */
     @Nullable public IgniteInternalFuture<IgniteInternalTx> processNearTxFinishRequest(UUID nodeId,
         GridNearTxFinishRequest req) {
+        if (txFinishMsgLog.isDebugEnabled())
+            txFinishMsgLog.debug("Received near finish request [txId=" + req.version() + ", node=" + nodeId + ']');
+
         return finish(nodeId, null, req);
     }
 
@@ -645,9 +716,11 @@ public class IgniteTxHandler {
         if (tx == null && !req.explicitLock()) {
             assert locTx == null : "DHT local tx should never be lost for near local tx: " + locTx;
 
-            U.warn(log, "Received finish request for completed transaction (the message may be too late " +
-                "and transaction could have been DGCed by now) [commit=" + req.commit() +
-                ", xid=" + req.version() + ']');
+            U.warn(txFinishMsgLog, "Received finish request for completed transaction (the message may be too late) [" +
+                "txId=" + req.version() +
+                ", dhtTxId=" + dhtVer +
+                ", node=" + nodeId +
+                ", commit=" + req.commit() + ']');
 
             // Always send finish response.
             GridCacheMessage res = new GridNearTxFinishResponse(req.version(), req.threadId(), req.futureId(),
@@ -655,17 +728,31 @@ public class IgniteTxHandler {
 
             try {
                 ctx.io().send(nodeId, res, req.policy());
+
+                if (txFinishMsgLog.isDebugEnabled()) {
+                    txFinishMsgLog.debug("Sent near finish response for completed tx [txId=" + req.version() +
+                        ", dhtTxId=" + dhtVer +
+                        ", node=" + nodeId + ']');
+                }
             }
             catch (Throwable e) {
                 // Double-check.
                 if (ctx.discovery().node(nodeId) == null) {
-                    if (log.isDebugEnabled())
-                        log.debug("Node left while sending finish response [nodeId=" + nodeId + ", res=" + res +
-                            ']');
+                    if (txFinishMsgLog.isDebugEnabled()) {
+                        txFinishMsgLog.debug("Failed to send near finish response for completed tx, node failed [" +
+                            "txId=" + req.version() +
+                            ", dhtTxId=" + dhtVer +
+                            ", node=" + nodeId + ']');
+                    }
+                }
+                else {
+                    U.error(txFinishMsgLog, "Failed to send near finish response for completed tx, node failed [" +
+                        "txId=" + req.version() +
+                        ", dhtTxId=" + dhtVer +
+                        ", node=" + nodeId +
+                        ", req=" + req +
+                        ", res=" + res + ']', e);
                 }
-                else
-                    U.error(log, "Failed to send finish response to node [nodeId=" + nodeId + ", " +
-                        "res=" + res + ']', e);
 
                 if (e instanceof Error)
                     throw (Error)e;
@@ -778,15 +865,17 @@ public class IgniteTxHandler {
      * @param req Request.
      */
     protected final void processDhtTxPrepareRequest(UUID nodeId, GridDhtTxPrepareRequest req) {
+        if (txPrepareMsgLog.isDebugEnabled()) {
+            txPrepareMsgLog.debug("Received dht prepare request [txId=" + req.nearXidVersion() +
+                ", dhtTxId=" + req.version() +
+                ", node=" + nodeId + ']');
+        }
+
         assert nodeId != null;
         assert req != null;
 
         assert req.transactionNodes() != null;
 
-        if (log.isDebugEnabled())
-            log.debug("Processing dht tx prepare request [locNodeId=" + ctx.localNodeId() +
-                ", nodeId=" + nodeId + ", req=" + req + ']');
-
         GridDhtTxRemote dhtTx = null;
         GridNearTxRemote nearTx = null;
 
@@ -846,16 +935,28 @@ public class IgniteTxHandler {
         try {
             // Reply back to sender.
             ctx.io().send(nodeId, res, req.policy());
+
+            if (txPrepareMsgLog.isDebugEnabled()) {
+                txPrepareMsgLog.debug("Sent dht prepare response [txId=" + req.nearXidVersion() +
+                    ", dhtTxId=" + req.version() +
+                    ", node=" + nodeId + ']');
+            }
         }
         catch (IgniteCheckedException e) {
             if (e instanceof ClusterTopologyCheckedException) {
-                if (log.isDebugEnabled())
-                    log.debug("Failed to send tx response to remote node (node left grid) [node=" + nodeId +
-                        ", xid=" + req.version());
+                if (txPrepareMsgLog.isDebugEnabled()) {
+                    txPrepareMsgLog.debug("Failed to send dht prepare response, node left [txId=" + req.nearXidVersion() +
+                        ", dhtTxId=" + req.version() +
+                        ", node=" + nodeId + ']');
+                }
+            }
+            else {
+                U.warn(log, "Failed to send tx response to remote node (will rollback transaction) [" +
+                    "txId=" + req.nearXidVersion() +
+                    ", dhtTxId=" + req.version() +
+                    ", node=" + nodeId +
+                    ", err=" + e.getMessage() + ']');
             }
-            else
-                U.warn(log, "Failed to send tx response to remote node (will rollback transaction) [node=" + nodeId +
-                    ", xid=" + req.version() + ", err=" +  e.getMessage() + ']');
 
             if (nearTx != null)
                 nearTx.rollback();
@@ -874,18 +975,24 @@ public class IgniteTxHandler {
         assert nodeId != null;
         assert req != null;
 
-        if (log.isDebugEnabled())
-            log.debug("Processing dht tx finish request [nodeId=" + nodeId + ", req=" + req + ']');
-
         if (req.checkCommitted()) {
-            sendReply(nodeId, req, !ctx.tm().addRolledbackTx(null, req.version()));
+            sendReply(nodeId, req, !ctx.tm().addRolledbackTx(null, req.version()), null);
 
             return;
         }
 
-        GridDhtTxRemote dhtTx = ctx.tm().tx(req.version());
+        final GridDhtTxRemote dhtTx = ctx.tm().tx(req.version());
         GridNearTxRemote nearTx = ctx.tm().nearTx(req.version());
 
+        final GridCacheVersion nearTxId =
+            (dhtTx != null ? dhtTx.nearXidVersion() : (nearTx != null ? nearTx.nearXidVersion() : null));
+
+        if (txFinishMsgLog.isDebugEnabled()) {
+            txFinishMsgLog.debug("Received dht finish request [txId=" + nearTxId +
+                ", dhtTxId=" + req.version() +
+                ", node=" + nodeId + ']');
+        }
+
         // Safety - local transaction will finish explicitly.
         if (nearTx != null && nearTx.local())
             nearTx = null;
@@ -901,7 +1008,7 @@ public class IgniteTxHandler {
             IgniteInternalFuture<IgniteInternalTx> dhtFin = dhtTx == null ?
                 null : dhtTx.done() ? null : dhtTx.finishFuture();
 
-            IgniteInternalFuture<IgniteInternalTx> nearFin = nearTx == null ?
+            final IgniteInternalFuture<IgniteInternalTx> nearFin = nearTx == null ?
                 null : nearTx.done() ? null : nearTx.finishFuture();
 
             if (dhtFin != null && nearFin != null) {
@@ -920,15 +1027,15 @@ public class IgniteTxHandler {
             if (completeFut != null) {
                 completeFut.listen(new CI1<IgniteInternalFuture<IgniteInternalTx>>() {
                     @Override public void apply(IgniteInternalFuture<IgniteInternalTx> igniteTxIgniteFuture) {
-                        sendReply(nodeId, req, true);
+                        sendReply(nodeId, req, true, nearTxId);
                     }
                 });
             }
             else
-                sendReply(nodeId, req, true);
+                sendReply(nodeId, req, true, nearTxId);
         }
         else
-            sendReply(nodeId, req, true);
+            sendReply(nodeId, req, true, null);
     }
 
     /**
@@ -1045,8 +1152,9 @@ public class IgniteTxHandler {
      * @param nodeId Node id that originated finish request.
      * @param req Request.
      * @param committed {@code True} if transaction committed on this node.
+     * @param nearTxId Near tx version.
      */
-    protected void sendReply(UUID nodeId, GridDhtTxFinishRequest req, boolean committed) {
+    protected void sendReply(UUID nodeId, GridDhtTxFinishRequest req, boolean committed, GridCacheVersion nearTxId) {
         if (req.replyRequired()) {
             GridDhtTxFinishResponse res = new GridDhtTxFinishResponse(req.version(), req.futureId(), req.miniId());
 
@@ -1064,20 +1172,41 @@ public class IgniteTxHandler {
 
             try {
                 ctx.io().send(nodeId, res, req.policy());
+
+                if (txFinishMsgLog.isDebugEnabled()) {
+                    txFinishMsgLog.debug("Sent dht tx finish response [txId=" + nearTxId +
+                        ", dhtTxId=" + req.version() +
+                        ", node=" + nodeId +
+                        ", checkCommitted=" + req.checkCommitted() + ']');
+                }
             }
             catch (Throwable e) {
                 // Double-check.
                 if (ctx.discovery().node(nodeId) == null) {
-                    if (log.isDebugEnabled())
-                        log.debug("Node left while sending finish response [nodeId=" + nodeId + ", res=" + res + ']');
+                    if (txFinishMsgLog.isDebugEnabled()) {
+                        txFinishMsgLog.debug("Node left while send dht tx finish response [txId=" + nearTxId +
+                            ", dhtTxId=" + req.version() +
+                            ", node=" + nodeId + ']');
+                    }
+                }
+                else {
+                    U.error(log, "Failed to send finish response to node [txId=" + nearTxId +
+                        ", dhtTxId=" + req.version() +
+                        ", nodeId=" + nodeId +
+                        ", res=" + res + ']', e);
                 }
-                else
-                    U.error(log, "Failed to send finish response to node [nodeId=" + nodeId + ", res=" + res + ']', e);
 
                 if (e instanceof Error)
                     throw (Error)e;
             }
         }
+        else {
+            if (txFinishMsgLog.isDebugEnabled()) {
+                txFinishMsgLog.debug("Skip send dht tx finish response [txId=" + nearTxId +
+                    ", dhtTxId=" + req.version() +
+                    ", node=" + nodeId + ']');
+            }
+        }
     }
 
     /**
@@ -1334,8 +1463,10 @@ public class IgniteTxHandler {
     protected void processCheckPreparedTxRequest(final UUID nodeId,
         final GridCacheTxRecoveryRequest req)
     {
-        if (log.isDebugEnabled())
-            log.debug("Processing check prepared transaction requests [nodeId=" + nodeId + ", req=" + req + ']');
+        if (txRecoveryMsgLog.isDebugEnabled()) {
+            txRecoveryMsgLog.debug("Received tx recovery request [txId=" + req.nearXidVersion() +
+                ", node=" + nodeId + ']');
+        }
 
         IgniteInternalFuture<Boolean> fut = req.nearTxCheck() ? ctx.tm().txCommitted(req.nearXidVersion()) :
             ctx.tm().txsPreparedOrCommitted(req.nearXidVersion(), req.transactions());
@@ -1382,23 +1513,32 @@ public class IgniteTxHandler {
     private void sendCheckPreparedResponse(UUID nodeId,
         GridCacheTxRecoveryRequest req,
         boolean prepared) {
-        GridCacheTxRecoveryResponse res =
-            new GridCacheTxRecoveryResponse(req.version(), req.futureId(), req.miniId(), prepared,
-                req.deployInfo() != null);
+        GridCacheTxRecoveryResponse res = new GridCacheTxRecoveryResponse(req.version(),
+            req.futureId(),
+            req.miniId(),
+            prepared,
+            req.deployInfo() != null);
 
         try {
-            if (log.isDebugEnabled())
-                log.debug("Sending check prepared transaction response [nodeId=" + nodeId + ", res=" + res + ']');
-
             ctx.io().send(nodeId, res, req.system() ? UTILITY_CACHE_POOL : SYSTEM_POOL);
+
+            if (txRecoveryMsgLog.isDebugEnabled()) {
+                txRecoveryMsgLog.debug("Sent tx recovery response [txId=" + req.nearXidVersion() +
+                    ", node=" + nodeId + ", res=" + res + ']');
+            }
         }
         catch (ClusterTopologyCheckedException ignored) {
-            if (log.isDebugEnabled())
-                log.debug("Failed to send check prepared transaction response (did node leave grid?) [nodeId=" +
-                    nodeId + ", res=" + res + ']');
+            if (txRecoveryMsgLog.isDebugEnabled())
+                txRecoveryMsgLog.debug("Failed to send tx recovery response, node failed [" +
+                    ", txId=" + req.nearXidVersion() +
+                    ", node=" + nodeId +
+                    ", res=" + res + ']');
         }
         catch (IgniteCheckedException e) {
-            U.error(log, "Failed to send response to node [nodeId=" + nodeId + ", res=" + res + ']', e);
+            U.error(txRecoveryMsgLog, "Failed to send tx recovery response [txId=" + req.nearXidVersion() +
+                ", node=" + nodeId +
+                ", req=" + req +
+                ", res=" + res + ']', e);
         }
     }
 
@@ -1407,14 +1547,19 @@ public class IgniteTxHandler {
      * @param res Response.
      */
     protected void processCheckPreparedTxResponse(UUID nodeId, GridCacheTxRecoveryResponse res) {
-        if (log.isDebugEnabled())
-            log.debug("Processing check prepared transaction response [nodeId=" + nodeId + ", res=" + res + ']');
+        if (txRecoveryMsgLog.isDebugEnabled()) {
+            txRecoveryMsgLog.debug("Received tx recovery response [txId=" + res.version() +
+                ", node=" + nodeId +
+                ", res=" + res + ']');
+        }
 
         GridCacheTxRecoveryFuture fut = (GridCacheTxRecoveryFuture)ctx.mvcc().future(res.futureId());
 
         if (fut == null) {
-            if (log.isDebugEnabled())
-                log.debug("Received response for unknown future (will ignore): " + res);
+            if (txRecoveryMsgLog.isDebugEnabled()) {
+                txRecoveryMsgLog.debug("Failed to find future for tx recovery response [txId=" + res.version() +
+                    ", node=" + nodeId + ", res=" + res + ']');
+            }
 
             return;
         }

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/test/config/log4j-test.xml
----------------------------------------------------------------------
diff --git a/modules/core/src/test/config/log4j-test.xml b/modules/core/src/test/config/log4j-test.xml
index 29ae7b6..276de8c 100644
--- a/modules/core/src/test/config/log4j-test.xml
+++ b/modules/core/src/test/config/log4j-test.xml
@@ -96,6 +96,12 @@
      </category>
     -->
 
+    <!--
+    <category name="org.apache.ignite.cache.msg">
+        <level value="DEBUG"/>
+    </category>
+    -->
+
     <!-- Disable all open source debugging. -->
     <category name="org">
         <level value="INFO"/>


[13/50] [abbrv] ignite git commit: Backported test fixes.

Posted by vo...@apache.org.
Backported test fixes.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: e2ec9fede7793c164821b99da37455ac9f7c8fda
Parents: 5b6e781
Author: sboikov <sb...@gridgain.com>
Authored: Tue Jul 5 07:43:51 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Thu Jul 7 12:37:46 2016 +0300

----------------------------------------------------------------------
 .../cache/GridCacheAbstractSelfTest.java        | 113 +++++--------------
 1 file changed, 29 insertions(+), 84 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/e2ec9fed/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractSelfTest.java
index b918f28..d58e560 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractSelfTest.java
@@ -17,7 +17,6 @@
 
 package org.apache.ignite.internal.processors.cache;
 
-import java.util.Map;
 import java.util.concurrent.atomic.AtomicInteger;
 import javax.cache.Cache;
 import javax.cache.configuration.Factory;
@@ -30,7 +29,6 @@ import org.apache.ignite.cache.CacheMode;
 import org.apache.ignite.cache.CachePeekMode;
 import org.apache.ignite.cache.CacheWriteSynchronizationMode;
 import org.apache.ignite.cache.store.CacheStore;
-import org.apache.ignite.cache.store.CacheStoreAdapter;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.configuration.NearCacheConfiguration;
@@ -43,7 +41,6 @@ import org.apache.ignite.internal.util.typedef.P1;
 import org.apache.ignite.internal.util.typedef.R1;
 import org.apache.ignite.internal.util.typedef.X;
 import org.apache.ignite.internal.util.typedef.internal.U;
-import org.apache.ignite.lang.IgniteBiInClosure;
 import org.apache.ignite.lang.IgnitePredicate;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
@@ -52,7 +49,6 @@ import org.apache.ignite.testframework.GridTestUtils;
 import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
 import org.apache.ignite.transactions.Transaction;
 import org.jetbrains.annotations.Nullable;
-import org.jsr166.ConcurrentHashMap8;
 
 import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
 import static org.apache.ignite.cache.CacheMemoryMode.OFFHEAP_TIERED;
@@ -66,21 +62,12 @@ public abstract class GridCacheAbstractSelfTest extends GridCommonAbstractTest {
     /** Test timeout */
     private static final long TEST_TIMEOUT = 30 * 1000;
 
-    /** Store map. */
-    protected static final Map<Object, Object> map = new ConcurrentHashMap8<>();
-
-    /** Reads counter. */
-    protected static final AtomicInteger reads = new AtomicInteger();
-
-    /** Writes counter. */
-    protected static final AtomicInteger writes = new AtomicInteger();
-
-    /** Removes counter. */
-    protected static final AtomicInteger removes = new AtomicInteger();
-
     /** VM ip finder for TCP discovery. */
     protected static TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);
 
+    /** */
+    protected static TestCacheStoreStrategy storeStgy;
+
     /**
      * @return Grids count to start.
      */
@@ -97,6 +84,8 @@ public abstract class GridCacheAbstractSelfTest extends GridCommonAbstractTest {
 
         assert cnt >= 1 : "At least one grid must be started";
 
+        initStoreStrategy();
+
         startGrids(cnt);
 
         awaitPartitionMapExchange();
@@ -106,7 +95,18 @@ public abstract class GridCacheAbstractSelfTest extends GridCommonAbstractTest {
     @Override protected void afterTestsStopped() throws Exception {
         stopAllGrids();
 
-        map.clear();
+        if (storeStgy != null)
+            storeStgy.resetStore();
+    }
+
+    /**
+     * Initializes {@link #storeStgy} with respect to the nature of the test.
+     *
+     * @throws IgniteCheckedException If failed.
+     */
+    void initStoreStrategy() throws IgniteCheckedException {
+        if (storeStgy == null)
+            storeStgy = isMultiJvm() ? new H2CacheStoreStrategy() : new MapCacheStoreStrategy();
     }
 
     /** {@inheritDoc} */
@@ -188,28 +188,7 @@ public abstract class GridCacheAbstractSelfTest extends GridCommonAbstractTest {
         assert jcache().unwrap(Ignite.class).transactions().tx() == null;
         assertEquals("Cache is not empty", 0, jcache().localSize(CachePeekMode.ALL));
 
-        resetStore();
-    }
-
-    /**
-     * Cleans up cache store.
-     */
-    protected void resetStore() {
-        map.clear();
-
-        reads.set(0);
-        writes.set(0);
-        removes.set(0);
-    }
-
-    /**
-     * Put entry to cache store.
-     *
-     * @param key Key.
-     * @param val Value.
-     */
-    protected void putToStore(Object key, Object val) {
-        map.put(key, val);
+        storeStgy.resetStore();
     }
 
     /** {@inheritDoc} */
@@ -241,13 +220,18 @@ public abstract class GridCacheAbstractSelfTest extends GridCommonAbstractTest {
     protected CacheConfiguration cacheConfiguration(String gridName) throws Exception {
         CacheConfiguration cfg = defaultCacheConfiguration();
 
-        CacheStore<?, ?> store = cacheStore();
+        if (storeStgy != null) {
+            Factory<? extends CacheStore<Object, Object>> storeFactory = storeStgy.getStoreFactory();
 
-        if (store != null) {
-            cfg.setCacheStoreFactory(new TestStoreFactory());
-            cfg.setReadThrough(true);
-            cfg.setWriteThrough(true);
-            cfg.setLoadPreviousValue(true);
+            CacheStore<?, ?> store = storeFactory.create();
+
+            if (store != null) {
+                cfg.setCacheStoreFactory(storeFactory);
+                cfg.setReadThrough(true);
+                cfg.setWriteThrough(true);
+                cfg.setLoadPreviousValue(true);
+                storeStgy.updateCacheConfiguration(cfg);
+            }
         }
 
         cfg.setSwapEnabled(swapEnabled());
@@ -303,37 +287,6 @@ public abstract class GridCacheAbstractSelfTest extends GridCommonAbstractTest {
     }
 
     /**
-     * @return Write through storage emulator.
-     */
-    protected static CacheStore<?, ?> cacheStore() {
-        return new CacheStoreAdapter<Object, Object>() {
-            @Override public void loadCache(IgniteBiInClosure<Object, Object> clo,
-                Object... args) {
-                for (Map.Entry<Object, Object> e : map.entrySet())
-                    clo.apply(e.getKey(), e.getValue());
-            }
-
-            @Override public Object load(Object key) {
-                reads.incrementAndGet();
-
-                return map.get(key);
-            }
-
-            @Override public void write(javax.cache.Cache.Entry<? extends Object, ? extends Object> e) {
-                writes.incrementAndGet();
-
-                map.put(e.getKey(), e.getValue());
-            }
-
-            @Override public void delete(Object key) {
-                removes.incrementAndGet();
-
-                map.remove(key);
-            }
-        };
-    }
-
-    /**
      * @return {@code true} if swap should be enabled.
      */
     protected boolean swapEnabled() {
@@ -575,12 +528,4 @@ public abstract class GridCacheAbstractSelfTest extends GridCommonAbstractTest {
         }
     }
 
-    /**
-     * Serializable factory.
-     */
-    protected static class TestStoreFactory implements Factory<CacheStore> {
-        @Override public CacheStore create() {
-            return cacheStore();
-        }
-    }
 }


[50/50] [abbrv] ignite git commit: Added node-aware infrastructure.

Posted by vo...@apache.org.
Added node-aware infrastructure.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 0d7049c6a7fcce2fd007d513f0d68189141f87d7
Parents: 6f7e3a8
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Tue Sep 6 17:39:05 2016 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Tue Sep 6 17:39:05 2016 +0300

----------------------------------------------------------------------
 .../org/apache/ignite/internal/IgnitionEx.java  |   4 +
 .../internal/binary/BinaryMarshaller.java       |  12 +-
 .../internal/binary/BinaryReaderExImpl.java     |   5 +-
 .../internal/binary/BinaryWriterExImpl.java     |   5 +-
 .../ignite/internal/util/IgniteUtils.java       |  18 ++-
 .../AbstractNodeNameAwareMarshaller.java        | 134 +++++++++++++++++++
 .../ignite/marshaller/jdk/JdkMarshaller.java    |  12 +-
 .../optimized/OptimizedMarshaller.java          |  12 +-
 8 files changed, 178 insertions(+), 24 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/0d7049c6/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java b/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
index 62bfd4a..07b1e2c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
@@ -76,6 +76,7 @@ import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteBiTuple;
 import org.apache.ignite.logger.LoggerNodeIdAware;
 import org.apache.ignite.logger.java.JavaLogger;
+import org.apache.ignite.marshaller.AbstractNodeNameAwareMarshaller;
 import org.apache.ignite.marshaller.Marshaller;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.mxbean.IgnitionMXBean;
@@ -1934,6 +1935,9 @@ public class IgnitionEx {
                     marsh = new BinaryMarshaller();
             }
 
+            if (marsh instanceof AbstractNodeNameAwareMarshaller)
+                ((AbstractNodeNameAwareMarshaller)marsh).nodeName(cfg.getGridName());
+
             myCfg.setMarshaller(marsh);
 
             if (myCfg.getPeerClassLoadingLocalClassPathExclude() == null)

http://git-wip-us.apache.org/repos/asf/ignite/blob/0d7049c6/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryMarshaller.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryMarshaller.java
index 1cbc9ad..7d63353 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryMarshaller.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryMarshaller.java
@@ -25,7 +25,7 @@ import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.binary.BinaryObjectException;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.util.GridUnsafe;
-import org.apache.ignite.marshaller.AbstractMarshaller;
+import org.apache.ignite.marshaller.AbstractNodeNameAwareMarshaller;
 import org.jetbrains.annotations.Nullable;
 import sun.misc.Unsafe;
 
@@ -33,7 +33,7 @@ import sun.misc.Unsafe;
  * Implementation of {@link org.apache.ignite.marshaller.Marshaller} that lets to serialize and deserialize all objects
  * in the binary format.
  */
-public class BinaryMarshaller extends AbstractMarshaller {
+public class BinaryMarshaller extends AbstractNodeNameAwareMarshaller {
     /** */
     private GridBinaryMarshaller impl;
 
@@ -81,12 +81,12 @@ public class BinaryMarshaller extends AbstractMarshaller {
     }
 
     /** {@inheritDoc} */
-    @Override public byte[] marshal(@Nullable Object obj) throws IgniteCheckedException {
+    @Override public byte[] marshal0(@Nullable Object obj) throws IgniteCheckedException {
         return impl.marshal(obj);
     }
 
     /** {@inheritDoc} */
-    @Override public void marshal(@Nullable Object obj, OutputStream out) throws IgniteCheckedException {
+    @Override public void marshal0(@Nullable Object obj, OutputStream out) throws IgniteCheckedException {
         byte[] arr = marshal(obj);
 
         try {
@@ -98,12 +98,12 @@ public class BinaryMarshaller extends AbstractMarshaller {
     }
 
     /** {@inheritDoc} */
-    @Override public <T> T unmarshal(byte[] bytes, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
+    @Override public <T> T unmarshal0(byte[] bytes, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
         return impl.deserialize(bytes, clsLdr);
     }
 
     /** {@inheritDoc} */
-    @Override public <T> T unmarshal(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
+    @Override public <T> T unmarshal0(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
         ByteArrayOutputStream buf = new ByteArrayOutputStream();
 
         // we have to fully read the InputStream because GridBinaryMarshaller requires support of a method that

http://git-wip-us.apache.org/repos/asf/ignite/blob/0d7049c6/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryReaderExImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryReaderExImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryReaderExImpl.java
index 3481ca3..0d1c839 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryReaderExImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryReaderExImpl.java
@@ -1421,13 +1421,14 @@ public class BinaryReaderExImpl implements BinaryReader, BinaryRawReaderEx, Bina
      * @throws BinaryObjectException If failed.
      */
     @Nullable Object deserialize() throws BinaryObjectException {
-        String oldName = IgniteUtils.setCurrentIgniteName(ctx.configuration().getGridName());
+        String newName = ctx.configuration().getGridName();
+        String oldName = IgniteUtils.setCurrentIgniteName(newName);
 
         try {
             return deserialize0();
         }
         finally {
-            IgniteUtils.restoreCurrentIgniteName(oldName);
+            IgniteUtils.restoreOldIgniteName(oldName, newName);
         }
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/0d7049c6/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java
index b3963d8..9536f31 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java
@@ -140,13 +140,14 @@ public class BinaryWriterExImpl implements BinaryWriter, BinaryRawWriterEx, Obje
      * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
      */
     void marshal(Object obj, boolean enableReplace) throws BinaryObjectException {
-        String oldName = IgniteUtils.setCurrentIgniteName(ctx.configuration().getGridName());
+        String newName = ctx.configuration().getGridName();
+        String oldName = IgniteUtils.setCurrentIgniteName(newName);
 
         try {
             marshal0(obj, enableReplace);
         }
         finally {
-            IgniteUtils.restoreCurrentIgniteName(oldName);
+            IgniteUtils.restoreOldIgniteName(oldName, newName);
         }
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/0d7049c6/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
index b6f2081..f932bda 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
@@ -490,7 +490,7 @@ public abstract class IgniteUtils {
     private static Method toStringMtd;
 
     /** Empty local Ignite name. */
-    private static final String LOC_IGNITE_NAME_EMPTY = new String();
+    public static final String LOC_IGNITE_NAME_EMPTY = new String();
 
     /** Local Ignite name thread local. */
     private static final ThreadLocal<String> LOC_IGNITE_NAME = new ThreadLocal<String>() {
@@ -9592,10 +9592,12 @@ public abstract class IgniteUtils {
      * @param newName New name.
      * @return Old name.
      */
+    @SuppressWarnings("StringEquality")
     @Nullable public static String setCurrentIgniteName(@Nullable String newName) {
         String oldName = LOC_IGNITE_NAME.get();
 
-        LOC_IGNITE_NAME.set(newName);
+        if (oldName != newName)
+            LOC_IGNITE_NAME.set(newName);
 
         return oldName;
     }
@@ -9608,4 +9610,16 @@ public abstract class IgniteUtils {
     public static void restoreCurrentIgniteName(@Nullable String oldName) {
         LOC_IGNITE_NAME.set(oldName);
     }
+
+    /**
+     * Restore old Ignite name.
+     *
+     * @param oldName Old name.
+     * @param curName Current name.
+     */
+    @SuppressWarnings("StringEquality")
+    public static void restoreOldIgniteName(@Nullable String oldName, @Nullable String curName) {
+        if (oldName != curName)
+            LOC_IGNITE_NAME.set(oldName);
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/0d7049c6/modules/core/src/main/java/org/apache/ignite/marshaller/AbstractNodeNameAwareMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/marshaller/AbstractNodeNameAwareMarshaller.java b/modules/core/src/main/java/org/apache/ignite/marshaller/AbstractNodeNameAwareMarshaller.java
new file mode 100644
index 0000000..270fdea
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/marshaller/AbstractNodeNameAwareMarshaller.java
@@ -0,0 +1,134 @@
+/*
+ * 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.marshaller;
+
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.Ignition;
+import org.apache.ignite.internal.util.IgniteUtils;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.jetbrains.annotations.Nullable;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * Marshaller allowing for {@link Ignition#localIgnite()} calls.
+ */
+public abstract class AbstractNodeNameAwareMarshaller extends AbstractMarshaller {
+    /** Node name. */
+    private volatile String nodeName = U.LOC_IGNITE_NAME_EMPTY;
+
+    /**
+     * Set node name.
+     *
+     * @param nodeName Node name.
+     */
+    public void nodeName(@Nullable String nodeName) {
+        this.nodeName = nodeName;
+    }
+
+    /** {@inheritDoc} */
+    @Override public byte[] marshal(@Nullable Object obj) throws IgniteCheckedException {
+        String oldNodeName = IgniteUtils.setCurrentIgniteName(nodeName);
+
+        try {
+            return marshal0(obj);
+        }
+        finally {
+            IgniteUtils.restoreOldIgniteName(oldNodeName, nodeName);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void marshal(@Nullable Object obj, OutputStream out) throws IgniteCheckedException {
+        String oldNodeName = IgniteUtils.setCurrentIgniteName(nodeName);
+
+        try {
+            marshal0(obj, out);
+        }
+        finally {
+            IgniteUtils.restoreOldIgniteName(oldNodeName, nodeName);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> T unmarshal(byte[] arr, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
+        String oldNodeName = IgniteUtils.setCurrentIgniteName(nodeName);
+
+        try {
+            return unmarshal0(arr, clsLdr);
+        }
+        finally {
+            IgniteUtils.restoreOldIgniteName(oldNodeName, nodeName);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public <T> T unmarshal(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
+        String oldNodeName = IgniteUtils.setCurrentIgniteName(nodeName);
+
+        try {
+            return unmarshal0(in, clsLdr);
+        }
+        finally {
+            IgniteUtils.restoreOldIgniteName(oldNodeName, nodeName);
+        }
+    }
+
+    /**
+     * Marshals object to the output stream. This method should not close
+     * given output stream.
+     *
+     * @param obj Object to marshal.
+     * @param out Output stream to marshal into.
+     * @throws IgniteCheckedException If marshalling failed.
+     */
+    protected abstract void marshal0(@Nullable Object obj, OutputStream out) throws IgniteCheckedException;
+
+    /**
+     * Marshals object to byte array.
+     *
+     * @param obj Object to marshal.
+     * @return Byte array.
+     * @throws IgniteCheckedException If marshalling failed.
+     */
+    protected abstract byte[] marshal0(@Nullable Object obj) throws IgniteCheckedException;
+
+    /**
+     * Unmarshals object from the input stream using given class loader.
+     * This method should not close given input stream.
+     *
+     * @param <T> Type of unmarshalled object.
+     * @param in Input stream.
+     * @param clsLdr Class loader to use.
+     * @return Unmarshalled object.
+     * @throws IgniteCheckedException If unmarshalling failed.
+     */
+    protected abstract <T> T unmarshal0(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException;
+
+    /**
+     * Unmarshals object from byte array using given class loader.
+     *
+     * @param <T> Type of unmarshalled object.
+     * @param arr Byte array.
+     * @param clsLdr Class loader to use.
+     * @return Unmarshalled object.
+     * @throws IgniteCheckedException If unmarshalling failed.
+     */
+    protected abstract <T> T unmarshal0(byte[] arr, @Nullable ClassLoader clsLdr) throws IgniteCheckedException;
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/0d7049c6/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java b/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java
index c8bb383..bcde7f4 100644
--- a/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java
+++ b/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java
@@ -27,7 +27,7 @@ import org.apache.ignite.internal.util.io.GridByteArrayInputStream;
 import org.apache.ignite.internal.util.io.GridByteArrayOutputStream;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
-import org.apache.ignite.marshaller.AbstractMarshaller;
+import org.apache.ignite.marshaller.AbstractNodeNameAwareMarshaller;
 import org.jetbrains.annotations.Nullable;
 
 /**
@@ -65,9 +65,9 @@ import org.jetbrains.annotations.Nullable;
  * <br>
  * For information about Spring framework visit <a href="http://www.springframework.org/">www.springframework.org</a>
  */
-public class JdkMarshaller extends AbstractMarshaller {
+public class JdkMarshaller extends AbstractNodeNameAwareMarshaller {
     /** {@inheritDoc} */
-    @Override public void marshal(@Nullable Object obj, OutputStream out) throws IgniteCheckedException {
+    @Override public void marshal0(@Nullable Object obj, OutputStream out) throws IgniteCheckedException {
         assert out != null;
 
         ObjectOutputStream objOut = null;
@@ -89,7 +89,7 @@ public class JdkMarshaller extends AbstractMarshaller {
     }
 
     /** {@inheritDoc} */
-    @Override public byte[] marshal(@Nullable Object obj) throws IgniteCheckedException {
+    @Override public byte[] marshal0(@Nullable Object obj) throws IgniteCheckedException {
         GridByteArrayOutputStream out = null;
 
         try {
@@ -106,7 +106,7 @@ public class JdkMarshaller extends AbstractMarshaller {
 
     /** {@inheritDoc} */
     @SuppressWarnings({"unchecked"})
-    @Override public <T> T unmarshal(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
+    @Override public <T> T unmarshal0(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
         assert in != null;
 
         if (clsLdr == null)
@@ -133,7 +133,7 @@ public class JdkMarshaller extends AbstractMarshaller {
     }
 
     /** {@inheritDoc} */
-    @Override public <T> T unmarshal(byte[] arr, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
+    @Override public <T> T unmarshal0(byte[] arr, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
         GridByteArrayInputStream in = null;
 
         try {

http://git-wip-us.apache.org/repos/asf/ignite/blob/0d7049c6/modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedMarshaller.java b/modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedMarshaller.java
index b2c98b2..7c22dee 100644
--- a/modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedMarshaller.java
+++ b/modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedMarshaller.java
@@ -28,7 +28,7 @@ import org.apache.ignite.IgniteException;
 import org.apache.ignite.IgniteSystemProperties;
 import org.apache.ignite.internal.util.GridUnsafe;
 import org.apache.ignite.internal.util.typedef.internal.U;
-import org.apache.ignite.marshaller.AbstractMarshaller;
+import org.apache.ignite.marshaller.AbstractNodeNameAwareMarshaller;
 import org.jetbrains.annotations.Nullable;
 import org.jsr166.ConcurrentHashMap8;
 import sun.misc.Unsafe;
@@ -83,7 +83,7 @@ import static org.apache.ignite.IgniteSystemProperties.IGNITE_OPTIMIZED_MARSHALL
  * <br>
  * For information about Spring framework visit <a href="http://www.springframework.org/">www.springframework.org</a>
  */
-public class OptimizedMarshaller extends AbstractMarshaller {
+public class OptimizedMarshaller extends AbstractNodeNameAwareMarshaller {
     /** Use default {@code serialVersionUID} for {@link Serializable} classes. */
     public static final boolean USE_DFLT_SUID =
         IgniteSystemProperties.getBoolean(IGNITE_OPTIMIZED_MARSHALLER_USE_DEFAULT_SUID, false);
@@ -159,7 +159,7 @@ public class OptimizedMarshaller extends AbstractMarshaller {
     }
 
     /** {@inheritDoc} */
-    @Override public void marshal(@Nullable Object obj, OutputStream out) throws IgniteCheckedException {
+    @Override public void marshal0(@Nullable Object obj, OutputStream out) throws IgniteCheckedException {
         assert out != null;
 
         OptimizedObjectOutputStream objOut = null;
@@ -182,7 +182,7 @@ public class OptimizedMarshaller extends AbstractMarshaller {
     }
 
     /** {@inheritDoc} */
-    @Override public byte[] marshal(@Nullable Object obj) throws IgniteCheckedException {
+    @Override public byte[] marshal0(@Nullable Object obj) throws IgniteCheckedException {
         OptimizedObjectOutputStream objOut = null;
 
         try {
@@ -204,7 +204,7 @@ public class OptimizedMarshaller extends AbstractMarshaller {
 
     /** {@inheritDoc} */
     @SuppressWarnings("unchecked")
-    @Override public <T> T unmarshal(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
+    @Override public <T> T unmarshal0(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
         assert in != null;
 
         OptimizedObjectInputStream objIn = null;
@@ -233,7 +233,7 @@ public class OptimizedMarshaller extends AbstractMarshaller {
 
     /** {@inheritDoc} */
     @SuppressWarnings("unchecked")
-    @Override public <T> T unmarshal(byte[] arr, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
+    @Override public <T> T unmarshal0(byte[] arr, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
         assert arr != null;
 
         OptimizedObjectInputStream objIn = null;


[25/50] [abbrv] ignite git commit: ignite-3254 - fixed

Posted by vo...@apache.org.
ignite-3254 - fixed


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 4d2be722935da42c82310ce70db996c5752f72f6
Parents: 10224df
Author: Sergi Vladykin <se...@gmail.com>
Authored: Wed Jul 13 20:19:25 2016 +0300
Committer: Sergi Vladykin <se...@gmail.com>
Committed: Wed Jul 13 20:19:25 2016 +0300

----------------------------------------------------------------------
 .../examples/IndexingBridgeMethodTest.java      | 93 ++++++++++++++++++++
 .../IgniteExamplesJ8SelfTestSuite.java          |  2 +
 .../configuration/CacheConfiguration.java       |  3 +
 3 files changed, 98 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/4d2be722/examples/src/test/java8/org/apache/ignite/java8/examples/IndexingBridgeMethodTest.java
----------------------------------------------------------------------
diff --git a/examples/src/test/java8/org/apache/ignite/java8/examples/IndexingBridgeMethodTest.java b/examples/src/test/java8/org/apache/ignite/java8/examples/IndexingBridgeMethodTest.java
new file mode 100644
index 0000000..2837ed6
--- /dev/null
+++ b/examples/src/test/java8/org/apache/ignite/java8/examples/IndexingBridgeMethodTest.java
@@ -0,0 +1,93 @@
+/*
+ * 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.java8.examples;
+
+
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.cache.query.SqlFieldsQuery;
+import org.apache.ignite.cache.query.annotations.QuerySqlField;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+/**
+ * Test covering bridge methods changes in Java 8.
+ */
+public class IndexingBridgeMethodTest extends GridCommonAbstractTest {
+    /**
+     * @throws Exception If failed.
+     */
+    public void testBridgeMethod() throws Exception {
+        Ignite ignite = startGrid();
+
+        CacheConfiguration<Integer, MyType> ccfg = new CacheConfiguration<>();
+
+        ccfg.setName("mytype");
+        ccfg.setIndexedTypes(Integer.class, MyType.class);
+
+        IgniteCache<Integer,MyType> c = ignite.getOrCreateCache(ccfg);
+
+        for (int i = 0; i < 100; i++)
+            c.put(i, new MyType(i));
+
+        assertEquals(100L, c.query(new SqlFieldsQuery(
+            "select count(*) from MyType")).getAll().get(0).get(0));
+        assertEquals(15, c.query(new SqlFieldsQuery(
+            "select id from MyType where _key = 15")).getAll().get(0).get(0));
+        assertEquals(25, c.query(new SqlFieldsQuery(
+            "select _key from MyType where id = 25")).getAll().get(0).get(0));
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+    }
+
+    /**
+     * Classes implementing this method, will have bridge method.
+     */
+    private static interface HasId<T extends Number> {
+        /**
+         * @return ID.
+         */
+        public T getId();
+    }
+
+    /**
+     *
+     */
+    private static class MyType implements HasId<Integer> {
+        /** */
+        private int id;
+
+        /**
+         * @param id Id.
+         */
+        private MyType(int id) {
+            this.id = id;
+        }
+
+        /**
+         * @return ID.
+         */
+        @QuerySqlField(index = true)
+        @Override public Integer getId() {
+            return id;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/4d2be722/examples/src/test/java8/org/apache/ignite/java8/testsuites/IgniteExamplesJ8SelfTestSuite.java
----------------------------------------------------------------------
diff --git a/examples/src/test/java8/org/apache/ignite/java8/testsuites/IgniteExamplesJ8SelfTestSuite.java b/examples/src/test/java8/org/apache/ignite/java8/testsuites/IgniteExamplesJ8SelfTestSuite.java
index 57e48f9..949324c 100644
--- a/examples/src/test/java8/org/apache/ignite/java8/testsuites/IgniteExamplesJ8SelfTestSuite.java
+++ b/examples/src/test/java8/org/apache/ignite/java8/testsuites/IgniteExamplesJ8SelfTestSuite.java
@@ -24,6 +24,7 @@ import org.apache.ignite.java8.examples.CacheExamplesMultiNodeSelfTest;
 import org.apache.ignite.java8.examples.CacheExamplesSelfTest;
 import org.apache.ignite.java8.examples.EventsExamplesMultiNodeSelfTest;
 import org.apache.ignite.java8.examples.EventsExamplesSelfTest;
+import org.apache.ignite.java8.examples.IndexingBridgeMethodTest;
 import org.apache.ignite.java8.examples.MessagingExamplesSelfTest;
 import org.apache.ignite.testframework.GridTestUtils;
 
@@ -45,6 +46,7 @@ public class IgniteExamplesJ8SelfTestSuite extends TestSuite {
 
         TestSuite suite = new TestSuite("Ignite Examples Test Suite");
 
+        suite.addTest(new TestSuite(IndexingBridgeMethodTest.class));
         suite.addTest(new TestSuite(CacheExamplesSelfTest.class));
         suite.addTest(new TestSuite(BasicExamplesSelfTest.class));
 //        suite.addTest(new TestSuite(ContinuationExamplesSelfTest.class));

http://git-wip-us.apache.org/repos/asf/ignite/blob/4d2be722/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java b/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
index 07542de..3276627 100644
--- a/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
+++ b/modules/core/src/main/java/org/apache/ignite/configuration/CacheConfiguration.java
@@ -2292,6 +2292,9 @@ public class CacheConfiguration<K, V> extends MutableConfiguration<K, V> {
             }
 
             for (Method mtd : c.getDeclaredMethods()) {
+                if (mtd.isBridge())
+                    continue;
+
                 QuerySqlField sqlAnn = mtd.getAnnotation(QuerySqlField.class);
                 QueryTextField txtAnn = mtd.getAnnotation(QueryTextField.class);
 


[18/50] [abbrv] ignite git commit: CacheKeepBinaryIterationSwapEnabledTest fix.

Posted by vo...@apache.org.
CacheKeepBinaryIterationSwapEnabledTest fix.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 7aa609aa54f0015649776105bf32b2a213fa031d
Parents: 005ce0f
Author: Anton Vinogradov <av...@apache.org>
Authored: Mon Jul 11 15:30:53 2016 +0300
Committer: Anton Vinogradov <av...@apache.org>
Committed: Mon Jul 11 15:30:53 2016 +0300

----------------------------------------------------------------------
 .../cache/CacheEvictableEntryImpl.java          | 11 ++++--
 .../CacheKeepBinaryIterationTest.java           | 36 ++++++++++----------
 2 files changed, 27 insertions(+), 20 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/7aa609aa/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEvictableEntryImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEvictableEntryImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEvictableEntryImpl.java
index 9f4d9d7..aef71ed 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEvictableEntryImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEvictableEntryImpl.java
@@ -64,9 +64,16 @@ public class CacheEvictableEntryImpl<K, V> implements EvictableEntry<K, V> {
 
         try {
             assert ctx != null;
-            assert ctx.evicts() != null;
 
-            return ctx.evicts().evict(cached, null, false, null);
+            GridCacheEvictionManager mgr = ctx.evicts();
+
+            if (mgr == null) {
+                assert ctx.kernalContext().isStopping();
+
+                return false;
+            }
+
+            return mgr.evict(cached, null, false, null);
         }
         catch (IgniteCheckedException e) {
             U.error(ctx.grid().log(), "Failed to evict entry from cache: " + cached, e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/7aa609aa/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheKeepBinaryIterationTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheKeepBinaryIterationTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheKeepBinaryIterationTest.java
index a775d21..605181f 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheKeepBinaryIterationTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheKeepBinaryIterationTest.java
@@ -29,11 +29,9 @@ import org.apache.ignite.cache.query.QueryCursor;
 import org.apache.ignite.cache.query.ScanQuery;
 import org.apache.ignite.configuration.CacheConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
-import org.apache.ignite.internal.IgniteInterruptedCheckedException;
 import org.apache.ignite.internal.binary.BinaryMarshaller;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.internal.S;
-import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi;
 import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
 import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
@@ -221,11 +219,11 @@ public class CacheKeepBinaryIterationTest extends GridCommonAbstractTest {
     /**
      * @param ccfg Cache configuration.
      */
-    private void doTestScanQuery(CacheConfiguration<Object, Object> ccfg, boolean keepBinary,
-        boolean primitives) throws IgniteInterruptedCheckedException {
+    private void doTestScanQuery(final CacheConfiguration<Object, Object> ccfg, boolean keepBinary,
+        boolean primitives) throws Exception {
         IgniteCache<Object, Object> cache = grid(0).createCache(ccfg);
 
-        assertTrue(cache.size() == 0);
+        assertEquals(0, cache.size());
 
         try {
             for (int i = 0; i < KEYS; i++)
@@ -272,24 +270,25 @@ public class CacheKeepBinaryIterationTest extends GridCommonAbstractTest {
             }
         }
         finally {
-            cache.removeAll();
+            if (ccfg.getEvictionPolicy() != null) { // TODO: IGNITE-3462. Fixes evictionPolicy issues at cache destroy.
+                stopAllGrids();
 
-            if (ccfg.getEvictionPolicy() != null)
-                U.sleep(1000); // Fixes evictionPolicy issues at cache destroy.
-
-            grid(0).destroyCache(ccfg.getName());
+                startGridsMultiThreaded(getServerNodeCount());
+            }
+            else
+                grid(0).destroyCache(ccfg.getName());
         }
     }
 
     /**
      * @param ccfg Cache configuration.
      */
-    private void doTestLocalEntries(CacheConfiguration<Object, Object> ccfg,
+    private void doTestLocalEntries(final CacheConfiguration<Object, Object> ccfg,
         boolean keepBinary,
-        boolean primitives) throws IgniteInterruptedCheckedException {
+        boolean primitives) throws Exception {
         IgniteCache<Object, Object> cache = grid(0).createCache(ccfg);
 
-        assertTrue(cache.size() == 0);
+        assertEquals(0, cache.size());
 
         try {
             for (int i = 0; i < KEYS; i++)
@@ -341,12 +340,13 @@ public class CacheKeepBinaryIterationTest extends GridCommonAbstractTest {
             }
         }
         finally {
-            cache.removeAll();
+            if (ccfg.getEvictionPolicy() != null) { // TODO: IGNITE-3462. Fixes evictionPolicy issues at cache destroy.
+                stopAllGrids();
 
-            if (ccfg.getEvictionPolicy() != null)
-                U.sleep(1000); // Fixes evictionPolicy issues at cache destroy.
-
-            grid(0).destroyCache(ccfg.getName());
+                startGridsMultiThreaded(getServerNodeCount());
+            }
+            else
+                grid(0).destroyCache(ccfg.getName());
         }
     }
 


[43/50] [abbrv] ignite git commit: Print debug information on 'waitForRent' timeout.

Posted by vo...@apache.org.
Print debug information on 'waitForRent' timeout.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 7cf26d9601f25b96198172f1c8140a0a34687814
Parents: a39770a
Author: sboikov <sb...@gridgain.com>
Authored: Tue Jul 26 15:48:36 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Tue Jul 26 15:48:36 2016 +0300

----------------------------------------------------------------------
 .../distributed/dht/GridDhtLocalPartition.java  |  2 +-
 .../dht/GridDhtPartitionTopologyImpl.java       | 36 +++++++++++++++++++-
 2 files changed, 36 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/7cf26d96/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLocalPartition.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLocalPartition.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLocalPartition.java
index 2c33fa2..6ea6159 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLocalPartition.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtLocalPartition.java
@@ -507,7 +507,7 @@ public class GridDhtLocalPartition implements Comparable<GridDhtLocalPartition>,
     /**
      * @return {@code true} If there is a group reservation.
      */
-    private boolean groupReserved() {
+    public boolean groupReserved() {
         for (GridDhtPartitionsReservation reservation : reservations) {
             if (!reservation.invalidate())
                 return true; // Failed to invalidate reservation -> we are reserved.

http://git-wip-us.apache.org/repos/asf/ignite/blob/7cf26d96/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtPartitionTopologyImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtPartitionTopologyImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtPartitionTopologyImpl.java
index 501388c..f9344bc 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtPartitionTopologyImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtPartitionTopologyImpl.java
@@ -32,8 +32,10 @@ import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.IgniteSystemProperties;
 import org.apache.ignite.cluster.ClusterNode;
 import org.apache.ignite.events.DiscoveryEvent;
+import org.apache.ignite.internal.IgniteFutureTimeoutCheckedException;
 import org.apache.ignite.internal.IgniteInterruptedCheckedException;
 import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.processors.cache.GridCacheContext;
@@ -51,6 +53,7 @@ import org.apache.ignite.internal.util.typedef.internal.U;
 import org.jetbrains.annotations.Nullable;
 import org.jsr166.ConcurrentHashMap8;
 
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT;
 import static org.apache.ignite.events.EventType.EVT_CACHE_REBALANCE_PART_DATA_LOST;
 import static org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState.EVICTED;
 import static org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState.MOVING;
@@ -171,6 +174,11 @@ class GridDhtPartitionTopologyImpl implements GridDhtPartitionTopology {
     private boolean waitForRent() throws IgniteCheckedException {
         boolean changed = false;
 
+        final long longOpDumpTimeout =
+            IgniteSystemProperties.getLong(IgniteSystemProperties.IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT, 60_000);
+
+        int dumpCnt = 0;
+
         // Synchronously wait for all renting partitions to complete.
         for (Iterator<GridDhtLocalPartition> it = locParts.values().iterator(); it.hasNext();) {
             GridDhtLocalPartition p = it.next();
@@ -182,7 +190,33 @@ class GridDhtPartitionTopologyImpl implements GridDhtPartitionTopology {
                     log.debug("Waiting for renting partition: " + p);
 
                 // Wait for partition to empty out.
-                p.rent(true).get();
+                if (longOpDumpTimeout > 0) {
+                    while (true) {
+                        try {
+                            p.rent(true).get(longOpDumpTimeout);
+
+                            break;
+                        }
+                        catch (IgniteFutureTimeoutCheckedException e) {
+                            if (dumpCnt++ < GridDhtPartitionsExchangeFuture.DUMP_PENDING_OBJECTS_THRESHOLD) {
+                                U.warn(log, "Failed to wait for partition eviction [" +
+                                    "topVer=" + topVer +
+                                    ", cache=" + cctx.name() +
+                                    ", part=" + p.id() +
+                                    ", partState=" + p.state() +
+                                    ", size=" + p.size() +
+                                    ", reservations=" + p.reservations() +
+                                    ", grpReservations=" + p.groupReserved() +
+                                    ", node=" + cctx.localNodeId() + "]");
+
+                                if (IgniteSystemProperties.getBoolean(IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT, false))
+                                    U.dumpThreads(log);
+                            }
+                        }
+                    }
+                }
+                else
+                    p.rent(true).get();
 
                 if (log.isDebugEnabled())
                     log.debug("Finished waiting for renting partition: " + p);


[30/50] [abbrv] ignite git commit: Merge branch 'gridgain-7.5.30' into ignite-1849

Posted by vo...@apache.org.
Merge branch 'gridgain-7.5.30' into ignite-1849


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 6f7df5ebf77d338f524c4d055fcf21c717f93e1f
Parents: a33dd1c 4897315
Author: Alexander Paschenko <al...@gmail.com>
Authored: Mon Jul 18 13:58:32 2016 +0300
Committer: Alexander Paschenko <al...@gmail.com>
Committed: Mon Jul 18 13:58:32 2016 +0300

----------------------------------------------------------------------
 .../examples/IndexingBridgeMethodTest.java      |  93 +++++++
 .../IgniteExamplesJ8SelfTestSuite.java          |   2 +
 .../org/apache/ignite/IgniteDataStreamer.java   |  52 +++-
 .../IgniteDataStreamerTimeoutException.java     |  45 +++
 .../configuration/CacheConfiguration.java       |   3 +
 .../processors/cache/GridCacheProcessor.java    |   2 +
 .../continuous/CacheContinuousQueryManager.java |   4 +-
 .../datastreamer/DataStreamerImpl.java          |  71 ++++-
 .../service/GridServiceProcessor.java           |  70 ++++-
 .../processors/service/GridServiceProxy.java    |  54 ++--
 .../ignite/internal/util/IgniteUtils.java       |  21 ++
 .../OptimizedObjectStreamRegistry.java          | 145 +++++-----
 ...eContinuousQueryMultiNodesFilteringTest.java | 278 +++++++++++++++++++
 ...dCacheContinuousQueryNodesFilteringTest.java | 168 +++++++++++
 .../datastreamer/DataStreamerTimeoutTest.java   | 163 +++++++++++
 ...rviceDeploymentExceptionPropagationTest.java |  80 ++++++
 .../OptimizedMarshallerPooledSelfTest.java      |  44 +++
 .../testsuites/IgniteBinaryBasicTestSuite.java  |   2 +
 .../ignite/testsuites/IgniteCacheTestSuite.java |   2 +
 .../IgniteMarshallerSelfTestSuite.java          |   2 +
 .../IgniteCacheQuerySelfTestSuite3.java         |   4 +
 .../ignite/visor/commands/VisorConsole.scala    |   5 +-
 .../commands/alert/VisorAlertCommand.scala      |   2 +-
 .../commands/cache/VisorCacheCommand.scala      |  40 ++-
 .../commands/cache/VisorCacheStopCommand.scala  |   2 +-
 .../config/VisorConfigurationCommand.scala      |  23 +-
 .../commands/events/VisorEventsCommand.scala    |  29 +-
 .../visor/commands/gc/VisorGcCommand.scala      |  11 +-
 .../visor/commands/kill/VisorKillCommand.scala  | 184 ++++++++----
 .../visor/commands/node/VisorNodeCommand.scala  |  13 +-
 .../visor/commands/vvm/VisorVvmCommand.scala    |  11 +-
 .../scala/org/apache/ignite/visor/visor.scala   |  76 +++--
 32 files changed, 1470 insertions(+), 231 deletions(-)
----------------------------------------------------------------------



[38/50] [abbrv] ignite git commit: IGNITE-3511: .NET: Fixed AffinityFunctionBase.cs placement, added missing Package-Info.cs files.

Posted by vo...@apache.org.
IGNITE-3511: .NET: Fixed AffinityFunctionBase.cs placement, added missing Package-Info.cs files.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 448571ba2ca1b05197b17a38d157babf4cb4f203
Parents: 7364938
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Tue Jul 19 16:11:23 2016 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Tue Jul 19 16:11:23 2016 +0300

----------------------------------------------------------------------
 .../Apache.Ignite.Core.csproj                   |   5 +-
 .../Cache/Affinity/AffinityFunctionBase.cs      | 139 ------------------
 .../Cache/Affinity/Fair/FairAffinityFunction.cs |   1 +
 .../Cache/Affinity/Fair/Package-Info.cs         |  26 ++++
 .../Cache/Affinity/Package-Info.cs              |  26 ++++
 .../Cache/Affinity/Rendezvous/Package-Info.cs   |  26 ++++
 .../Rendezvous/RendezvousAffinityFunction.cs    |   1 +
 .../Impl/Cache/Affinity/AffinityFunctionBase.cs | 140 +++++++++++++++++++
 8 files changed, 224 insertions(+), 140 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/448571ba/modules/platforms/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj b/modules/platforms/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
index 6793873..3736988 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj
@@ -55,11 +55,13 @@
   </ItemGroup>
   <ItemGroup>
     <Compile Include="Binary\Package-Info.cs" />
-    <Compile Include="Cache\Affinity\AffinityFunctionBase.cs" />
     <Compile Include="Cache\Affinity\AffinityFunctionContext.cs" />
     <Compile Include="Cache\Affinity\AffinityTopologyVersion.cs" />
     <Compile Include="Cache\Affinity\Fair\FairAffinityFunction.cs" />
+    <Compile Include="Cache\Affinity\Fair\Package-Info.cs" />
+    <Compile Include="Cache\Affinity\Rendezvous\Package-Info.cs" />
     <Compile Include="Cache\Affinity\IAffinityFunction.cs" />
+    <Compile Include="Cache\Affinity\Package-Info.cs" />
     <Compile Include="Cache\Affinity\Rendezvous\RendezvousAffinityFunction.cs" />
     <Compile Include="Cache\CacheAtomicUpdateTimeoutException.cs" />
     <Compile Include="Cache\CacheEntryProcessorException.cs" />
@@ -114,6 +116,7 @@
     <Compile Include="Common\IgniteFutureCancelledException.cs" />
     <Compile Include="Common\IgniteGuid.cs" />
     <Compile Include="Common\Package-Info.cs" />
+    <Compile Include="Impl\Cache\Affinity\AffinityFunctionBase.cs" />
     <Compile Include="Impl\Cache\Affinity\AffinityFunctionSerializer.cs" />
     <Compile Include="Impl\Cache\Affinity\PlatformAffinityFunction.cs" />
     <Compile Include="Impl\Cache\Event\JavaCacheEntryEventFilter.cs" />

http://git-wip-us.apache.org/repos/asf/ignite/blob/448571ba/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityFunctionBase.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityFunctionBase.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityFunctionBase.cs
deleted file mode 100644
index ce2e5e1..0000000
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityFunctionBase.cs
+++ /dev/null
@@ -1,139 +0,0 @@
-\ufeff/*
- * 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.
- */
-
-namespace Apache.Ignite.Core.Cache.Affinity
-{
-    using System;
-    using System.Collections.Generic;
-    using System.ComponentModel;
-    using Apache.Ignite.Core.Cluster;
-    using Apache.Ignite.Core.Common;
-
-    /// <summary>
-    /// Base class for predefined affinity functions.
-    /// </summary>
-    [Serializable]
-    public abstract class AffinityFunctionBase : IAffinityFunction
-    {
-        /// <summary> The default value for <see cref="Partitions"/> property. </summary>
-        public const int DefaultPartitions = 1024;
-
-        /** */
-        private int _partitions = DefaultPartitions;
-
-        /** */
-        private IAffinityFunction _baseFunction;
-
-
-        /// <summary>
-        /// Gets or sets the total number of partitions.
-        /// </summary>
-        [DefaultValue(DefaultPartitions)]
-        public virtual int Partitions
-        {
-            get { return _partitions; }
-            set { _partitions = value; }
-        }
-
-        /// <summary>
-        /// Gets partition number for a given key starting from 0. Partitioned caches
-        /// should make sure that keys are about evenly distributed across all partitions
-        /// from 0 to <see cref="Partitions" /> for best performance.
-        /// <para />
-        /// Note that for fully replicated caches it is possible to segment key sets among different
-        /// grid node groups. In that case each node group should return a unique partition
-        /// number. However, unlike partitioned cache, mappings of keys to nodes in
-        /// replicated caches are constant and a node cannot migrate from one partition
-        /// to another.
-        /// </summary>
-        /// <param name="key">Key to get partition for.</param>
-        /// <returns>
-        /// Partition number for a given key.
-        /// </returns>
-        public virtual int GetPartition(object key)
-        {
-            ThrowIfUninitialized();
-
-            return _baseFunction.GetPartition(key);
-        }
-
-        /// <summary>
-        /// Removes node from affinity. This method is called when it is safe to remove
-        /// disconnected node from affinity mapping.
-        /// </summary>
-        /// <param name="nodeId">The node identifier.</param>
-        public virtual void RemoveNode(Guid nodeId)
-        {
-            ThrowIfUninitialized();
-
-            _baseFunction.RemoveNode(nodeId);
-        }
-
-        /// <summary>
-        /// Gets affinity nodes for a partition. In case of replicated cache, all returned
-        /// nodes are updated in the same manner. In case of partitioned cache, the returned
-        /// list should contain only the primary and back up nodes with primary node being
-        /// always first.
-        /// <pare />
-        /// Note that partitioned affinity must obey the following contract: given that node
-        /// <code>N</code> is primary for some key <code>K</code>, if any other node(s) leave
-        /// grid and no node joins grid, node <code>N</code> will remain primary for key <code>K</code>.
-        /// </summary>
-        /// <param name="context">The affinity function context.</param>
-        /// <returns>
-        /// A collection of partitions, where each partition is a collection of nodes,
-        /// where first node is a primary node, and other nodes are backup nodes.
-        /// </returns>
-        public virtual IEnumerable<IEnumerable<IClusterNode>> AssignPartitions(AffinityFunctionContext context)
-        {
-            ThrowIfUninitialized();
-
-            return _baseFunction.AssignPartitions(context);
-        }
-
-        /// <summary>
-        /// Gets or sets a value indicating whether to exclude same-host-neighbors from being backups of each other.
-        /// </summary>
-        public virtual bool ExcludeNeighbors { get; set; }
-
-        /// <summary>
-        /// Initializes a new instance of the <see cref="AffinityFunctionBase"/> class.
-        /// </summary>
-        internal AffinityFunctionBase()
-        {
-            // No-op.
-        }
-
-        /// <summary>
-        /// Sets the base function.
-        /// </summary>
-        /// <param name="baseFunc">The base function.</param>
-        internal void SetBaseFunction(IAffinityFunction baseFunc)
-        {
-            _baseFunction = baseFunc;
-        }
-
-        /// <summary>
-        /// Gets the direct usage error.
-        /// </summary>
-        private void ThrowIfUninitialized()
-        {
-            if (_baseFunction == null)
-                throw new IgniteException(GetType() + " has not yet been initialized.");
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/448571ba/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/FairAffinityFunction.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/FairAffinityFunction.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/FairAffinityFunction.cs
index 4a3885f..f06937d 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/FairAffinityFunction.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/FairAffinityFunction.cs
@@ -18,6 +18,7 @@
 namespace Apache.Ignite.Core.Cache.Affinity.Fair
 {
     using System;
+    using Apache.Ignite.Core.Impl.Cache.Affinity;
 
     /// <summary>
     /// Fair affinity function which tries to ensure that all nodes get equal number of partitions with 

http://git-wip-us.apache.org/repos/asf/ignite/blob/448571ba/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/Package-Info.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/Package-Info.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/Package-Info.cs
new file mode 100644
index 0000000..3bcaa59
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/Package-Info.cs
@@ -0,0 +1,26 @@
+\ufeff/*
+* 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.
+*/
+
+#pragma warning disable 1587   // invalid XML comment
+
+/// <summary>
+/// Fair affinity functionality.
+/// </summary>
+namespace Apache.Ignite.Core.Cache.Affinity.Fair
+{
+    // No-op.
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/448571ba/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Package-Info.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Package-Info.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Package-Info.cs
new file mode 100644
index 0000000..dfbdf08
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Package-Info.cs
@@ -0,0 +1,26 @@
+\ufeff/*
+* 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.
+*/
+
+#pragma warning disable 1587   // invalid XML comment
+
+/// <summary>
+/// Cache affinity API.
+/// </summary>
+namespace Apache.Ignite.Core.Cache.Affinity
+{
+    // No-op.
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/448571ba/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/Package-Info.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/Package-Info.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/Package-Info.cs
new file mode 100644
index 0000000..d3f5ef0
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/Package-Info.cs
@@ -0,0 +1,26 @@
+\ufeff/*
+* 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.
+*/
+
+#pragma warning disable 1587   // invalid XML comment
+
+/// <summary>
+/// Rendezvous affinity functionality.
+/// </summary>
+namespace Apache.Ignite.Core.Cache.Affinity.Rendezvous
+{
+    // No-op.
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/448571ba/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/RendezvousAffinityFunction.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/RendezvousAffinityFunction.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/RendezvousAffinityFunction.cs
index 98ec364..928324c 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/RendezvousAffinityFunction.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/RendezvousAffinityFunction.cs
@@ -18,6 +18,7 @@
 namespace Apache.Ignite.Core.Cache.Affinity.Rendezvous
 {
     using System;
+    using Apache.Ignite.Core.Impl.Cache.Affinity;
 
     /// <summary>
     /// Affinity function for partitioned cache based on Highest Random Weight algorithm.

http://git-wip-us.apache.org/repos/asf/ignite/blob/448571ba/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/Affinity/AffinityFunctionBase.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/Affinity/AffinityFunctionBase.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/Affinity/AffinityFunctionBase.cs
new file mode 100644
index 0000000..8536e4c
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/Affinity/AffinityFunctionBase.cs
@@ -0,0 +1,140 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Cache.Affinity
+{
+    using System;
+    using System.Collections.Generic;
+    using System.ComponentModel;
+    using Apache.Ignite.Core.Cache.Affinity;
+    using Apache.Ignite.Core.Cluster;
+    using Apache.Ignite.Core.Common;
+
+    /// <summary>
+    /// Base class for predefined affinity functions.
+    /// </summary>
+    [Serializable]
+    public abstract class AffinityFunctionBase : IAffinityFunction
+    {
+        /// <summary> The default value for <see cref="Partitions"/> property. </summary>
+        public const int DefaultPartitions = 1024;
+
+        /** */
+        private int _partitions = DefaultPartitions;
+
+        /** */
+        private IAffinityFunction _baseFunction;
+
+
+        /// <summary>
+        /// Gets or sets the total number of partitions.
+        /// </summary>
+        [DefaultValue(DefaultPartitions)]
+        public virtual int Partitions
+        {
+            get { return _partitions; }
+            set { _partitions = value; }
+        }
+
+        /// <summary>
+        /// Gets partition number for a given key starting from 0. Partitioned caches
+        /// should make sure that keys are about evenly distributed across all partitions
+        /// from 0 to <see cref="Partitions" /> for best performance.
+        /// <para />
+        /// Note that for fully replicated caches it is possible to segment key sets among different
+        /// grid node groups. In that case each node group should return a unique partition
+        /// number. However, unlike partitioned cache, mappings of keys to nodes in
+        /// replicated caches are constant and a node cannot migrate from one partition
+        /// to another.
+        /// </summary>
+        /// <param name="key">Key to get partition for.</param>
+        /// <returns>
+        /// Partition number for a given key.
+        /// </returns>
+        public virtual int GetPartition(object key)
+        {
+            ThrowIfUninitialized();
+
+            return _baseFunction.GetPartition(key);
+        }
+
+        /// <summary>
+        /// Removes node from affinity. This method is called when it is safe to remove
+        /// disconnected node from affinity mapping.
+        /// </summary>
+        /// <param name="nodeId">The node identifier.</param>
+        public virtual void RemoveNode(Guid nodeId)
+        {
+            ThrowIfUninitialized();
+
+            _baseFunction.RemoveNode(nodeId);
+        }
+
+        /// <summary>
+        /// Gets affinity nodes for a partition. In case of replicated cache, all returned
+        /// nodes are updated in the same manner. In case of partitioned cache, the returned
+        /// list should contain only the primary and back up nodes with primary node being
+        /// always first.
+        /// <pare />
+        /// Note that partitioned affinity must obey the following contract: given that node
+        /// <code>N</code> is primary for some key <code>K</code>, if any other node(s) leave
+        /// grid and no node joins grid, node <code>N</code> will remain primary for key <code>K</code>.
+        /// </summary>
+        /// <param name="context">The affinity function context.</param>
+        /// <returns>
+        /// A collection of partitions, where each partition is a collection of nodes,
+        /// where first node is a primary node, and other nodes are backup nodes.
+        /// </returns>
+        public virtual IEnumerable<IEnumerable<IClusterNode>> AssignPartitions(AffinityFunctionContext context)
+        {
+            ThrowIfUninitialized();
+
+            return _baseFunction.AssignPartitions(context);
+        }
+
+        /// <summary>
+        /// Gets or sets a value indicating whether to exclude same-host-neighbors from being backups of each other.
+        /// </summary>
+        public virtual bool ExcludeNeighbors { get; set; }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="AffinityFunctionBase"/> class.
+        /// </summary>
+        internal AffinityFunctionBase()
+        {
+            // No-op.
+        }
+
+        /// <summary>
+        /// Sets the base function.
+        /// </summary>
+        /// <param name="baseFunc">The base function.</param>
+        internal void SetBaseFunction(IAffinityFunction baseFunc)
+        {
+            _baseFunction = baseFunc;
+        }
+
+        /// <summary>
+        /// Gets the direct usage error.
+        /// </summary>
+        private void ThrowIfUninitialized()
+        {
+            if (_baseFunction == null)
+                throw new IgniteException(GetType() + " has not yet been initialized.");
+        }
+    }
+}


[02/50] [abbrv] ignite git commit: ignite-3428 Fixed message recovery handling on reconnect

Posted by vo...@apache.org.
ignite-3428 Fixed message recovery handling on reconnect


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 89d722c25082fac7e2c7ba4af6938dc742eab99c
Parents: bebf3f0
Author: sboikov <sb...@gridgain.com>
Authored: Wed Jul 6 09:31:07 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Wed Jul 6 09:31:07 2016 +0300

----------------------------------------------------------------------
 .../util/nio/GridNioRecoveryDescriptor.java     |  19 ++-
 .../ignite/internal/util/nio/GridNioServer.java |  50 ++++--
 .../util/nio/GridSelectorNioSessionImpl.java    |   7 +
 .../communication/tcp/TcpCommunicationSpi.java  | 167 ++++++++++++-------
 ...gniteCacheMessageRecoveryIdleConnection.java | 154 +++++++++++++++++
 .../ignite/testsuites/IgniteCacheTestSuite.java |   2 +
 6 files changed, 324 insertions(+), 75 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/89d722c2/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioRecoveryDescriptor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioRecoveryDescriptor.java b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioRecoveryDescriptor.java
index 409bded..35480ac 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioRecoveryDescriptor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioRecoveryDescriptor.java
@@ -74,6 +74,9 @@ public class GridNioRecoveryDescriptor {
     /** Maximum size of unacknowledged messages queue. */
     private final int queueLimit;
 
+    /** Number of descriptor reservations (for info purposes). */
+    private int reserveCnt;
+
     /**
      * @param queueLimit Maximum size of unacknowledged messages queue.
      * @param node Node.
@@ -256,9 +259,12 @@ public class GridNioRecoveryDescriptor {
             while (!connected && reserved)
                 wait();
 
-            if (!connected)
+            if (!connected) {
                 reserved = true;
 
+                reserveCnt++;
+            }
+
             return !connected;
         }
     }
@@ -375,12 +381,23 @@ public class GridNioRecoveryDescriptor {
             else {
                 reserved = true;
 
+                reserveCnt++;
+
                 return true;
             }
         }
     }
 
     /**
+     * @return Number of descriptor reservations.
+     */
+    public int reserveCount() {
+        synchronized (this) {
+            return reserveCnt;
+        }
+    }
+
+    /**
      * @param futs Futures to complete.
      */
     private void completeOnNodeLeft(GridNioFuture<?>[] futs) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/89d722c2/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioServer.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioServer.java b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioServer.java
index 75cf776..ac55a14 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioServer.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioServer.java
@@ -1429,11 +1429,7 @@ public class GridNioServer<T> {
 
                                     sb.append("    Connection info [")
                                         .append("rmtAddr=").append(ses.remoteAddress())
-                                        .append(", locAddr=").append(ses.localAddress())
-                                        .append(", msgWriter=").append(writer != null ? writer.toString() : "null")
-                                        .append(", msgReader=").append(reader != null ? reader.toString() : "null")
-                                        .append(", bytesRcvd=").append(ses.bytesReceived())
-                                        .append(", bytesSent=").append(ses.bytesSent());
+                                        .append(", locAddr=").append(ses.localAddress());
 
                                     GridNioRecoveryDescriptor desc = ses.recoveryDescriptor();
 
@@ -1446,11 +1442,32 @@ public class GridNioServer<T> {
                                     else
                                         sb.append(", recoveryDesc=null");
 
+                                    sb.append(", bytesRcvd=").append(ses.bytesReceived())
+                                        .append(", bytesSent=").append(ses.bytesSent())
+                                        .append(", opQueueSize=").append(ses.writeQueueSize())
+                                        .append(", msgWriter=").append(writer != null ? writer.toString() : "null")
+                                        .append(", msgReader=").append(reader != null ? reader.toString() : "null");
+
+                                    int cnt = 0;
+
+                                    for (GridNioFuture<?> fut : ses.writeQueue()) {
+                                        if (cnt == 0)
+                                            sb.append(",\n opQueue=[").append(fut);
+                                        else
+                                            sb.append(',').append(fut);
+
+                                        if (++cnt == 5) {
+                                            sb.append(']');
+
+                                            break;
+                                        }
+                                    }
+
+
                                     sb.append("]").append(U.nl());
                                 }
 
-                                if (log.isInfoEnabled())
-                                    log.info(sb.toString());
+                                U.warn(log, sb.toString());
 
                                 // Complete the request just in case (none should wait on this future).
                                 req.onDone(true);
@@ -1721,13 +1738,6 @@ public class GridNioServer<T> {
                 if (e != null)
                     filterChain.onExceptionCaught(ses, e);
 
-                try {
-                    filterChain.onSessionClosed(ses);
-                }
-                catch (IgniteCheckedException e1) {
-                    filterChain.onExceptionCaught(ses, e1);
-                }
-
                 ses.removeMeta(BUF_META_KEY);
 
                 // Since ses is in closed state, no write requests will be added.
@@ -1755,6 +1765,13 @@ public class GridNioServer<T> {
                         fut.connectionClosed();
                 }
 
+                try {
+                    filterChain.onSessionClosed(ses);
+                }
+                catch (IgniteCheckedException e1) {
+                    filterChain.onExceptionCaught(ses, e1);
+                }
+
                 return true;
             }
 
@@ -1980,24 +1997,29 @@ public class GridNioServer<T> {
         private SocketChannel sockCh;
 
         /** Session to perform operation on. */
+        @GridToStringExclude
         private GridSelectorNioSessionImpl ses;
 
         /** Is it a close request or a write request. */
         private NioOperation op;
 
         /** Message. */
+        @GridToStringExclude
         private ByteBuffer msg;
 
         /** Direct message. */
         private Message commMsg;
 
         /** */
+        @GridToStringExclude
         private boolean accepted;
 
         /** */
+        @GridToStringExclude
         private Map<Integer, ?> meta;
 
         /** */
+        @GridToStringExclude
         private boolean skipRecovery;
 
         /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/89d722c2/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridSelectorNioSessionImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridSelectorNioSessionImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridSelectorNioSessionImpl.java
index deb7d2b..360b3d4 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridSelectorNioSessionImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridSelectorNioSessionImpl.java
@@ -264,6 +264,13 @@ class GridSelectorNioSessionImpl extends GridNioSessionImpl {
         return queueSize.get();
     }
 
+    /**
+     * @return Write requests.
+     */
+    Collection<GridNioFuture<?>> writeQueue() {
+        return queue;
+    }
+
     /** {@inheritDoc} */
     @Override public void recoveryDescriptor(GridNioRecoveryDescriptor recoveryDesc) {
         assert recoveryDesc != null;

http://git-wip-us.apache.org/repos/asf/ignite/blob/89d722c2/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java b/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java
index 0a18003..ed29b59 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java
@@ -353,30 +353,31 @@ public class TcpCommunicationSpi extends IgniteSpiAdapter
                 UUID id = ses.meta(NODE_ID_META);
 
                 if (id != null) {
-                    GridCommunicationClient rmv = clients.get(id);
+                    if (!stopping) {
+                        boolean reconnect = false;
 
-                    if (rmv instanceof GridTcpNioCommunicationClient &&
-                        ((GridTcpNioCommunicationClient)rmv).session() == ses &&
-                        clients.remove(id, rmv)) {
-                        rmv.forceClose();
+                        GridNioRecoveryDescriptor recoveryData = ses.recoveryDescriptor();
 
-                        if (!stopping) {
-                            GridNioRecoveryDescriptor recoveryData = ses.recoveryDescriptor();
+                        if (recoveryData != null) {
+                            if (recoveryData.nodeAlive(getSpiContext().node(id))) {
+                                if (!recoveryData.messagesFutures().isEmpty()) {
+                                    reconnect = true;
 
-                            if (recoveryData != null) {
-                                if (recoveryData.nodeAlive(getSpiContext().node(id))) {
-                                    if (!recoveryData.messagesFutures().isEmpty()) {
-                                        if (log.isDebugEnabled())
-                                            log.debug("Session was closed but there are unacknowledged messages, " +
-                                                "will try to reconnect [rmtNode=" + recoveryData.node().id() + ']');
-
-                                        commWorker.addReconnectRequest(recoveryData);
-                                    }
+                                    if (log.isDebugEnabled())
+                                        log.debug("Session was closed but there are unacknowledged messages, " +
+                                            "will try to reconnect [rmtNode=" + recoveryData.node().id() + ']');
                                 }
-                                else
-                                    recoveryData.onNodeLeft();
                             }
+                            else
+                                recoveryData.onNodeLeft();
                         }
+
+                        DisconnectedSessionInfo disconnectData = new DisconnectedSessionInfo(id,
+                            ses,
+                            recoveryData,
+                            reconnect);
+
+                        commWorker.addProcessDisconnectRequest(disconnectData);
                     }
 
                     CommunicationListener<Message> lsnr0 = lsnr;
@@ -1383,7 +1384,7 @@ public class TcpCommunicationSpi extends IgniteSpiAdapter
     @Override public void dumpStats() {
         IgniteLogger log = this.log;
 
-        if (log != null && log.isInfoEnabled()) {
+        if (log != null) {
             StringBuilder sb = new StringBuilder("Communication SPI recovery descriptors: ").append(U.nl());
 
             for (Map.Entry<ClientKey, GridNioRecoveryDescriptor> entry : recoveryDescs.entrySet()) {
@@ -1393,11 +1394,13 @@ public class TcpCommunicationSpi extends IgniteSpiAdapter
                     .append(", msgsSent=").append(desc.sent())
                     .append(", msgsAckedByRmt=").append(desc.acked())
                     .append(", msgsRcvd=").append(desc.received())
+                    .append(", lastAcked=").append(desc.lastAcknowledged())
+                    .append(", reserveCnt=").append(desc.reserveCount())
                     .append(", descIdHash=").append(System.identityHashCode(desc))
                     .append(']').append(U.nl());
             }
 
-            log.info(sb.toString());
+            U.warn(log, sb.toString());
         }
 
         GridNioServer<Message> nioSrvr = this.nioSrvr;
@@ -3030,14 +3033,14 @@ public class TcpCommunicationSpi extends IgniteSpiAdapter
             endpoint.close();
         }
 
-        /** @{@inheritDoc} */
+        /** {@inheritDoc} */
         @Override protected void cleanup() {
             super.cleanup();
 
             endpoint.close();
         }
 
-        /** @{@inheritDoc} */
+        /** {@inheritDoc} */
         @Override public String toString() {
             return S.toString(ShmemWorker.class, this);
         }
@@ -3048,7 +3051,7 @@ public class TcpCommunicationSpi extends IgniteSpiAdapter
      */
     private class CommunicationWorker extends IgniteSpiThread {
         /** */
-        private final BlockingQueue<GridNioRecoveryDescriptor> q = new LinkedBlockingQueue<>();
+        private final BlockingQueue<DisconnectedSessionInfo> q = new LinkedBlockingQueue<>();
 
         /**
          * @param gridName Grid name.
@@ -3063,10 +3066,10 @@ public class TcpCommunicationSpi extends IgniteSpiAdapter
                 log.debug("Tcp communication worker has been started.");
 
             while (!isInterrupted()) {
-                GridNioRecoveryDescriptor recoveryDesc = q.poll(idleConnTimeout, TimeUnit.MILLISECONDS);
+                DisconnectedSessionInfo disconnectData = q.poll(idleConnTimeout, TimeUnit.MILLISECONDS);
 
-                if (recoveryDesc != null)
-                    processRecovery(recoveryDesc);
+                if (disconnectData != null)
+                    processDisconnect(disconnectData);
                 else
                     processIdle();
             }
@@ -3171,56 +3174,62 @@ public class TcpCommunicationSpi extends IgniteSpiAdapter
         }
 
         /**
-         * @param recoveryDesc Recovery descriptor.
+         * @param sesInfo Disconnected session information.
          */
-        private void processRecovery(GridNioRecoveryDescriptor recoveryDesc) {
-            ClusterNode node = recoveryDesc.node();
+        private void processDisconnect(DisconnectedSessionInfo sesInfo) {
+            GridCommunicationClient client = clients.get(sesInfo.nodeId);
 
-            try {
-                if (clients.containsKey(node.id()) ||
-                    !recoveryDesc.nodeAlive(getSpiContext().node(node.id())) ||
-                    !getSpiContext().pingNode(node.id()))
-                    return;
-            }
-            catch (IgniteClientDisconnectedException e) {
-                if (log.isDebugEnabled())
-                    log.debug("Failed to ping node, client disconnected.");
+            if (client instanceof GridTcpNioCommunicationClient &&
+                ((GridTcpNioCommunicationClient) client).session() == sesInfo.ses)
+                    clients.remove(sesInfo.nodeId, client);
 
-                return;
-            }
+            if (sesInfo.reconnect) {
+                GridNioRecoveryDescriptor recoveryDesc = sesInfo.recoveryDesc;
 
-            try {
-                if (log.isDebugEnabled())
-                    log.debug("Recovery reconnect [rmtNode=" + recoveryDesc.node().id() + ']');
+                ClusterNode node = recoveryDesc.node();
 
-                GridCommunicationClient client = reserveClient(node);
+                if (!recoveryDesc.nodeAlive(getSpiContext().node(node.id())))
+                    return;
 
-                client.release();
-            }
-            catch (IgniteCheckedException | IgniteException e) {
-                if (recoveryDesc.nodeAlive(getSpiContext().node(node.id()))) {
+                try {
                     if (log.isDebugEnabled())
-                        log.debug("Recovery reconnect failed, will retry " +
-                            "[rmtNode=" + recoveryDesc.node().id() + ", err=" + e + ']');
+                        log.debug("Recovery reconnect [rmtNode=" + recoveryDesc.node().id() + ']');
+
+                    client = reserveClient(node);
 
-                    addReconnectRequest(recoveryDesc);
+                    client.release();
                 }
-                else {
-                    if (log.isDebugEnabled())
-                        log.debug("Recovery reconnect failed, " +
-                            "node left [rmtNode=" + recoveryDesc.node().id() + ", err=" + e + ']');
+                catch (IgniteCheckedException | IgniteException e) {
+                    try {
+                        if (recoveryDesc.nodeAlive(getSpiContext().node(node.id())) && getSpiContext().pingNode(node.id())) {
+                            if (log.isDebugEnabled())
+                                log.debug("Recovery reconnect failed, will retry " +
+                                    "[rmtNode=" + recoveryDesc.node().id() + ", err=" + e + ']');
+
+                            addProcessDisconnectRequest(sesInfo);
+                        }
+                        else {
+                            if (log.isDebugEnabled())
+                                log.debug("Recovery reconnect failed, " +
+                                    "node left [rmtNode=" + recoveryDesc.node().id() + ", err=" + e + ']');
 
-                    onException("Recovery reconnect failed, node left [rmtNode=" + recoveryDesc.node().id() + "]",
-                        e);
+                            onException("Recovery reconnect failed, node left [rmtNode=" + recoveryDesc.node().id() + "]",
+                                e);
+                        }
+                    }
+                    catch (IgniteClientDisconnectedException e0) {
+                        if (log.isDebugEnabled())
+                            log.debug("Failed to ping node, client disconnected.");
+                    }
                 }
             }
         }
 
         /**
-         * @param recoverySnd Recovery send data.
+         * @param sesInfo Disconnected session information.
          */
-        void addReconnectRequest(GridNioRecoveryDescriptor recoverySnd) {
-            boolean add = q.add(recoverySnd);
+        void addProcessDisconnectRequest(DisconnectedSessionInfo sesInfo) {
+            boolean add = q.add(sesInfo);
 
             assert add;
         }
@@ -3731,4 +3740,42 @@ public class TcpCommunicationSpi extends IgniteSpiAdapter
             lock.readUnlock();
         }
     }
+
+    /**
+     *
+     */
+    private static class DisconnectedSessionInfo {
+        /** */
+        private final UUID nodeId;
+
+        /** */
+        private final GridNioSession ses;
+
+        /** */
+        private final GridNioRecoveryDescriptor recoveryDesc;
+
+        /** */
+        private final boolean reconnect;
+
+        /**
+         * @param nodeId Node ID.
+         * @param ses Session.
+         * @param recoveryDesc Recovery descriptor.
+         * @param reconnect Reconnect flag.
+         */
+        public DisconnectedSessionInfo(UUID nodeId,
+            GridNioSession ses,
+            @Nullable GridNioRecoveryDescriptor recoveryDesc,
+            boolean reconnect) {
+            this.nodeId = nodeId;
+            this.ses = ses;
+            this.recoveryDesc = recoveryDesc;
+            this.reconnect = reconnect;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(DisconnectedSessionInfo.class, this);
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/89d722c2/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheMessageRecoveryIdleConnection.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheMessageRecoveryIdleConnection.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheMessageRecoveryIdleConnection.java
new file mode 100644
index 0000000..618fe2a
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/IgniteCacheMessageRecoveryIdleConnection.java
@@ -0,0 +1,154 @@
+/*
+ * 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.distributed;
+
+import java.util.List;
+import java.util.concurrent.ThreadLocalRandom;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.cache.CacheAtomicityMode;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgniteKernal;
+import org.apache.ignite.internal.IgnitionEx;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.lang.IgniteFuture;
+import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi;
+import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
+import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
+import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
+import static org.apache.ignite.cache.CacheMode.REPLICATED;
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
+
+/**
+ *
+ */
+public class IgniteCacheMessageRecoveryIdleConnection extends GridCommonAbstractTest {
+    /** */
+    private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
+
+    /** */
+    private static final int NODES = 3;
+
+    /** */
+    private static final long IDLE_TIMEOUT = 50;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(IP_FINDER);
+
+        TcpCommunicationSpi commSpi = new TcpCommunicationSpi();
+
+        commSpi.setIdleConnectionTimeout(IDLE_TIMEOUT);
+        commSpi.setSharedMemoryPort(-1);
+
+        cfg.setCommunicationSpi(commSpi);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected long getTestTimeout() {
+        return 2 * 60_000;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        super.beforeTestsStarted();
+
+        startGridsMultiThreaded(NODES);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        super.afterTestsStopped();
+
+        stopAllGrids();
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCacheOperationsIdleConnectionCloseTx() throws Exception {
+        cacheOperationsIdleConnectionClose(TRANSACTIONAL);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testCacheOperationsIdleConnectionCloseAtomic() throws Exception {
+        cacheOperationsIdleConnectionClose(ATOMIC);
+    }
+
+    /**
+     * @param atomicityMode Cache atomicity mode.
+     * @throws Exception If failed.
+     */
+    private void cacheOperationsIdleConnectionClose(CacheAtomicityMode atomicityMode) throws Exception {
+        CacheConfiguration<Object, Object> ccfg = new CacheConfiguration<>();
+
+        ccfg.setAtomicityMode(atomicityMode);
+        ccfg.setCacheMode(REPLICATED);
+        ccfg.setWriteSynchronizationMode(FULL_SYNC);
+
+        IgniteCache<Object, Object> cache = ignite(0).createCache(ccfg).withAsync();
+
+        try {
+            ThreadLocalRandom rnd = ThreadLocalRandom.current();
+
+            int iter = 0;
+
+            long stopTime = System.currentTimeMillis() + 90_000;
+
+            while (System.currentTimeMillis() < stopTime) {
+                if (iter++ % 10 == 0)
+                    log.info("Iteration: " + iter);
+
+                cache.put(iter, 1);
+
+                IgniteFuture<?> fut = cache.future();
+
+                try {
+                    fut.get(10_000);
+                }
+                catch (IgniteException e) {
+                    List<Ignite> nodes = IgnitionEx.allGridsx();
+
+                    for (Ignite node : nodes)
+                        ((IgniteKernal)node).dumpDebugInfo();
+
+                    U.dumpThreads(log);
+
+                    throw e;
+                }
+
+                U.sleep(rnd.nextLong(IDLE_TIMEOUT - 10, IDLE_TIMEOUT + 10));
+            }
+        }
+        finally {
+            ignite(0).destroyCache(ccfg.getName());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/89d722c2/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
index 003b12c..33aae9a 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
@@ -123,6 +123,7 @@ import org.apache.ignite.internal.processors.cache.distributed.CacheAtomicNearUp
 import org.apache.ignite.internal.processors.cache.distributed.CacheTxNearUpdateTopologyChangeTest;
 import org.apache.ignite.internal.processors.cache.distributed.GridCacheEntrySetIterationPreloadingSelfTest;
 import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheAtomicMessageRecoveryTest;
+import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheMessageRecoveryIdleConnection;
 import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheSystemTransactionsSelfTest;
 import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheTxMessageRecoveryTest;
 import org.apache.ignite.internal.processors.cache.distributed.IgniteCrossCacheTxStoreSelfTest;
@@ -272,6 +273,7 @@ public class IgniteCacheTestSuite extends TestSuite {
         suite.addTestSuite(GridCacheMixedPartitionExchangeSelfTest.class);
         suite.addTestSuite(IgniteCacheAtomicMessageRecoveryTest.class);
         suite.addTestSuite(IgniteCacheTxMessageRecoveryTest.class);
+        suite.addTestSuite(IgniteCacheMessageRecoveryIdleConnection.class);
         GridTestUtils.addTestIfNeeded(suite, GridCacheOffHeapTieredEvictionAtomicSelfTest.class, ignoredTests);
         GridTestUtils.addTestIfNeeded(suite, GridCacheOffHeapTieredEvictionSelfTest.class, ignoredTests);
         GridTestUtils.addTestIfNeeded(suite, GridCacheOffHeapTieredAtomicSelfTest.class, ignoredTests);


[20/50] [abbrv] ignite git commit: IGNITE-1849 GridCacheAdapter - made size tasks @GridInternal

Posted by vo...@apache.org.
IGNITE-1849 GridCacheAdapter - made size tasks @GridInternal


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

Branch: refs/heads/ignite-1.5.31-1
Commit: a33dd1c5d680c6a3d9dd266f135f139cacd7772f
Parents: 762c43d
Author: Alexander Paschenko <al...@gmail.com>
Authored: Wed Jul 13 05:01:02 2016 +0300
Committer: Alexander Paschenko <al...@gmail.com>
Committed: Wed Jul 13 05:01:02 2016 +0300

----------------------------------------------------------------------
 .../processors/cache/GridCacheAdapter.java      |  2 +
 .../IgniteCacheInternalEventsIgnoreTest.java    | 53 ++++++++++++++++++++
 .../testsuites/IgniteCacheTestSuite5.java       |  2 +
 3 files changed, 57 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/a33dd1c5/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
index 55bd81d..05fd7d8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheAdapter.java
@@ -6656,6 +6656,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
     /**
      * Size task.
      */
+    @GridInternal
     private static class SizeTask extends ComputeTaskAdapter<Object, Integer> {
         /** */
         private static final long serialVersionUID = 0L;
@@ -6721,6 +6722,7 @@ public abstract class GridCacheAdapter<K, V> implements IgniteInternalCache<K, V
     /**
      * Size task.
      */
+    @GridInternal
     private static class SizeLongTask extends ComputeTaskAdapter<Object, Long> {
         /** */
         private static final long serialVersionUID = 0L;

http://git-wip-us.apache.org/repos/asf/ignite/blob/a33dd1c5/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheInternalEventsIgnoreTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheInternalEventsIgnoreTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheInternalEventsIgnoreTest.java
new file mode 100644
index 0000000..e87206d
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheInternalEventsIgnoreTest.java
@@ -0,0 +1,53 @@
+/*
+ * 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;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.cache.CachePeekMode;
+import org.apache.ignite.events.Event;
+import org.apache.ignite.events.EventType;
+import org.apache.ignite.lang.IgnitePredicate;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+/** */
+public class IgniteCacheInternalEventsIgnoreTest extends GridCommonAbstractTest {
+    /** */
+    private static final AtomicBoolean evtFlag = new AtomicBoolean();
+
+    /** */
+    public void testInternalEventsIgnore() throws Exception {
+        Ignite ignite = startGrid(1);
+        ignite.events().localListen(new EvtLsnr(), EventType.EVT_TASK_STARTED, EventType.EVT_TASK_REDUCED,
+            EventType.EVT_TASK_FINISHED);
+        IgniteCache cache = ignite.createCache(defaultCacheConfiguration().setName("myTestCache"));
+        cache.size(CachePeekMode.ALL);
+        cache.sizeLong(CachePeekMode.ALL);
+        assertFalse(evtFlag.get());
+    }
+
+    /** */
+    private static final class EvtLsnr implements IgnitePredicate<Event> {
+        /** {@inheritDoc} */
+        @Override public boolean apply(Event e) {
+            evtFlag.set(true);
+            return true;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/a33dd1c5/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite5.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite5.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite5.java
index 98a3c44..af54f91 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite5.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite5.java
@@ -21,6 +21,7 @@ import junit.framework.TestSuite;
 import org.apache.ignite.internal.processors.cache.CacheNearReaderUpdateTest;
 import org.apache.ignite.internal.processors.cache.CacheSerializableTransactionsTest;
 import org.apache.ignite.internal.processors.cache.EntryVersionConsistencyReadThroughTest;
+import org.apache.ignite.internal.processors.cache.IgniteCacheInternalEventsIgnoreTest;
 import org.apache.ignite.internal.processors.cache.IgniteCachePutStackOverflowSelfTest;
 import org.apache.ignite.internal.processors.cache.IgniteCacheStoreCollectionTest;
 import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheTxIteratorSelfTest;
@@ -44,6 +45,7 @@ public class IgniteCacheTestSuite5 extends TestSuite {
         suite.addTestSuite(IgniteCachePutStackOverflowSelfTest.class);
         suite.addTestSuite(EntryVersionConsistencyReadThroughTest.class);
         suite.addTestSuite(IgniteCacheTxIteratorSelfTest.class);
+        suite.addTestSuite(IgniteCacheInternalEventsIgnoreTest.class);
 
         return suite;
     }


[15/50] [abbrv] ignite git commit: ignite-1088 Implemented store for multi jvm tests (cherry picked from commit f91b699)

Posted by vo...@apache.org.
ignite-1088 Implemented store for multi jvm tests
(cherry picked from commit f91b699)


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 5b49dadd3741ee7d4ec92eb97919b15bcbd33482
Parents: f045558
Author: sboikov <sb...@gridgain.com>
Authored: Fri Jul 1 12:16:56 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Thu Jul 7 12:38:15 2016 +0300

----------------------------------------------------------------------
 .../cache/GridCacheAbstractMetricsSelfTest.java |   2 +-
 .../GridCacheInterceptorAbstractSelfTest.java   |   2 +-
 .../processors/cache/H2CacheStoreStrategy.java  | 468 +++++++++++++++++++
 .../processors/cache/MapCacheStoreStrategy.java | 145 ++++++
 .../cache/TestCacheStoreStrategy.java           |  96 ++++
 ...edOffHeapTieredMultiNodeFullApiSelfTest.java |   2 +-
 .../cache/IgniteCacheQueryIndexSelfTest.java    |   2 +-
 7 files changed, 713 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/5b49dadd/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractMetricsSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractMetricsSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractMetricsSelfTest.java
index 4c04df0..113a3b2 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractMetricsSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheAbstractMetricsSelfTest.java
@@ -906,7 +906,7 @@ public abstract class GridCacheAbstractMetricsSelfTest extends GridCacheAbstract
         }
 
         // Avoid reloading from store.
-        map.remove(key);
+        storeStgy.removeFromStore(key);
 
         assertTrue(GridTestUtils.waitForCondition(new GridAbsPredicateX() {
             @SuppressWarnings("unchecked")

http://git-wip-us.apache.org/repos/asf/ignite/blob/5b49dadd/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheInterceptorAbstractSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheInterceptorAbstractSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheInterceptorAbstractSelfTest.java
index f50a3e0..68bfb6f 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheInterceptorAbstractSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheInterceptorAbstractSelfTest.java
@@ -1444,7 +1444,7 @@ public abstract class GridCacheInterceptorAbstractSelfTest extends GridCacheAbst
         interceptor.disabled = true;
 
         if (storeEnabled())
-            assertEquals("Unexpected store value", expVal, map.get(key));
+            assertEquals("Unexpected store value", expVal, storeStgy.getFromStore(key));
 
         try {
             for (int i = 0; i < gridCount(); i++)

http://git-wip-us.apache.org/repos/asf/ignite/blob/5b49dadd/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/H2CacheStoreStrategy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/H2CacheStoreStrategy.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/H2CacheStoreStrategy.java
new file mode 100644
index 0000000..ccb2994
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/H2CacheStoreStrategy.java
@@ -0,0 +1,468 @@
+/*
+ * 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;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.StringReader;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Map;
+import javax.cache.Cache;
+import javax.cache.configuration.Factory;
+import javax.cache.integration.CacheLoaderException;
+import javax.cache.integration.CacheWriterException;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.cache.store.CacheStore;
+import org.apache.ignite.cache.store.CacheStoreAdapter;
+import org.apache.ignite.cache.store.CacheStoreSession;
+import org.apache.ignite.cache.store.CacheStoreSessionListener;
+import org.apache.ignite.cache.store.jdbc.CacheJdbcStoreSessionListener;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.lang.IgniteBiInClosure;
+import org.apache.ignite.resources.CacheStoreSessionResource;
+import org.h2.jdbcx.JdbcConnectionPool;
+import org.h2.tools.RunScript;
+import org.h2.tools.Server;
+
+/**
+ * {@link TestCacheStoreStrategy} backed by H2 in-memory database.
+ */
+public class H2CacheStoreStrategy implements TestCacheStoreStrategy {
+    /** Pool to get {@link Connection}s from. */
+    private final JdbcConnectionPool dataSrc;
+
+    /** Script that creates CACHE table. */
+    private static final String CREATE_CACHE_TABLE =
+        "create table if not exists CACHE(k binary not null, v binary not null, PRIMARY KEY(k));";
+
+    /** Script that creates STATS table. */
+    private static final String CREATE_STATS_TABLES =
+        "create table if not exists READS(id bigint auto_increment);\n" +
+        "create table if not exists WRITES(id bigint auto_increment);\n" +
+        "create table if not exists REMOVES(id bigint auto_increment);";
+
+    /** Script that populates STATS table */
+    private static final String POPULATE_STATS_TABLE =
+        "delete from READS;\n" +
+        "delete from WRITES;\n" +
+        "delete from REMOVES;";
+
+
+    /**
+     * @throws IgniteCheckedException If failed.
+     */
+    public H2CacheStoreStrategy() throws IgniteCheckedException {
+        try {
+            Server.createTcpServer().start();
+            dataSrc = H2CacheStoreSessionListenerFactory.createDataSource();
+
+            try (Connection conn = connection()) {
+                RunScript.execute(conn, new StringReader(CREATE_CACHE_TABLE));
+                RunScript.execute(conn, new StringReader(CREATE_STATS_TABLES));
+                RunScript.execute(conn, new StringReader(POPULATE_STATS_TABLE));
+            }
+        }
+        catch (SQLException e) {
+            throw new IgniteCheckedException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getReads() {
+        return queryStats("reads");
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getWrites() {
+        return queryStats("writes");
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getRemoves() {
+        return queryStats("removes");
+    }
+
+    /**
+     * @param tbl Table name.
+     * @return Update statistics.
+     */
+    private int queryStats(String tbl) {
+        return querySingleInt("select count(*) from " + tbl, "Failed to query store stats [table=" + tbl + "]");
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getStoreSize() {
+        return querySingleInt("select count(*) from CACHE;", "Failed to query number of rows from CACHE table");
+    }
+
+    /** {@inheritDoc} */
+    @Override public void resetStore() {
+        try (Connection conn = connection()) {
+            RunScript.execute(conn, new StringReader("delete from CACHE;"));
+            RunScript.execute(conn, new StringReader(POPULATE_STATS_TABLE));
+        }
+        catch (SQLException e) {
+            throw new IgniteException(e);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void putToStore(Object key, Object val) {
+        Connection conn = null;
+        try {
+            conn = connection();
+            H2CacheStore.putToDb(conn, key, val);
+        }
+        catch (SQLException e) {
+            throw new IgniteException(e);
+        }
+        finally {
+            U.closeQuiet(conn);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void putAllToStore(Map<?, ?> data) {
+        Connection conn = null;
+        PreparedStatement stmt = null;
+        try {
+            conn = connection();
+            stmt = conn.prepareStatement(H2CacheStore.MERGE);
+            for (Map.Entry<?, ?> e : data.entrySet()) {
+                stmt.setBinaryStream(1, new ByteArrayInputStream(H2CacheStore.serialize(e.getKey())));
+                stmt.setBinaryStream(2, new ByteArrayInputStream(H2CacheStore.serialize(e.getValue())));
+                stmt.addBatch();
+            }
+            stmt.executeBatch();
+        }
+        catch (SQLException e) {
+            throw new IgniteException(e);
+        }
+        finally {
+            U.closeQuiet(stmt);
+            U.closeQuiet(conn);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object getFromStore(Object key) {
+        Connection conn = null;
+        try {
+            conn = connection();
+            return H2CacheStore.getFromDb(conn, key);
+        }
+        catch (SQLException e) {
+            throw new IgniteException(e);
+        }
+        finally {
+            U.closeQuiet(conn);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void removeFromStore(Object key) {
+        Connection conn = null;
+        try {
+            conn = connection();
+            H2CacheStore.removeFromDb(conn, key);
+        }
+        catch (SQLException e) {
+            throw new IgniteException(e);
+        }
+        finally {
+            U.closeQuiet(conn);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isInStore(Object key) {
+        return getFromStore(key) != null;
+    }
+
+    /**
+     * @return New {@link Connection} from {@link #dataSrc}
+     * @throws SQLException if failed
+     */
+    private Connection connection() throws SQLException {
+        return dataSrc.getConnection();
+    }
+
+    /**
+     * Retrieves single int value from {@link ResultSet} returned by given query.
+     *
+     * @param qry Query string (fully populated, with params).
+     * @param errorMsg Message for {@link IgniteException} to bear in case of failure.
+     * @return Requested value
+     */
+    private int querySingleInt(String qry, String errorMsg) {
+        Connection conn = null;
+        PreparedStatement stmt = null;
+        ResultSet rs = null;
+        try {
+            conn = connection();
+            stmt = conn.prepareStatement(qry);
+            rs = stmt.executeQuery();
+            if (rs.next())
+                return rs.getInt(1);
+            else
+                throw new IgniteException(errorMsg);
+        }
+        catch (SQLException e) {
+            throw new IgniteException(e);
+        }
+        finally {
+            U.closeQuiet(rs);
+            U.closeQuiet(stmt);
+            U.closeQuiet(conn);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void updateCacheConfiguration(CacheConfiguration<Object, Object> cfg) {
+        cfg.setCacheStoreSessionListenerFactories(new H2CacheStoreSessionListenerFactory());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Factory<? extends CacheStore<Object, Object>> getStoreFactory() {
+        return new H2StoreFactory();
+    }
+
+    /** Serializable H2 backed cache store factory. */
+    public static class H2StoreFactory implements Factory<CacheStore<Object, Object>> {
+        /** {@inheritDoc} */
+        @Override public CacheStore<Object, Object> create() {
+            return new H2CacheStore();
+        }
+    }
+
+    /** Serializable {@link Factory} producing H2 backed {@link CacheStoreSessionListener}s. */
+    public static class H2CacheStoreSessionListenerFactory implements Factory<CacheStoreSessionListener> {
+        /**
+         * @return Connection pool
+         */
+        static JdbcConnectionPool createDataSource() {
+            JdbcConnectionPool pool = JdbcConnectionPool.create("jdbc:h2:tcp://localhost/mem:TestDb;LOCK_MODE=0", "sa", "");
+            pool.setMaxConnections(100);
+            return pool;
+        }
+
+        /** {@inheritDoc} */
+        @Override public CacheStoreSessionListener create() {
+            CacheJdbcStoreSessionListener lsnr = new CacheJdbcStoreSessionListener();
+            lsnr.setDataSource(createDataSource());
+            return lsnr;
+        }
+    }
+
+    /** H2 backed {@link CacheStoreAdapter} implementations */
+    public static class H2CacheStore extends CacheStoreAdapter<Object, Object> {
+        /** Store session */
+        @CacheStoreSessionResource
+        private CacheStoreSession ses;
+
+        /** Template for an insert statement */
+        private static final String MERGE = "merge into CACHE(k, v) values(?, ?);";
+
+        /** {@inheritDoc} */
+        @Override public void loadCache(IgniteBiInClosure<Object, Object> clo, Object... args) {
+            Connection conn = ses.attachment();
+            assert conn != null;
+
+            Statement stmt = null;
+            ResultSet rs = null;
+            try {
+                stmt = conn.createStatement();
+                rs = stmt.executeQuery("select * from CACHE");
+                while (rs.next())
+                    clo.apply(deserialize(rs.getBytes(1)), deserialize(rs.getBytes(2)));
+            }
+            catch (SQLException e) {
+                throw new IgniteException(e);
+            }
+            finally {
+                U.closeQuiet(rs);
+                U.closeQuiet(stmt);
+            }
+        }
+
+        /** {@inheritDoc} */
+        @Override public Object load(Object key) throws CacheLoaderException {
+            try {
+                Connection conn = ses.attachment();
+                Object res = getFromDb(conn, key);
+                updateStats("reads");
+                return res;
+            }
+            catch (SQLException e) {
+                throw new CacheLoaderException("Failed to load object [key=" + key + ']', e);
+            }
+        }
+
+        /** {@inheritDoc} */
+        @Override public void write(Cache.Entry<?, ?> entry) throws CacheWriterException {
+            try {
+                Connection conn = ses.attachment();
+                putToDb(conn, entry.getKey(), entry.getValue());
+                updateStats("writes");
+            }
+            catch (SQLException e) {
+                throw new CacheWriterException("Failed to write object [key=" + entry.getKey() + ", " +
+                    "val=" + entry.getValue() + ']', e);
+            }
+        }
+
+        /** {@inheritDoc} */
+        @Override public void delete(Object key) throws CacheWriterException {
+            try {
+                Connection conn = ses.attachment();
+                removeFromDb(conn, key);
+                updateStats("removes");
+            }
+            catch (SQLException e) {
+                throw new CacheWriterException("Failed to delete object [key=" + key + ']', e);
+            }
+        }
+
+        /**
+         * Selects from H2 and deserialize from bytes the value pointed by key.
+         *
+         * @param conn {@link Connection} to use.
+         * @param key Key to look for.
+         * @return Stored object or null if the key is missing from DB.
+         * @throws SQLException If failed.
+         */
+        static Object getFromDb(Connection conn, Object key) throws SQLException {
+            PreparedStatement stmt = null;
+            ResultSet rs = null;
+            try {
+                stmt = conn.prepareStatement("select v from CACHE where k = ?");
+                stmt.setBinaryStream(1, new ByteArrayInputStream(H2CacheStore.serialize(key)));
+                rs = stmt.executeQuery();
+                return rs.next() ? H2CacheStore.deserialize(rs.getBytes(1)) : null;
+            }
+            finally {
+                U.closeQuiet(rs);
+                U.closeQuiet(stmt);
+            }
+        }
+
+        /**
+         * Puts key-value pair to H2.
+         *
+         * @param conn {@link Connection} to use.
+         * @param key Key.
+         * @param val Value.
+         * @throws SQLException If failed.
+         */
+        static void putToDb(Connection conn, Object key, Object val) throws SQLException {
+            PreparedStatement stmt = null;
+            try {
+                stmt = conn.prepareStatement(H2CacheStore.MERGE);
+                stmt.setBinaryStream(1, new ByteArrayInputStream(H2CacheStore.serialize(key)));
+                stmt.setBinaryStream(2, new ByteArrayInputStream(H2CacheStore.serialize(val)));
+                stmt.executeUpdate();
+            }
+            finally {
+                U.closeQuiet(stmt);
+            }
+        }
+
+        /**
+         * Removes given key and its value from H2.
+         *
+         * @param conn {@link Connection} to invoke query upon.
+         * @param key Key to remove.
+         * @throws SQLException if failed.
+         */
+        static void removeFromDb(Connection conn, Object key) throws SQLException {
+            PreparedStatement stmt = null;
+            try {
+                stmt = conn.prepareStatement("delete from CACHE where k = ?");
+                stmt.setBinaryStream(1, new ByteArrayInputStream(H2CacheStore.serialize(key)));
+                stmt.executeUpdate();
+            }
+            finally {
+                U.closeQuiet(stmt);
+            }
+        }
+
+        /**
+         * Increments stored stats for given operation.
+         *
+         * @param tblName Table name
+         */
+        private void updateStats(String tblName) {
+            Connection conn = ses.attachment();
+            assert conn != null;
+            Statement stmt = null;
+            try {
+                stmt = conn.createStatement();
+                stmt.executeUpdate("insert into " + tblName + " default values");
+            }
+            catch (SQLException e) {
+                throw new IgniteException("Failed to update H2 store usage stats", e);
+            }
+            finally {
+                U.closeQuiet(stmt);
+            }
+        }
+
+        /**
+         * Turns given arbitrary object to byte array.
+         *
+         * @param obj Object to serialize
+         * @return Bytes representation of given object.
+         */
+        static byte[] serialize(Object obj) {
+            try (ByteArrayOutputStream b = new ByteArrayOutputStream()) {
+                try (ObjectOutputStream o = new ObjectOutputStream(b)) {
+                    o.writeObject(obj);
+                }
+                return b.toByteArray();
+            }
+            catch (Exception e) {
+                throw new IgniteException("Failed to serialize object to byte array [obj=" + obj, e);
+            }
+        }
+
+        /**
+         * Deserializes an object from its byte array representation.
+         *
+         * @param bytes Byte array representation of the object.
+         * @return Deserialized object.
+         */
+        public static Object deserialize(byte[] bytes) {
+            try (ByteArrayInputStream b = new ByteArrayInputStream(bytes)) {
+                try (ObjectInputStream o = new ObjectInputStream(b)) {
+                    return o.readObject();
+                }
+            }
+            catch (Exception e) {
+                throw new IgniteException("Failed to deserialize object from byte array", e);
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/5b49dadd/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/MapCacheStoreStrategy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/MapCacheStoreStrategy.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/MapCacheStoreStrategy.java
new file mode 100644
index 0000000..800d781
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/MapCacheStoreStrategy.java
@@ -0,0 +1,145 @@
+/*
+ * 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;
+
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+import javax.cache.Cache;
+import javax.cache.configuration.Factory;
+import javax.cache.configuration.FactoryBuilder;
+import org.apache.ignite.cache.store.CacheStore;
+import org.apache.ignite.cache.store.CacheStoreAdapter;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.lang.IgniteBiInClosure;
+import org.jsr166.ConcurrentHashMap8;
+
+/**
+ * {@link TestCacheStoreStrategy} implemented as a wrapper around {@link #map}
+ */
+public class MapCacheStoreStrategy implements TestCacheStoreStrategy {
+    /** Removes counter. */
+    private final static AtomicInteger removes = new AtomicInteger();
+
+    /** Writes counter. */
+    private final static AtomicInteger writes = new AtomicInteger();
+
+    /** Reads counter. */
+    private final static AtomicInteger reads = new AtomicInteger();
+
+    /** Store map. */
+    private final static Map<Object, Object> map = new ConcurrentHashMap8<>();
+
+    /** {@inheritDoc} */
+    @Override public int getReads() {
+        return reads.get();
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getWrites() {
+        return writes.get();
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getRemoves() {
+        return removes.get();
+    }
+
+    /** {@inheritDoc} */
+    @Override public int getStoreSize() {
+        return map.size();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void resetStore() {
+        map.clear();
+
+        reads.set(0);
+        writes.set(0);
+        removes.set(0);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void putToStore(Object key, Object val) {
+        map.put(key, val);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void putAllToStore(Map<?, ?> data) {
+        map.putAll(data);
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object getFromStore(Object key) {
+        return map.get(key);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void removeFromStore(Object key) {
+        map.remove(key);
+    }
+
+    /** {@inheritDoc} */
+    @Override public boolean isInStore(Object key) {
+        return map.containsKey(key);
+    }
+
+    /** {@inheritDoc} */
+    @Override public void updateCacheConfiguration(CacheConfiguration<Object, Object> cfg) {
+        // No-op.
+    }
+
+    /** {@inheritDoc} */
+    @Override public Factory<? extends CacheStore<Object, Object>> getStoreFactory() {
+        return FactoryBuilder.factoryOf(MapCacheStore.class);
+    }
+
+    /** Serializable {@link #map} backed cache store factory */
+    public static class MapStoreFactory implements Factory<CacheStore<Object, Object>> {
+        /** {@inheritDoc} */
+        @Override public CacheStore<Object, Object> create() {
+            return new MapCacheStore();
+        }
+    }
+
+    /** {@link CacheStore} backed by {@link #map} */
+    public static class MapCacheStore extends CacheStoreAdapter<Object, Object> {
+        /** {@inheritDoc} */
+        @Override public void loadCache(IgniteBiInClosure<Object, Object> clo, Object... args) {
+            for (Map.Entry<Object, Object> e : map.entrySet())
+                clo.apply(e.getKey(), e.getValue());
+        }
+
+        /** {@inheritDoc} */
+        @Override public Object load(Object key) {
+            reads.incrementAndGet();
+            return map.get(key);
+        }
+
+        /** {@inheritDoc} */
+        @Override public void write(Cache.Entry<?, ?> e) {
+            writes.incrementAndGet();
+            map.put(e.getKey(), e.getValue());
+        }
+
+        /** {@inheritDoc} */
+        @Override public void delete(Object key) {
+            removes.incrementAndGet();
+            map.remove(key);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/5b49dadd/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/TestCacheStoreStrategy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/TestCacheStoreStrategy.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/TestCacheStoreStrategy.java
new file mode 100644
index 0000000..9ee174a
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/TestCacheStoreStrategy.java
@@ -0,0 +1,96 @@
+/*
+ * 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;
+
+import java.util.Map;
+import javax.cache.configuration.Factory;
+import org.apache.ignite.cache.store.CacheStore;
+import org.apache.ignite.configuration.CacheConfiguration;
+
+/**
+ * Interface for cache store backend manipulation and stats routines.
+ */
+public interface TestCacheStoreStrategy {
+    /**
+     * @return Number of reads to store.
+     */
+    public int getReads();
+
+    /**
+     * @return Number of writes to store.
+     */
+    public int getWrites();
+
+    /**
+     * @return Number of removals from store.
+     */
+    public int getRemoves();
+
+    /**
+     * @return Total number of items in the store.
+     */
+    public int getStoreSize();
+
+    /**
+     * Clear store contents.
+     */
+    public void resetStore();
+
+    /**
+     * Put entry to cache store.
+     *
+     * @param key Key.
+     * @param val Value.
+     */
+    public void putToStore(Object key, Object val);
+
+    /**
+     * @param data Items to put to store.
+     */
+    public void putAllToStore(Map<?, ?> data);
+
+    /**
+     * @param key Key to look for.
+     * @return {@link Object} pointed to by given key or {@code null} if no object is present.
+     */
+    public Object getFromStore(Object key);
+
+    /**
+     * @param key to look for
+     */
+    public void removeFromStore(Object key);
+
+    /**
+     * @param key to look for.
+     * @return {@code True} if object pointed to by key is in store, false otherwise.
+     */
+    public boolean isInStore(Object key);
+
+    /**
+     * Called from {@link GridCacheAbstractSelfTest#cacheConfiguration(String)},
+     * this method allows implementations to tune cache config.
+     *
+     * @param cfg {@link CacheConfiguration} to tune.
+     */
+    public void updateCacheConfiguration(CacheConfiguration<Object, Object> cfg);
+
+    /**
+     * @return {@link Factory} for write-through storage emulator.
+     */
+    public Factory<? extends CacheStore<Object, Object>> getStoreFactory();
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/5b49dadd/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCachePartitionedOffHeapTieredMultiNodeFullApiSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCachePartitionedOffHeapTieredMultiNodeFullApiSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCachePartitionedOffHeapTieredMultiNodeFullApiSelfTest.java
index cbcc739..0386510 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCachePartitionedOffHeapTieredMultiNodeFullApiSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridCachePartitionedOffHeapTieredMultiNodeFullApiSelfTest.java
@@ -68,6 +68,6 @@ public class GridCachePartitionedOffHeapTieredMultiNodeFullApiSelfTest extends G
         assertEquals(5, primaryCache.localPeek(key, CachePeekMode.ONHEAP).intValue());
         assertNull(primaryCache.localPeek(key, CachePeekMode.OFFHEAP));
         assertEquals(5, cache.get(key).intValue());
-        assertEquals(5, map.get(key));
+        assertEquals(5, storeStgy.getFromStore(key));
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/5b49dadd/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheQueryIndexSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheQueryIndexSelfTest.java b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheQueryIndexSelfTest.java
index d834eb3..73b665e 100644
--- a/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheQueryIndexSelfTest.java
+++ b/modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheQueryIndexSelfTest.java
@@ -74,7 +74,7 @@ public class IgniteCacheQueryIndexSelfTest extends GridCacheAbstractSelfTest {
      */
     public void testWithStoreLoad() throws Exception {
         for (int i = 0; i < ENTRY_CNT; i++)
-            putToStore(i, new CacheValue(i));
+            storeStgy.putToStore(i, new CacheValue(i));
 
         IgniteCache<Integer, CacheValue> cache0 = grid(0).cache(null);
 


[41/50] [abbrv] ignite git commit: IGNITE-3446 Visor CMD: improve usability for batch mode.

Posted by vo...@apache.org.
IGNITE-3446 Visor CMD: improve usability for batch mode.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 71ef6527f1b90cf795072174378d9c401714df96
Parents: aedfde6
Author: Andrey Novikov <an...@apache.org>
Authored: Fri Jul 22 18:03:50 2016 +0700
Committer: Andrey Novikov <an...@apache.org>
Committed: Fri Jul 22 18:03:50 2016 +0700

----------------------------------------------------------------------
 .../ignite/visor/commands/cache/VisorCacheStopCommand.scala     | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/71ef6527/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheStopCommand.scala
----------------------------------------------------------------------
diff --git a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheStopCommand.scala b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheStopCommand.scala
index 1b55505..22fb89d 100644
--- a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheStopCommand.scala
+++ b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheStopCommand.scala
@@ -19,7 +19,6 @@ package org.apache.ignite.visor.commands.cache
 
 import org.apache.ignite.cluster.{ClusterGroupEmptyException, ClusterNode}
 import org.apache.ignite.visor.visor._
-
 import org.apache.ignite.internal.visor.cache.VisorCacheStopTask
 import org.apache.ignite.internal.visor.util.VisorTaskUtils._
 
@@ -102,7 +101,9 @@ class VisorCacheStopCommand {
                 return
         }
 
-        ask(s"Are you sure you want to stop cache: ${escapeName(cacheName)}? (y/n) [n]: ", "n") match {
+        val dflt = if (batchMode) "y" else "n"
+
+        ask(s"Are you sure you want to stop cache: ${escapeName(cacheName)}? (y/n) [$dflt]: ", dflt) match {
             case "y" | "Y" =>
                 try {
                     executeRandom(grp, classOf[VisorCacheStopTask], cacheName)


[21/50] [abbrv] ignite git commit: ignite-3392 Added test.

Posted by vo...@apache.org.
ignite-3392 Added test.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: a056954bbb179300716961c116b51492889db356
Parents: 762c43d
Author: sboikov <sb...@gridgain.com>
Authored: Wed Jul 13 12:29:33 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Wed Jul 13 12:29:33 2016 +0300

----------------------------------------------------------------------
 .../processors/service/GridServiceProxy.java    | 54 ++++++-------
 ...rviceDeploymentExceptionPropagationTest.java | 80 ++++++++++++++++++++
 2 files changed, 107 insertions(+), 27 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/a056954b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProxy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProxy.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProxy.java
index 25b2915..ba140f2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProxy.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProxy.java
@@ -169,38 +169,38 @@ class GridServiceProxy<T> implements Serializable {
 
                         // If service is deployed locally, then execute locally.
                         if (node.isLocal()) {
-                            ServiceContextImpl svcCtx = ctx.service().serviceContext(name);
+                                ServiceContextImpl svcCtx = ctx.service().serviceContext(name);
 
-                        if (svcCtx != null) {
-                            Service svc = svcCtx.service();
+                            if (svcCtx != null) {
+                                Service svc = svcCtx.service();
 
-                            if (svc != null)
-                                return mtd.invoke(svc, args);
+                                if (svc != null)
+                                    return mtd.invoke(svc, args);
+                            }
+                        }
+                        else {
+                            // Execute service remotely.
+                            return ctx.closure().callAsyncNoFailover(
+                                BALANCE,
+                                new ServiceProxyCallable(mtd.getName(), name, mtd.getParameterTypes(), args),
+                                Collections.singleton(node),
+                                false
+                            ).get();
                         }
                     }
-                    else {
-                        // Execute service remotely.
-                        return ctx.closure().callAsyncNoFailover(
-                            BALANCE,
-                            new ServiceProxyCallable(mtd.getName(), name, mtd.getParameterTypes(), args),
-                            Collections.singleton(node),
-                            false
-                        ).get();
+                    catch (GridServiceNotFoundException | ClusterTopologyCheckedException e) {
+                        if (log.isDebugEnabled())
+                            log.debug("Service was not found or topology changed (will retry): " + e.getMessage());
+                    }
+                    catch (RuntimeException | Error e) {
+                        throw e;
+                    }
+                    catch (IgniteCheckedException e) {
+                        throw U.convertException(e);
+                    }
+                    catch (Exception e) {
+                        throw new IgniteException(e);
                     }
-                }
-                catch (GridServiceNotFoundException | ClusterTopologyCheckedException e) {
-                    if (log.isDebugEnabled())
-                        log.debug("Service was not found or topology changed (will retry): " + e.getMessage());
-                }
-                catch (RuntimeException | Error e) {
-                    throw e;
-                }
-                catch (IgniteCheckedException e) {
-                    throw U.convertException(e);
-                }
-                catch (Exception e) {
-                    throw new IgniteException(e);
-                }
 
                     // If we are here, that means that service was not found
                     // or topology was changed. In this case, we erase the

http://git-wip-us.apache.org/repos/asf/ignite/blob/a056954b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/GridServiceDeploymentExceptionPropagationTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/service/GridServiceDeploymentExceptionPropagationTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/GridServiceDeploymentExceptionPropagationTest.java
new file mode 100644
index 0000000..811594f
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/service/GridServiceDeploymentExceptionPropagationTest.java
@@ -0,0 +1,80 @@
+/*
+ * 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.service;
+
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.services.Service;
+import org.apache.ignite.services.ServiceContext;
+import org.apache.ignite.testframework.GridStringLogger;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+/** */
+public class GridServiceDeploymentExceptionPropagationTest extends GridCommonAbstractTest {
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+
+        super.afterTestsStopped();
+    }
+
+    /** */
+    @SuppressWarnings("unused")
+    public void testExceptionPropagation() throws Exception {
+        try (Ignite srv = startGrid("server")) {
+
+            GridStringLogger log = new GridStringLogger();
+
+            try (Ignite client = startGrid("client", getConfiguration("client").setGridLogger(log).setClientMode(true))) {
+
+                try {
+                    client.services().deployClusterSingleton("my-service", new ServiceImpl());
+                }
+                catch (IgniteException e) {
+                    assertTrue(log.toString().contains("ServiceImpl init exception"));
+
+                    return; // Exception is what we expect.
+                }
+
+                // Fail explicitly if we've managed to get here though we shouldn't have.
+                fail("https://issues.apache.org/jira/browse/IGNITE-3392");
+            }
+        }
+    }
+
+    /**
+     * Simple service implementation throwing an exception on init.
+     * Doesn't even try to do anything useful because what we're testing here is failure.
+     */
+    private static class ServiceImpl implements Service {
+        /** {@inheritDoc} */
+        @Override public void cancel(ServiceContext ctx) {
+            // No-op.
+        }
+
+        /** {@inheritDoc} */
+        @Override public void init(ServiceContext ctx) throws Exception {
+            throw new RuntimeException("ServiceImpl init exception");
+        }
+
+        /** {@inheritDoc} */
+        @Override public void execute(ServiceContext ctx) throws Exception {
+            // No-op.
+        }
+    }
+}


[06/50] [abbrv] ignite git commit: VisorNodeDataCollectorTask should be aware of passed nodes IDs.

Posted by vo...@apache.org.
 VisorNodeDataCollectorTask should be aware of passed nodes IDs.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: c35c6522d9d2e34322ab39de9d689f7a72647b39
Parents: 8ed13e8
Author: Alexey Kuznetsov <ak...@apache.org>
Authored: Wed Jul 6 17:48:12 2016 +0700
Committer: Alexey Kuznetsov <ak...@apache.org>
Committed: Wed Jul 6 17:48:12 2016 +0700

----------------------------------------------------------------------
 .../visor/node/VisorNodeDataCollectorTask.java  | 26 --------------------
 1 file changed, 26 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/c35c6522/modules/core/src/main/java/org/apache/ignite/internal/visor/node/VisorNodeDataCollectorTask.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/visor/node/VisorNodeDataCollectorTask.java b/modules/core/src/main/java/org/apache/ignite/internal/visor/node/VisorNodeDataCollectorTask.java
index 494f902..746583d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/visor/node/VisorNodeDataCollectorTask.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/visor/node/VisorNodeDataCollectorTask.java
@@ -18,22 +18,15 @@
 package org.apache.ignite.internal.visor.node;
 
 import java.util.List;
-import java.util.Map;
 import java.util.UUID;
 import org.apache.ignite.IgniteException;
 import org.apache.ignite.cluster.ClusterGroupEmptyException;
-import org.apache.ignite.cluster.ClusterNode;
-import org.apache.ignite.compute.ComputeJob;
 import org.apache.ignite.compute.ComputeJobResult;
 import org.apache.ignite.internal.processors.task.GridInternal;
-import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.internal.visor.VisorMultiNodeTask;
-import org.apache.ignite.internal.visor.VisorTaskArgument;
 import org.apache.ignite.internal.visor.util.VisorExceptionWrapper;
 import org.jetbrains.annotations.Nullable;
 
-import static org.apache.ignite.internal.visor.util.VisorTaskUtils.logMapped;
-
 /**
  * Collects current Grid state mostly topology and metrics.
  */
@@ -44,25 +37,6 @@ public class VisorNodeDataCollectorTask extends VisorMultiNodeTask<VisorNodeData
     private static final long serialVersionUID = 0L;
 
     /** {@inheritDoc} */
-    @Override protected Map<? extends ComputeJob, ClusterNode> map0(List<ClusterNode> subgrid,
-        VisorTaskArgument<VisorNodeDataCollectorTaskArg> arg) {
-        assert arg != null;
-
-        Map<ComputeJob, ClusterNode> map = U.newHashMap(subgrid.size());
-
-        try {
-            for (ClusterNode node : subgrid)
-                map.put(job(taskArg), node);
-
-            return map;
-        }
-        finally {
-            if (debug)
-                logMapped(ignite.log(), getClass(), map.values());
-        }
-    }
-
-    /** {@inheritDoc} */
     @Override protected VisorNodeDataCollectorJob job(VisorNodeDataCollectorTaskArg arg) {
         return new VisorNodeDataCollectorJob(arg, debug);
     }


[10/50] [abbrv] ignite git commit: Revert IGNITE-2949 due to broken compatibility

Posted by vo...@apache.org.
Revert IGNITE-2949 due to broken compatibility


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 1b7428bde5bac38ac3eb2a8b015d3766f68f5a50
Parents: bebf3f0
Author: Valentin Kulichenko <va...@gmail.com>
Authored: Thu Jul 7 00:05:16 2016 -0700
Committer: Valentin Kulichenko <va...@gmail.com>
Committed: Thu Jul 7 00:05:16 2016 -0700

----------------------------------------------------------------------
 assembly/LICENSE_FABRIC                   | 7 ++++++-
 assembly/LICENSE_HADOOP                   | 7 ++++++-
 examples/pom-standalone-lgpl.xml          | 6 +++---
 examples/pom-standalone.xml               | 6 +++---
 examples/pom.xml                          | 6 +++---
 examples/schema-import/pom-standalone.xml | 6 +++---
 examples/schema-import/pom.xml            | 6 +++---
 modules/cassandra/pom.xml                 | 2 +-
 modules/core/pom.xml                      | 6 +++---
 modules/flume/README.txt                  | 2 +-
 parent/pom.xml                            | 1 +
 11 files changed, 33 insertions(+), 22 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/1b7428bd/assembly/LICENSE_FABRIC
----------------------------------------------------------------------
diff --git a/assembly/LICENSE_FABRIC b/assembly/LICENSE_FABRIC
index 8cb5730..b9c75b2 100644
--- a/assembly/LICENSE_FABRIC
+++ b/assembly/LICENSE_FABRIC
@@ -1,4 +1,3 @@
-
                                  Apache License
                            Version 2.0, January 2004
                         http://www.apache.org/licenses/
@@ -227,6 +226,12 @@ For details, see CC0 1.0 Universal (1.0), Public Domain Dedication,
 http://creativecommons.org/publicdomain/zero/1.0/
 
 ==============================================================================
+For JSR107 API and SPI (https://github.com/jsr107/jsr107spec) javax.cache:cache-api:jar:1.0.0
+==============================================================================
+This product bundles JSR107 API and SPI which is available under a:
+JSR-000107 JCACHE 2.9 Public Review - Updated Specification License. For details, see https://raw.github.com/jsr107/jsr107spec/master/LICENSE.txt.
+
+==============================================================================
 For JSch (http://www.jcraft.com/jsch/) com.jcraft:jsch:jar:0.1.50
 ==============================================================================
 This product bundles JSch which is available under a:

http://git-wip-us.apache.org/repos/asf/ignite/blob/1b7428bd/assembly/LICENSE_HADOOP
----------------------------------------------------------------------
diff --git a/assembly/LICENSE_HADOOP b/assembly/LICENSE_HADOOP
index 0d05d52..0256b20 100644
--- a/assembly/LICENSE_HADOOP
+++ b/assembly/LICENSE_HADOOP
@@ -1,4 +1,3 @@
-
                                  Apache License
                            Version 2.0, January 2004
                         http://www.apache.org/licenses/
@@ -227,6 +226,12 @@ For details, see CC0 1.0 Universal (1.0), Public Domain Dedication,
 http://creativecommons.org/publicdomain/zero/1.0/
 
 ==============================================================================
+For JSR107 API and SPI (https://github.com/jsr107/jsr107spec) javax.cache:cache-api:jar:1.0.0
+==============================================================================
+This product bundles JSR107 API and SPI which is available under a:
+JSR-000107 JCACHE 2.9 Public Review - Updated Specification License. For details, see https://raw.github.com/jsr107/jsr107spec/master/LICENSE.txt.
+
+==============================================================================
 For JSch (http://www.jcraft.com/jsch/) com.jcraft:jsch:jar:0.1.50
 ==============================================================================
 This product bundles JSch which is available under a:

http://git-wip-us.apache.org/repos/asf/ignite/blob/1b7428bd/examples/pom-standalone-lgpl.xml
----------------------------------------------------------------------
diff --git a/examples/pom-standalone-lgpl.xml b/examples/pom-standalone-lgpl.xml
index 951fab6..7e7ccc2 100644
--- a/examples/pom-standalone-lgpl.xml
+++ b/examples/pom-standalone-lgpl.xml
@@ -41,9 +41,9 @@
 
     <dependencies>
         <dependency>
-            <groupId>org.apache.geronimo.specs</groupId>
-            <artifactId>geronimo-jcache_1.0_spec</artifactId>
-            <version>1.0-alpha-1</version>
+            <groupId>javax.cache</groupId>
+            <artifactId>cache-api</artifactId>
+            <version>1.0.0</version>
         </dependency>
 
         <dependency>

http://git-wip-us.apache.org/repos/asf/ignite/blob/1b7428bd/examples/pom-standalone.xml
----------------------------------------------------------------------
diff --git a/examples/pom-standalone.xml b/examples/pom-standalone.xml
index 20399ee..6247ced 100644
--- a/examples/pom-standalone.xml
+++ b/examples/pom-standalone.xml
@@ -41,9 +41,9 @@
 
     <dependencies>
         <dependency>
-            <groupId>org.apache.geronimo.specs</groupId>
-            <artifactId>geronimo-jcache_1.0_spec</artifactId>
-            <version>1.0-alpha-1</version>
+            <groupId>javax.cache</groupId>
+            <artifactId>cache-api</artifactId>
+            <version>1.0.0</version>
         </dependency>
 
         <dependency>

http://git-wip-us.apache.org/repos/asf/ignite/blob/1b7428bd/examples/pom.xml
----------------------------------------------------------------------
diff --git a/examples/pom.xml b/examples/pom.xml
index 1c03a24..d8a38d8 100644
--- a/examples/pom.xml
+++ b/examples/pom.xml
@@ -32,9 +32,9 @@
 
     <dependencies>
         <dependency>
-            <groupId>org.apache.geronimo.specs</groupId>
-            <artifactId>geronimo-jcache_1.0_spec</artifactId>
-            <version>1.0-alpha-1</version>
+            <groupId>javax.cache</groupId>
+            <artifactId>cache-api</artifactId>
+            <version>${javax.cache.version}</version>
         </dependency>
 
         <dependency>

http://git-wip-us.apache.org/repos/asf/ignite/blob/1b7428bd/examples/schema-import/pom-standalone.xml
----------------------------------------------------------------------
diff --git a/examples/schema-import/pom-standalone.xml b/examples/schema-import/pom-standalone.xml
index 43b76d8..e443728 100644
--- a/examples/schema-import/pom-standalone.xml
+++ b/examples/schema-import/pom-standalone.xml
@@ -36,9 +36,9 @@
 
     <dependencies>
         <dependency>
-            <groupId>org.apache.geronimo.specs</groupId>
-            <artifactId>geronimo-jcache_1.0_spec</artifactId>
-            <version>1.0-alpha-1</version>
+            <groupId>javax.cache</groupId>
+            <artifactId>cache-api</artifactId>
+            <version>1.0.0</version>
         </dependency>
 
         <dependency>

http://git-wip-us.apache.org/repos/asf/ignite/blob/1b7428bd/examples/schema-import/pom.xml
----------------------------------------------------------------------
diff --git a/examples/schema-import/pom.xml b/examples/schema-import/pom.xml
index eb1236d..62bb773 100644
--- a/examples/schema-import/pom.xml
+++ b/examples/schema-import/pom.xml
@@ -39,9 +39,9 @@
 
     <dependencies>
         <dependency>
-            <groupId>org.apache.geronimo.specs</groupId>
-            <artifactId>geronimo-jcache_1.0_spec</artifactId>
-            <version>1.0-alpha-1</version>
+            <groupId>javax.cache</groupId>
+            <artifactId>cache-api</artifactId>
+            <version>${javax.cache.version}</version>
         </dependency>
 
         <dependency>

http://git-wip-us.apache.org/repos/asf/ignite/blob/1b7428bd/modules/cassandra/pom.xml
----------------------------------------------------------------------
diff --git a/modules/cassandra/pom.xml b/modules/cassandra/pom.xml
index 2eff19e..3eda256 100644
--- a/modules/cassandra/pom.xml
+++ b/modules/cassandra/pom.xml
@@ -237,7 +237,7 @@
                                 org.apache.ignite,org.springframework,org.gridgain
                             </excludeGroupIds>
                             <excludeArtifactIds>
-                                commons-logging,slf4j-api,geronimo-jcache_1.0_spec,slf4j-api,aopalliance
+                                commons-logging,slf4j-api,cache-api,slf4j-api,aopalliance
                             </excludeArtifactIds>
                             <includeScope>runtime</includeScope>
                         </configuration>

http://git-wip-us.apache.org/repos/asf/ignite/blob/1b7428bd/modules/core/pom.xml
----------------------------------------------------------------------
diff --git a/modules/core/pom.xml b/modules/core/pom.xml
index fe3a477..b80a924 100644
--- a/modules/core/pom.xml
+++ b/modules/core/pom.xml
@@ -63,9 +63,9 @@
 
     <dependencies>
         <dependency>
-            <groupId>org.apache.geronimo.specs</groupId>
-            <artifactId>geronimo-jcache_1.0_spec</artifactId>
-            <version>1.0-alpha-1</version>
+            <groupId>javax.cache</groupId>
+            <artifactId>cache-api</artifactId>
+            <version>${javax.cache.version}</version>
         </dependency>
 
         <dependency>

http://git-wip-us.apache.org/repos/asf/ignite/blob/1b7428bd/modules/flume/README.txt
----------------------------------------------------------------------
diff --git a/modules/flume/README.txt b/modules/flume/README.txt
index 97d8cac..bf7e0ff 100644
--- a/modules/flume/README.txt
+++ b/modules/flume/README.txt
@@ -20,7 +20,7 @@ plugins.d/
     |-- lib
     |   `-- ignite-flume-transformer-x.x.x.jar <-- your jar
     `-- libext
-        |-- geronimo-jcache_1.0_spec-1.0-alpha-1.jar
+        |-- cache-api-1.0.0.jar
         |-- ignite-core-x.x.x.jar
         |-- ignite-flume-x.x.x.jar <-- IgniteSink
         |-- ignite-spring-x.x.x.jar

http://git-wip-us.apache.org/repos/asf/ignite/blob/1b7428bd/parent/pom.xml
----------------------------------------------------------------------
diff --git a/parent/pom.xml b/parent/pom.xml
index 6600542..1553612 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -75,6 +75,7 @@
         <jackson.version>1.9.13</jackson.version>
         <jackson2.version>2.7.5</jackson2.version>
         <javax.cache.bundle.version>1.0.0_1</javax.cache.bundle.version>
+        <javax.cache.version>1.0.0</javax.cache.version>
         <jetty.version>9.2.11.v20150529</jetty.version>
         <jms.spec.version>1.1.1</jms.spec.version>
         <jsch.bundle.version>0.1.53_1</jsch.bundle.version>


[07/50] [abbrv] ignite git commit: VisorGatewayTask should be aware of passed nodes IDs.

Posted by vo...@apache.org.
 VisorGatewayTask should be aware of passed nodes IDs.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 5d9f899c15e44d1860e4c5d8fd8bf69c91228de9
Parents: c35c652
Author: Alexey Kuznetsov <ak...@apache.org>
Authored: Wed Jul 6 18:52:13 2016 +0700
Committer: Alexey Kuznetsov <ak...@apache.org>
Committed: Wed Jul 6 18:52:13 2016 +0700

----------------------------------------------------------------------
 .../apache/ignite/internal/visor/compute/VisorGatewayTask.java    | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/5d9f899c/modules/core/src/main/java/org/apache/ignite/internal/visor/compute/VisorGatewayTask.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/visor/compute/VisorGatewayTask.java b/modules/core/src/main/java/org/apache/ignite/internal/visor/compute/VisorGatewayTask.java
index f1d6c85..2539a26 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/visor/compute/VisorGatewayTask.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/visor/compute/VisorGatewayTask.java
@@ -355,7 +355,8 @@ public class VisorGatewayTask implements ComputeTask<Object[], Object> {
                 }
             }
 
-            return ignite.compute().execute(taskName, new VisorTaskArgument<>(nids, jobArgs, false));
+            return ignite.compute(ignite.cluster().forNodeIds(nids))
+                .execute(taskName, new VisorTaskArgument<>(nids, jobArgs, false));
         }
     }
 }


[04/50] [abbrv] ignite git commit: ignite-3336 Added properties IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT, IGNITE_LONG_OPERATIONS_DUMP_TIMEOUT. Refactored cache message logging.

Posted by vo...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareFuture.java
index cedfee5..e48e0d6 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareFuture.java
@@ -117,6 +117,9 @@ public final class GridDhtTxPrepareFuture extends GridCompoundFuture<IgniteInter
     /** Logger. */
     private static IgniteLogger log;
 
+    /** Logger. */
+    private static IgniteLogger msgLog;
+
     /** Context. */
     private GridCacheSharedContext<?, ?> cctx;
 
@@ -212,8 +215,10 @@ public final class GridDhtTxPrepareFuture extends GridCompoundFuture<IgniteInter
 
         this.nearMiniId = nearMiniId;
 
-        if (log == null)
+        if (log == null) {
+            msgLog = cctx.txPrepareMessageLogger();
             log = U.logger(cctx.kernalContext(), logRef, GridDhtTxPrepareFuture.class);
+        }
 
         dhtMap = tx.dhtMap();
         nearMap = tx.nearMap();
@@ -268,7 +273,7 @@ public final class GridDhtTxPrepareFuture extends GridCompoundFuture<IgniteInter
     /**
      * @return Transaction.
      */
-    GridDhtTxLocalAdapter tx() {
+    public GridDhtTxLocalAdapter tx() {
         return tx;
     }
 
@@ -463,13 +468,36 @@ public final class GridDhtTxPrepareFuture extends GridCompoundFuture<IgniteInter
      */
     public void onResult(UUID nodeId, GridDhtTxPrepareResponse res) {
         if (!isDone()) {
+            boolean found = false;
+
             MiniFuture mini = miniFuture(res.miniId());
 
             if (mini != null) {
+                found = true;
+
                 assert mini.node().id().equals(nodeId);
 
                 mini.onResult(res);
             }
+
+            if (!found) {
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("DHT prepare fut, failed to find mini future [txId=" + tx.nearXidVersion() +
+                        ", dhtTxId=" + tx.xidVersion() +
+                        ", node=" + nodeId +
+                        ", res=" + res +
+                        ", fut=" + this + ']');
+                }
+            }
+        }
+        else {
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("DHT prepare fut, response for finished future [txId=" + tx.nearXidVersion() +
+                    ", dhtTxId=" + tx.xidVersion() +
+                    ", node=" + nodeId +
+                    ", res=" + res +
+                    ", fut=" + this + ']');
+            }
         }
     }
 
@@ -638,7 +666,12 @@ public final class GridDhtTxPrepareFuture extends GridCompoundFuture<IgniteInter
                                         sendPrepareResponse(res);
                                 }
                                 catch (IgniteCheckedException e) {
-                                    U.error(log, "Failed to send prepare response for transaction: " + tx, e);
+                                    U.error(log, "Failed to send prepare response [txId=" + tx.nearXidVersion() + "," +
+                                        ", dhtTxId=" + tx.xidVersion() +
+                                        ", node=" + tx.nearNodeId() +
+                                        ", res=" + res,
+                                        ", tx=" + tx,
+                                        e);
                                 }
                             }
                         };
@@ -676,7 +709,12 @@ public final class GridDhtTxPrepareFuture extends GridCompoundFuture<IgniteInter
                         sendPrepareResponse(res);
                 }
                 catch (IgniteCheckedException e) {
-                    U.error(log, "Failed to send prepare response for transaction: " + tx, e);
+                    U.error(log, "Failed to send prepare response [txId=" + tx.nearXidVersion() + "," +
+                        ", dhtTxId=" + tx.xidVersion() +
+                        ", node=" + tx.nearNodeId() +
+                        ", res=" + res,
+                        ", tx=" + tx,
+                        e);
                 }
             }
 
@@ -690,7 +728,12 @@ public final class GridDhtTxPrepareFuture extends GridCompoundFuture<IgniteInter
                     sendPrepareResponse(res);
                 }
                 catch (IgniteCheckedException e) {
-                    U.error(log, "Failed to send prepare response for transaction: " + tx, e);
+                    U.error(log, "Failed to send prepare response [txId=" + tx.nearXidVersion() + "," +
+                        ", dhtTxId=" + tx.xidVersion() +
+                        ", node=" + tx.nearNodeId() +
+                        ", res=" + res,
+                        ", tx=" + tx,
+                        e);
                 }
                 finally {
                     // Will call super.onDone().
@@ -725,10 +768,26 @@ public final class GridDhtTxPrepareFuture extends GridCompoundFuture<IgniteInter
         if (!tx.nearNodeId().equals(cctx.localNodeId())) {
             Throwable err = this.err.get();
 
-            if (err != null && err instanceof IgniteFutureCancelledException)
+            if (err != null && err instanceof IgniteFutureCancelledException) {
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("DHT prepare fut, skip send response [txId=" + tx.nearXidVersion() +
+                        ", dhtTxId=" + tx.xidVersion() +
+                        ", node=" + tx.nearNodeId() +
+                        ", err=" + err +
+                        ", res=" + res + ']');
+                }
+
                 return;
+            }
 
             cctx.io().send(tx.nearNodeId(), res, tx.ioPolicy());
+
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("DHT prepare fut, sent response [txId=" + tx.nearXidVersion() +
+                    ", dhtTxId=" + tx.xidVersion() +
+                    ", node=" + tx.nearNodeId() +
+                    ", res=" + res + ']');
+            }
         }
     }
 
@@ -1178,13 +1237,34 @@ public final class GridDhtTxPrepareFuture extends GridCompoundFuture<IgniteInter
 
                     try {
                         cctx.io().send(n, req, tx.ioPolicy());
+
+                        if (msgLog.isDebugEnabled()) {
+                            msgLog.debug("DHT prepare fut, sent request dht [txId=" + tx.nearXidVersion() +
+                                ", dhtTxId=" + tx.xidVersion() +
+                                ", node=" + n.id() + ']');
+                        }
                     }
                     catch (ClusterTopologyCheckedException e) {
                         fut.onNodeLeft(e);
                     }
                     catch (IgniteCheckedException e) {
-                        if (!cctx.kernalContext().isStopping())
+                        if (!cctx.kernalContext().isStopping()) {
+                            if (msgLog.isDebugEnabled()) {
+                                msgLog.debug("DHT prepare fut, failed to send request dht [txId=" + tx.nearXidVersion() +
+                                    ", dhtTxId=" + tx.xidVersion() +
+                                    ", node=" + n.id() + ']');
+                            }
+
                             fut.onResult(e);
+                        }
+                        else {
+                            if (msgLog.isDebugEnabled()) {
+                                msgLog.debug("DHT prepare fut, failed to send request dht, ignore [txId=" + tx.nearXidVersion() +
+                                    ", dhtTxId=" + tx.xidVersion() +
+                                    ", node=" + n.id() +
+                                    ", err=" + e + ']');
+                            }
+                        }
                     }
                 }
 
@@ -1236,13 +1316,34 @@ public final class GridDhtTxPrepareFuture extends GridCompoundFuture<IgniteInter
 
                         try {
                             cctx.io().send(nearMapping.node(), req, tx.ioPolicy());
+
+                            if (msgLog.isDebugEnabled()) {
+                                msgLog.debug("DHT prepare fut, sent request near [txId=" + tx.nearXidVersion() +
+                                    ", dhtTxId=" + tx.xidVersion() +
+                                    ", node=" + nearMapping.node().id() + ']');
+                            }
                         }
                         catch (ClusterTopologyCheckedException e) {
                             fut.onNodeLeft(e);
                         }
                         catch (IgniteCheckedException e) {
-                            if (!cctx.kernalContext().isStopping())
+                            if (!cctx.kernalContext().isStopping()) {
+                                if (msgLog.isDebugEnabled()) {
+                                    msgLog.debug("DHT prepare fut, failed to send request near [txId=" + tx.nearXidVersion() +
+                                        ", dhtTxId=" + tx.xidVersion() +
+                                        ", node=" + nearMapping.node().id() + ']');
+                                }
+
                                 fut.onResult(e);
+                            }
+                            else {
+                                if (msgLog.isDebugEnabled()) {
+                                    msgLog.debug("DHT prepare fut, failed to send request near, ignore [txId=" + tx.nearXidVersion() +
+                                        ", dhtTxId=" + tx.xidVersion() +
+                                        ", node=" + nearMapping.node().id() +
+                                        ", err=" + e + ']');
+                                }
+                            }
                         }
                     }
                 }
@@ -1458,8 +1559,11 @@ public final class GridDhtTxPrepareFuture extends GridCompoundFuture<IgniteInter
          * @param e Node failure.
          */
         void onNodeLeft(ClusterTopologyCheckedException e) {
-            if (log.isDebugEnabled())
-                log.debug("Remote node left grid while sending or waiting for reply (will ignore): " + this);
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("DHT prepare fut, mini future node left [txId=" + tx.nearXidVersion() +
+                    ", dhtTxId=" + tx.xidVersion() +
+                    ", node=" + node().id() + ']');
+            }
 
             if (tx != null)
                 tx.removeMapping(nodeId);

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicCache.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicCache.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicCache.java
index ad87add..6bb6a80 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicCache.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicCache.java
@@ -37,6 +37,7 @@ import javax.cache.processor.EntryProcessor;
 import javax.cache.processor.EntryProcessorResult;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.cluster.ClusterNode;
 import org.apache.ignite.internal.IgniteInternalFuture;
 import org.apache.ignite.internal.NodeStoppingException;
@@ -151,6 +152,9 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
     /** */
     private GridNearAtomicCache<K, V> near;
 
+    /** Logger. */
+    private IgniteLogger msgLog;
+
     /**
      * Empty constructor required by {@link Externalizable}.
      */
@@ -163,6 +167,8 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
      */
     public GridDhtAtomicCache(GridCacheContext<K, V> ctx) {
         super(ctx);
+
+        msgLog = ctx.shared().atomicMessageLogger();
     }
 
     /**
@@ -171,6 +177,8 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
      */
     public GridDhtAtomicCache(GridCacheContext<K, V> ctx, GridCacheConcurrentMap map) {
         super(ctx, map);
+
+        msgLog = ctx.shared().atomicMessageLogger();
     }
 
     /** {@inheritDoc} */
@@ -1428,7 +1436,8 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
                         ClusterNode node = ctx.discovery().node(nodeId);
 
                         if (node == null) {
-                            U.warn(log, "Node originated update request left grid: " + nodeId);
+                            U.warn(msgLog, "Skip near update request, node originated update request left [" +
+                                "futId=" + req.futureVersion() + ", node=" + nodeId + ']');
 
                             return;
                         }
@@ -1443,14 +1452,15 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
 
                             if (hasNear)
                                 res.nearVersion(ver);
+
+                            if (msgLog.isDebugEnabled()) {
+                                msgLog.debug("Assigned update version [futId=" + req.futureVersion() +
+                                    ", writeVer=" + ver + ']');
+                            }
                         }
 
                         assert ver != null : "Got null version for update request: " + req;
 
-                        if (log.isDebugEnabled())
-                            log.debug("Using cache version for update request on primary node [ver=" + ver +
-                                ", req=" + req + ']');
-
                         boolean sndPrevVal = !top.rebalanceFinished(req.topologyVersion());
 
                         dhtFut = createDhtFuture(ver, req, res, completionCb, false);
@@ -2776,8 +2786,11 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
      * @param req Near atomic update request.
      */
     private void processNearAtomicUpdateRequest(UUID nodeId, GridNearAtomicUpdateRequest req) {
-        if (log.isDebugEnabled())
-            log.debug("Processing near atomic update request [nodeId=" + nodeId + ", req=" + req + ']');
+        if (msgLog.isDebugEnabled()) {
+            msgLog.debug("Received near atomic update request [futId=" + req.futureVersion() +
+                ", writeVer=" + req.updateVersion() +
+                ", node=" + nodeId + ']');
+        }
 
         req.nodeId(ctx.localNodeId());
 
@@ -2790,8 +2803,8 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
      */
     @SuppressWarnings("unchecked")
     private void processNearAtomicUpdateResponse(UUID nodeId, GridNearAtomicUpdateResponse res) {
-        if (log.isDebugEnabled())
-            log.debug("Processing near atomic update response [nodeId=" + nodeId + ", res=" + res + ']');
+        if (msgLog.isDebugEnabled())
+            msgLog.debug("Received near atomic update response [futId" + res.futureVersion() + ", node=" + nodeId + ']');
 
         res.nodeId(ctx.localNodeId());
 
@@ -2799,9 +2812,10 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
 
         if (fut != null)
             fut.onResult(nodeId, res);
-        else
-            U.warn(log, "Failed to find near update future for update response (will ignore) " +
-                "[nodeId=" + nodeId + ", res=" + res + ']');
+        else {
+            U.warn(msgLog, "Failed to find near update future for update response (will ignore) " +
+                "[futId" + res.futureVersion() + ", node=" + nodeId + ", res=" + res + ']');
+        }
     }
 
     /**
@@ -2809,8 +2823,10 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
      * @param req Dht atomic update request.
      */
     private void processDhtAtomicUpdateRequest(UUID nodeId, GridDhtAtomicUpdateRequest req) {
-        if (log.isDebugEnabled())
-            log.debug("Processing dht atomic update request [nodeId=" + nodeId + ", req=" + req + ']');
+        if (msgLog.isDebugEnabled()) {
+            msgLog.debug("Received DHT atomic update request [futId=" + req.futureVersion() +
+                ", writeVer=" + req.writeVersion() + ", node=" + nodeId + ']');
+        }
 
         GridCacheVersion ver = req.writeVersion();
 
@@ -2908,20 +2924,31 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
             ((GridNearAtomicCache<K, V>)near()).processDhtAtomicUpdateRequest(nodeId, req, res);
 
         try {
-            if (res.failedKeys() != null || res.nearEvicted() != null || req.writeSynchronizationMode() == FULL_SYNC)
+            if (res.failedKeys() != null || res.nearEvicted() != null || req.writeSynchronizationMode() == FULL_SYNC) {
                 ctx.io().send(nodeId, res, ctx.ioPolicy());
+
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Sent DHT atomic update response [futId=" + req.futureVersion() +
+                        ", writeVer=" + req.writeVersion() + ", node=" + nodeId + ']');
+                }
+            }
             else {
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Will send deferred DHT atomic update response [futId=" + req.futureVersion() +
+                        ", writeVer=" + req.writeVersion() + ", node=" + nodeId + ']');
+                }
+
                 // No failed keys and sync mode is not FULL_SYNC, thus sending deferred response.
                 sendDeferredUpdateResponse(nodeId, req.futureVersion());
             }
         }
         catch (ClusterTopologyCheckedException ignored) {
-            U.warn(log, "Failed to send DHT atomic update response to node because it left grid: " +
-                req.nodeId());
+            U.warn(msgLog, "Failed to send DHT atomic update response, node left [futId=" + req.futureVersion() +
+                ", node=" + req.nodeId() + ']');
         }
         catch (IgniteCheckedException e) {
-            U.error(log, "Failed to send DHT atomic update response (did node leave grid?) [nodeId=" + nodeId +
-                ", req=" + req + ']', e);
+            U.error(msgLog, "Failed to send DHT atomic update response [futId=" + req.futureVersion() +
+                ", node=" + nodeId +  ", res=" + res + ']', e);
         }
     }
 
@@ -2960,16 +2987,20 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
      */
     @SuppressWarnings("unchecked")
     private void processDhtAtomicUpdateResponse(UUID nodeId, GridDhtAtomicUpdateResponse res) {
-        if (log.isDebugEnabled())
-            log.debug("Processing dht atomic update response [nodeId=" + nodeId + ", res=" + res + ']');
-
         GridDhtAtomicUpdateFuture updateFut = (GridDhtAtomicUpdateFuture)ctx.mvcc().atomicFuture(res.futureVersion());
 
-        if (updateFut != null)
+        if (updateFut != null) {
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("Received DHT atomic update response [futId=" + res.futureVersion() +
+                    ", writeVer=" + updateFut.writeVersion() + ", node=" + nodeId + ']');
+            }
+
             updateFut.onResult(nodeId, res);
-        else
-            U.warn(log, "Failed to find DHT update future for update response [nodeId=" + nodeId +
-                ", res=" + res + ']');
+        }
+        else {
+            U.warn(msgLog, "Failed to find DHT update future for update response [futId=" + res.futureVersion() +
+                ", node=" + nodeId + ", res=" + res + ']');
+        }
     }
 
     /**
@@ -2978,17 +3009,21 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
      */
     @SuppressWarnings("unchecked")
     private void processDhtAtomicDeferredUpdateResponse(UUID nodeId, GridDhtAtomicDeferredUpdateResponse res) {
-        if (log.isDebugEnabled())
-            log.debug("Processing deferred dht atomic update response [nodeId=" + nodeId + ", res=" + res + ']');
-
         for (GridCacheVersion ver : res.futureVersions()) {
             GridDhtAtomicUpdateFuture updateFut = (GridDhtAtomicUpdateFuture)ctx.mvcc().atomicFuture(ver);
 
-            if (updateFut != null)
+            if (updateFut != null) {
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Received DHT atomic deferred update response [futId=" + ver +
+                        ", writeVer=" + res + ", node=" + nodeId + ']');
+                }
+
                 updateFut.onResult(nodeId);
-            else
-                U.warn(log, "Failed to find DHT update future for deferred update response [nodeId=" +
-                    nodeId + ", ver=" + ver + ", res=" + res + ']');
+            }
+            else {
+                U.warn(msgLog, "Failed to find DHT update future for deferred update response [futId=" + ver +
+                    ", nodeId=" + nodeId + ", res=" + res + ']');
+            }
         }
     }
 
@@ -2999,14 +3034,19 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
     private void sendNearUpdateReply(UUID nodeId, GridNearAtomicUpdateResponse res) {
         try {
             ctx.io().send(nodeId, res, ctx.ioPolicy());
+
+            if (msgLog.isDebugEnabled())
+                msgLog.debug("Sent near update response [futId=" + res.futureVersion() + ", node=" + nodeId + ']');
         }
         catch (ClusterTopologyCheckedException ignored) {
-            U.warn(log, "Failed to send near update reply to node because it left grid: " +
-                nodeId);
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("Failed to send near update response [futId=" + res.futureVersion() +
+                    ", node=" + nodeId + ']');
+            }
         }
         catch (IgniteCheckedException e) {
-            U.error(log, "Failed to send near update reply (did node leave grid?) [nodeId=" + nodeId +
-                ", res=" + res + ']', e);
+            U.error(msgLog, "Failed to send near update response [futId=" + res.futureVersion() +
+                ", node=" + nodeId + ", res=" + res + ']', e);
         }
     }
 
@@ -3276,24 +3316,31 @@ public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
 
                 try {
                     ctx.io().send(nodeId, msg, ctx.ioPolicy());
+
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("Sent deferred DHT update response [futIds=" + msg.futureVersions() +
+                            ", node=" + nodeId + ']');
+                    }
                 }
                 finally {
                     ctx.kernalContext().gateway().readUnlock();
                 }
             }
             catch (IllegalStateException ignored) {
-                if (log.isDebugEnabled())
-                    log.debug("Failed to send deferred dht update response to remote node (grid is stopping) " +
-                        "[nodeId=" + nodeId + ", msg=" + msg + ']');
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Failed to send deferred DHT update response, node is stopping [" +
+                        "futIds=" + msg.futureVersions() + ", node=" + nodeId + ']');
+                }
             }
             catch (ClusterTopologyCheckedException ignored) {
-                if (log.isDebugEnabled())
-                    log.debug("Failed to send deferred dht update response to remote node (did node leave grid?) " +
-                        "[nodeId=" + nodeId + ", msg=" + msg + ']');
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Failed to send deferred DHT update response, node left [" +
+                        "futIds=" + msg.futureVersions() + ", node=" + nodeId + ']');
+                }
             }
             catch (IgniteCheckedException e) {
-                U.error(log, "Failed to send deferred dht update response to remote node [nodeId="
-                    + nodeId + ", msg=" + msg + ']', e);
+                U.error(log, "Failed to send deferred DHT update response to remote node [" +
+                    "futIds=" + msg.futureVersions() + ", node=" + nodeId + ']', e);
             }
 
             pendingResponses.remove(nodeId, this);

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicDeferredUpdateResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicDeferredUpdateResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicDeferredUpdateResponse.java
index 3a7bf1c..923b220 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicDeferredUpdateResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicDeferredUpdateResponse.java
@@ -20,9 +20,11 @@ package org.apache.ignite.internal.processors.cache.distributed.dht.atomic;
 import java.io.Externalizable;
 import java.nio.ByteBuffer;
 import java.util.Collection;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.GridDirectCollection;
 import org.apache.ignite.internal.processors.cache.GridCacheDeployable;
 import org.apache.ignite.internal.processors.cache.GridCacheMessage;
+import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
@@ -83,6 +85,11 @@ public class GridDhtAtomicDeferredUpdateResponse extends GridCacheMessage implem
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.atomicMessageLogger();
+    }
+
+    /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateFuture.java
index df44455..2e44317 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateFuture.java
@@ -63,7 +63,10 @@ public class GridDhtAtomicUpdateFuture extends GridFutureAdapter<Void>
     private static final AtomicReference<IgniteLogger> logRef = new AtomicReference<>();
 
     /** Logger. */
-    protected static IgniteLogger log;
+    private static IgniteLogger log;
+
+    /** Logger. */
+    private static IgniteLogger msgLog;
 
     /** Cache context. */
     private final GridCacheContext cctx;
@@ -115,8 +118,7 @@ public class GridDhtAtomicUpdateFuture extends GridFutureAdapter<Void>
      */
     public GridDhtAtomicUpdateFuture(
         GridCacheContext cctx,
-        CI2<GridNearAtomicUpdateRequest,
-        GridNearAtomicUpdateResponse> completionCb,
+        CI2<GridNearAtomicUpdateRequest, GridNearAtomicUpdateResponse> completionCb,
         GridCacheVersion writeVer,
         GridNearAtomicUpdateRequest updateReq,
         GridNearAtomicUpdateResponse updateRes
@@ -129,8 +131,10 @@ public class GridDhtAtomicUpdateFuture extends GridFutureAdapter<Void>
         this.completionCb = completionCb;
         this.updateRes = updateRes;
 
-        if (log == null)
+        if (log == null) {
+            msgLog = cctx.shared().atomicMessageLogger();
             log = U.logger(cctx.kernalContext(), logRef, GridDhtAtomicUpdateFuture.class);
+        }
 
         keys = new ArrayList<>(updateReq.keys().size());
         mappings = U.newHashMap(updateReq.keys().size());
@@ -140,6 +144,13 @@ public class GridDhtAtomicUpdateFuture extends GridFutureAdapter<Void>
         waitForExchange = !topLocked;
     }
 
+    /**
+     * @return Write version.
+     */
+    GridCacheVersion writeVersion() {
+        return writeVer;
+    }
+
     /** {@inheritDoc} */
     @Override public IgniteUuid futureId() {
         return futVer.asGridUuid();
@@ -152,10 +163,14 @@ public class GridDhtAtomicUpdateFuture extends GridFutureAdapter<Void>
 
     /** {@inheritDoc} */
     @Override public boolean onNodeLeft(UUID nodeId) {
-        if (log.isDebugEnabled())
-            log.debug("Processing node leave event [fut=" + this + ", nodeId=" + nodeId + ']');
+        boolean res = registerResponse(nodeId);
+
+        if (res && msgLog.isDebugEnabled()) {
+            msgLog.debug("DTH update fut, node left [futId=" + futVer + ", writeVer=" + writeVer +
+                ", node=" + nodeId + ']');
+        }
 
-        return registerResponse(nodeId);
+        return res;
     }
 
     /**
@@ -388,20 +403,24 @@ public class GridDhtAtomicUpdateFuture extends GridFutureAdapter<Void>
         if (!mappings.isEmpty()) {
             for (GridDhtAtomicUpdateRequest req : mappings.values()) {
                 try {
-                    if (log.isDebugEnabled())
-                        log.debug("Sending DHT atomic update request [nodeId=" + req.nodeId() + ", req=" + req + ']');
-
                     cctx.io().send(req.nodeId(), req, cctx.ioPolicy());
+
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("DTH update fut, sent request [futId=" + futVer +
+                            ", writeVer=" + writeVer + ", node=" + req.nodeId() + ']');
+                    }
                 }
                 catch (ClusterTopologyCheckedException ignored) {
-                    U.warn(log, "Failed to send update request to backup node because it left grid: " +
-                        req.nodeId());
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("DTH update fut, failed to send request, node left [futId=" + futVer +
+                            ", writeVer=" + writeVer + ", node=" + req.nodeId() + ']');
+                    }
 
                     registerResponse(req.nodeId());
                 }
                 catch (IgniteCheckedException e) {
-                    U.error(log, "Failed to send update request to backup node (did node leave the grid?): "
-                        + req.nodeId(), e);
+                    U.error(msgLog, "Failed to send request [futId=" + futVer +
+                        ", writeVer=" + writeVer + ", node=" + req.nodeId() + ']');
 
                     registerResponse(req.nodeId());
                 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateRequest.java
index ed50f41..3901dbd 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateRequest.java
@@ -25,6 +25,7 @@ import java.util.List;
 import java.util.UUID;
 import javax.cache.processor.EntryProcessor;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.cache.CacheWriteSynchronizationMode;
 import org.apache.ignite.internal.GridDirectCollection;
 import org.apache.ignite.internal.GridDirectTransient;
@@ -703,6 +704,11 @@ public class GridDhtAtomicUpdateRequest extends GridCacheMessage implements Grid
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.atomicMessageLogger();
+    }
+
+    /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java
index 1c7b5f0..742b39c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java
@@ -23,6 +23,7 @@ import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.GridDirectCollection;
 import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.processors.cache.GridCacheContext;
@@ -188,6 +189,11 @@ public class GridDhtAtomicUpdateResponse extends GridCacheMessage implements Gri
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.atomicMessageLogger();
+    }
+
+    /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateFuture.java
index c9e1a11..c125514 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateFuture.java
@@ -75,7 +75,10 @@ public class GridNearAtomicUpdateFuture extends GridFutureAdapter<Object>
     private static final AtomicReference<IgniteLogger> logRef = new AtomicReference<>();
 
     /** Logger. */
-    protected static IgniteLogger log;
+    private static IgniteLogger log;
+
+    /** Logger. */
+    private static IgniteLogger msgLog;
 
     /** Cache context. */
     private final GridCacheContext cctx;
@@ -216,8 +219,10 @@ public class GridNearAtomicUpdateFuture extends GridFutureAdapter<Object>
         this.keepBinary = keepBinary;
         this.waitTopFut = waitTopFut;
 
-        if (log == null)
+        if (log == null) {
+            msgLog = cctx.shared().atomicMessageLogger();
             log = U.logger(cctx.kernalContext(), logRef, GridFutureAdapter.class);
+        }
 
         fastMap = F.isEmpty(filter) && op != TRANSFORM && cctx.config().getWriteSynchronizationMode() == FULL_SYNC &&
             cctx.config().getAtomicWriteOrderMode() == CLOCK &&
@@ -463,15 +468,25 @@ public class GridNearAtomicUpdateFuture extends GridFutureAdapter<Object>
         }
         else {
             try {
-                if (log.isDebugEnabled())
-                    log.debug("Sending near atomic update request [nodeId=" + req.nodeId() + ", req=" + req + ']');
-
                 cctx.io().send(req.nodeId(), req, cctx.ioPolicy());
 
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Near update fut, sent request [futId=" + req.futureVersion() +
+                        ", writeVer=" + req.updateVersion() +
+                        ", node=" + req.nodeId() + ']');
+                }
+
                 if (syncMode == FULL_ASYNC)
                     onDone(new GridCacheReturn(cctx, true, true, null, true));
             }
             catch (IgniteCheckedException e) {
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Near update fut, failed to send request [futId=" + req.futureVersion() +
+                        ", writeVer=" + req.updateVersion() +
+                        ", node=" + req.nodeId() +
+                        ", err=" + e + ']');
+                }
+
                 state.onSendError(req, e);
             }
         }
@@ -497,12 +512,22 @@ public class GridNearAtomicUpdateFuture extends GridFutureAdapter<Object>
             }
             else {
                 try {
-                    if (log.isDebugEnabled())
-                        log.debug("Sending near atomic update request [nodeId=" + req.nodeId() + ", req=" + req + ']');
-
                     cctx.io().send(req.nodeId(), req, cctx.ioPolicy());
+
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("Near update fut, sent request [futId=" + req.futureVersion() +
+                            ", writeVer=" + req.updateVersion() +
+                            ", node=" + req.nodeId() + ']');
+                    }
                 }
                 catch (IgniteCheckedException e) {
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("Near update fut, failed to send request [futId=" + req.futureVersion() +
+                            ", writeVer=" + req.updateVersion() +
+                            ", node=" + req.nodeId() +
+                            ", err=" + e + ']');
+                    }
+
                     state.onSendError(req, e);
                 }
             }
@@ -572,9 +597,9 @@ public class GridNearAtomicUpdateFuture extends GridFutureAdapter<Object>
         void onNodeLeft(UUID nodeId) {
             GridNearAtomicUpdateResponse res = null;
 
-            synchronized (this) {
-                GridNearAtomicUpdateRequest req;
+            GridNearAtomicUpdateRequest req;
 
+            synchronized (this) {
                 if (singleReq != null)
                     req = singleReq.nodeId().equals(nodeId) ? singleReq : null;
                 else
@@ -595,8 +620,15 @@ public class GridNearAtomicUpdateFuture extends GridFutureAdapter<Object>
                 }
             }
 
-            if (res != null)
+            if (res != null) {
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Near update fut, node left [futId=" + req.futureVersion() +
+                        ", writeVer=" + req.updateVersion() +
+                        ", node=" + nodeId + ']');
+                }
+
                 onResult(nodeId, res, true);
+            }
         }
 
         /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java
index c756d9a..1d03dd2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java
@@ -26,6 +26,7 @@ import java.util.UUID;
 import javax.cache.expiry.ExpiryPolicy;
 import javax.cache.processor.EntryProcessor;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.cache.CacheWriteSynchronizationMode;
 import org.apache.ignite.internal.GridDirectCollection;
 import org.apache.ignite.internal.GridDirectTransient;
@@ -642,6 +643,11 @@ public class GridNearAtomicUpdateRequest extends GridCacheMessage implements Gri
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.atomicMessageLogger();
+    }
+
+    /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java
index 8c55b85..dd52aae 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java
@@ -25,6 +25,7 @@ import java.util.List;
 import java.util.UUID;
 import java.util.concurrent.ConcurrentLinkedQueue;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.internal.GridDirectCollection;
 import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.processors.cache.CacheObject;
@@ -435,6 +436,11 @@ public class GridNearAtomicUpdateResponse extends GridCacheMessage implements Gr
     }
 
     /** {@inheritDoc} */
+    @Override public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
+        return ctx.atomicMessageLogger();
+    }
+
+    /** {@inheritDoc} */
     @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
         writer.setBuffer(buf);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java
index e8e8298..70ee6e5 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedCache.java
@@ -1082,6 +1082,9 @@ public class GridDhtColocatedCache<K, V> extends GridDhtTransactionalCacheAdapte
      * @param res Response.
      */
     private void processLockResponse(UUID nodeId, GridNearLockResponse res) {
+        if (txLockMsgLog.isDebugEnabled())
+            txLockMsgLog.debug("Received near lock response [txId=" + res.version() + ", node=" + nodeId + ']');
+
         assert nodeId != null;
         assert res != null;
 
@@ -1090,6 +1093,13 @@ public class GridDhtColocatedCache<K, V> extends GridDhtTransactionalCacheAdapte
 
         if (fut != null)
             fut.onResult(nodeId, res);
+        else {
+            if (txLockMsgLog.isDebugEnabled()) {
+                txLockMsgLog.debug("Received near lock response for unknown future [txId=" + res.version() +
+                    ", node=" + nodeId +
+                    ", res=" + res + ']');
+            }
+        }
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedLockFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedLockFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedLockFuture.java
index dc55eb5..577f0f4 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedLockFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/colocated/GridDhtColocatedLockFuture.java
@@ -92,6 +92,9 @@ public final class GridDhtColocatedLockFuture extends GridCompoundIdentityFuture
     /** Logger. */
     private static IgniteLogger log;
 
+    /** Logger. */
+    private static IgniteLogger msgLog;
+
     /** Cache registry. */
     @GridToStringExclude
     private final GridCacheContext<?, ?> cctx;
@@ -198,8 +201,10 @@ public final class GridDhtColocatedLockFuture extends GridCompoundIdentityFuture
 
         futId = IgniteUuid.randomUuid();
 
-        if (log == null)
+        if (log == null) {
+            msgLog = cctx.shared().txLockMessageLogger();
             log = U.logger(cctx.kernalContext(), logRef, GridDhtColocatedLockFuture.class);
+        }
 
         if (timeout > 0) {
             timeoutObj = new LockTimeoutObject();
@@ -403,10 +408,6 @@ public final class GridDhtColocatedLockFuture extends GridCompoundIdentityFuture
                 MiniFuture f = (MiniFuture)fut;
 
                 if (f.node().id().equals(nodeId)) {
-                    if (log.isDebugEnabled())
-                        log.debug("Found mini-future for left node [nodeId=" + nodeId + ", mini=" + f + ", fut=" +
-                            this + ']');
-
                     f.onResult(newTopologyException(null, nodeId));
 
                     found = true;
@@ -427,33 +428,29 @@ public final class GridDhtColocatedLockFuture extends GridCompoundIdentityFuture
      */
     void onResult(UUID nodeId, GridNearLockResponse res) {
         if (!isDone()) {
-            if (log.isDebugEnabled())
-                log.debug("Received lock response from node [nodeId=" + nodeId + ", res=" + res + ", fut=" +
-                    this + ']');
-
             MiniFuture mini = miniFuture(res.miniId());
 
             if (mini != null) {
                 assert mini.node().id().equals(nodeId);
 
-                if (log.isDebugEnabled())
-                    log.debug("Found mini future for response [mini=" + mini + ", res=" + res + ']');
-
                 mini.onResult(res);
 
-                if (log.isDebugEnabled())
-                    log.debug("Future after processed lock response [fut=" + this + ", mini=" + mini +
-                        ", res=" + res + ']');
-
                 return;
             }
 
-            U.warn(log, "Failed to find mini future for response (perhaps due to stale message) [res=" + res +
+            U.warn(msgLog, "Collocated lock fut, failed to find mini future [txId=" + lockVer +
+                ", inTx=" + inTx() +
+                ", node=" + nodeId +
+                ", res=" + res +
                 ", fut=" + this + ']');
         }
-        else if (log.isDebugEnabled())
-            log.debug("Ignoring lock response from node (future is done) [nodeId=" + nodeId + ", res=" + res +
-                ", fut=" + this + ']');
+        else {
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("Collocated lock fut, response for finished future [txId=" + lockVer +
+                    ", inTx=" + inTx() +
+                    ", node=" + nodeId + ']');
+            }
+        }
     }
 
     /**
@@ -1059,10 +1056,13 @@ public final class GridDhtColocatedLockFuture extends GridCompoundIdentityFuture
 
             if (txSync == null || txSync.isDone()) {
                 try {
-                    if (log.isDebugEnabled())
-                        log.debug("Sending near lock request [node=" + node.id() + ", req=" + req + ']');
-
                     cctx.io().send(node, req, cctx.ioPolicy());
+
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("Collocated lock fut, sent request [txId=" + lockVer +
+                            ", inTx=" + inTx() +
+                            ", node=" + node.id() + ']');
+                    }
                 }
                 catch (ClusterTopologyCheckedException ex) {
                     assert fut != null;
@@ -1074,10 +1074,13 @@ public final class GridDhtColocatedLockFuture extends GridCompoundIdentityFuture
                 txSync.listen(new CI1<IgniteInternalFuture<?>>() {
                     @Override public void apply(IgniteInternalFuture<?> t) {
                         try {
-                            if (log.isDebugEnabled())
-                                log.debug("Sending near lock request [node=" + node.id() + ", req=" + req + ']');
-
                             cctx.io().send(node, req, cctx.ioPolicy());
+
+                            if (msgLog.isDebugEnabled()) {
+                                msgLog.debug("Collocated lock fut, sent request [txId=" + lockVer +
+                                    ", inTx=" + inTx() +
+                                    ", node=" + node.id() + ']');
+                            }
                         }
                         catch (ClusterTopologyCheckedException ex) {
                             assert fut != null;
@@ -1085,6 +1088,13 @@ public final class GridDhtColocatedLockFuture extends GridCompoundIdentityFuture
                             fut.onResult(ex);
                         }
                         catch (IgniteCheckedException e) {
+                            if (msgLog.isDebugEnabled()) {
+                                msgLog.debug("Collocated lock fut, failed to send request [txId=" + lockVer +
+                                    ", inTx=" + inTx() +
+                                    ", node=" + node.id() +
+                                    ", err=" + e + ']');
+                            }
+
                             onError(e);
                         }
                     }
@@ -1421,6 +1431,12 @@ public final class GridDhtColocatedLockFuture extends GridCompoundIdentityFuture
          * @param e Node left exception.
          */
         void onResult(ClusterTopologyCheckedException e) {
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("Collocated lock fut, mini future node left [txId=" + lockVer +
+                    ", inTx=" + inTx() +
+                    ", nodeId=" + node.id() + ']');
+            }
+
             if (isDone())
                 return;
 
@@ -1431,9 +1447,6 @@ public final class GridDhtColocatedLockFuture extends GridCompoundIdentityFuture
                 rcvRes = true;
             }
 
-            if (log.isDebugEnabled())
-                log.debug("Remote node left grid while sending or waiting for reply (will fail): " + this);
-
             if (tx != null)
                 tx.removeMapping(node.id());
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsExchangeFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsExchangeFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsExchangeFuture.java
index be346b4..dc006c1 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsExchangeFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionsExchangeFuture.java
@@ -75,6 +75,7 @@ import org.apache.ignite.lang.IgnitePredicate;
 import org.jetbrains.annotations.Nullable;
 import org.jsr166.ConcurrentHashMap8;
 
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT;
 import static org.apache.ignite.events.EventType.EVT_NODE_FAILED;
 import static org.apache.ignite.events.EventType.EVT_NODE_JOINED;
 import static org.apache.ignite.events.EventType.EVT_NODE_LEFT;
@@ -87,7 +88,7 @@ import static org.apache.ignite.internal.managers.communication.GridIoPolicy.SYS
 public class GridDhtPartitionsExchangeFuture extends GridFutureAdapter<AffinityTopologyVersion>
     implements Comparable<GridDhtPartitionsExchangeFuture>, GridDhtTopologyFuture {
     /** */
-    private static final int DUMP_PENDING_OBJECTS_THRESHOLD =
+    public static final int DUMP_PENDING_OBJECTS_THRESHOLD =
         IgniteSystemProperties.getInteger(IgniteSystemProperties.IGNITE_DUMP_PENDING_OBJECTS_THRESHOLD, 10);
 
     /** */
@@ -786,7 +787,18 @@ public class GridDhtPartitionsExchangeFuture extends GridFutureAdapter<AffinityT
                     catch (IgniteFutureTimeoutCheckedException ignored) {
                         // Print pending transactions and locks that might have led to hang.
                         if (dumpedObjects < DUMP_PENDING_OBJECTS_THRESHOLD) {
-                            dumpPendingObjects();
+                            U.warn(log, "Failed to wait for partition release future [topVer=" + topologyVersion() +
+                                ", node=" + cctx.localNodeId() + "]. Dumping pending objects that might be the cause: ");
+
+                            try {
+                                cctx.exchange().dumpDebugInfo();
+                            }
+                            catch (Exception e) {
+                                U.error(log, "Failed to dump debug information: " + e, e);
+                            }
+
+                            if (IgniteSystemProperties.getBoolean(IGNITE_THREAD_DUMP_ON_EXCHANGE_TIMEOUT, false))
+                                U.dumpThreads(log);
 
                             dumpedObjects++;
                         }
@@ -923,16 +935,6 @@ public class GridDhtPartitionsExchangeFuture extends GridFutureAdapter<AffinityT
     }
 
     /**
-     *
-     */
-    private void dumpPendingObjects() {
-        U.warn(log, "Failed to wait for partition release future [topVer=" + topologyVersion() +
-            ", node=" + cctx.localNodeId() + "]. Dumping pending objects that might be the cause: ");
-
-        cctx.exchange().dumpDebugInfo();
-    }
-
-    /**
      * @param cacheId Cache ID to check.
      * @return {@code True} if cache is stopping by this exchange.
      */

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFuture.java
index 818c998..cf48889 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearOptimisticTxPrepareFuture.java
@@ -160,6 +160,22 @@ public class GridNearOptimisticTxPrepareFuture extends GridNearOptimisticTxPrepa
 
                 mini.onResult(nodeId, res);
             }
+            else {
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Near optimistic prepare fut, failed to find mini future [txId=" + tx.nearXidVersion() +
+                        ", node=" + nodeId +
+                        ", res=" + res +
+                        ", fut=" + this + ']');
+                }
+            }
+        }
+        else {
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("Near optimistic prepare fut, response for finished future [txId=" + tx.nearXidVersion() +
+                    ", node=" + nodeId +
+                    ", res=" + res +
+                    ", fut=" + this + ']');
+            }
         }
     }
 
@@ -480,6 +496,11 @@ public class GridNearOptimisticTxPrepareFuture extends GridNearOptimisticTxPrepa
             else {
                 try {
                     cctx.io().send(n, req, tx.ioPolicy());
+
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("Near optimistic prepare fut, sent request [txId=" + tx.nearXidVersion() +
+                            ", node=" + n.id() + ']');
+                    }
                 }
                 catch (ClusterTopologyCheckedException e) {
                     e.retryReadyFuture(cctx.nextAffinityReadyFuture(tx.topologyVersion()));
@@ -487,6 +508,12 @@ public class GridNearOptimisticTxPrepareFuture extends GridNearOptimisticTxPrepa
                     fut.onResult(e);
                 }
                 catch (IgniteCheckedException e) {
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("Near optimistic prepare fut, failed to sent request [txId=" + tx.nearXidVersion() +
+                            ", node=" + n.id() +
+                            ", err=" + e + ']');
+                    }
+
                     fut.onResult(e);
                 }
             }
@@ -687,6 +714,11 @@ public class GridNearOptimisticTxPrepareFuture extends GridNearOptimisticTxPrepa
          * @param e Node failure.
          */
         void onResult(ClusterTopologyCheckedException e) {
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("Near optimistic prepare fut, mini future node left [txId=" + tx.nearXidVersion() +
+                    ", node=" + m.node().id() + ']');
+            }
+
             if (isDone())
                 return;
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearPessimisticTxPrepareFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearPessimisticTxPrepareFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearPessimisticTxPrepareFuture.java
index 104af94..4fcfa66 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearPessimisticTxPrepareFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearPessimisticTxPrepareFuture.java
@@ -100,11 +100,24 @@ public class GridNearPessimisticTxPrepareFuture extends GridNearTxPrepareFutureA
             if (f != null) {
                 assert f.node().id().equals(nodeId);
 
-                if (log.isDebugEnabled())
-                    log.debug("Remote node left grid while sending or waiting for reply (will not retry): " + f);
-
                 f.onResult(res);
             }
+            else {
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Near pessimistic prepare, failed to find mini future [txId=" + tx.nearXidVersion() +
+                        ", node=" + nodeId +
+                        ", res=" + res +
+                        ", fut=" + this + ']');
+                }
+            }
+        }
+        else {
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("Near pessimistic prepare, response for finished future [txId=" + tx.nearXidVersion() +
+                    ", node=" + nodeId +
+                    ", res=" + res +
+                    ", fut=" + this + ']');
+            }
         }
     }
 
@@ -258,6 +271,11 @@ public class GridNearPessimisticTxPrepareFuture extends GridNearTxPrepareFutureA
             else {
                 try {
                     cctx.io().send(node, req, tx.ioPolicy());
+
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("Near pessimistic prepare, sent request [txId=" + tx.nearXidVersion() +
+                            ", node=" + node.id() + ']');
+                    }
                 }
                 catch (ClusterTopologyCheckedException e) {
                     e.retryReadyFuture(cctx.nextAffinityReadyFuture(topVer));
@@ -265,6 +283,11 @@ public class GridNearPessimisticTxPrepareFuture extends GridNearTxPrepareFutureA
                     fut.onNodeLeft(e);
                 }
                 catch (IgniteCheckedException e) {
+                    if (msgLog.isDebugEnabled()) {
+                        msgLog.debug("Near pessimistic prepare, failed send request [txId=" + tx.nearXidVersion() +
+                            ", node=" + node.id() + ", err=" + e + ']');
+                    }
+
                     fut.onError(e);
                 }
             }
@@ -363,6 +386,11 @@ public class GridNearPessimisticTxPrepareFuture extends GridNearTxPrepareFutureA
          * @param e Error.
          */
         void onNodeLeft(ClusterTopologyCheckedException e) {
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("Near pessimistic prepare, mini future node left [txId=" + tx.nearXidVersion() +
+                    ", nodeId=" + m.node().id() + ']');
+            }
+
             if (tx.onePhaseCommit()) {
                 tx.markForBackupCheck();
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishFuture.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishFuture.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishFuture.java
index 291c88a..400d23d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishFuture.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxFinishFuture.java
@@ -72,6 +72,9 @@ public final class GridNearTxFinishFuture<K, V> extends GridCompoundIdentityFutu
     /** Logger. */
     private static IgniteLogger log;
 
+    /** Logger. */
+    protected static IgniteLogger msgLog;
+
     /** Context. */
     private GridCacheSharedContext<K, V> cctx;
 
@@ -112,8 +115,10 @@ public final class GridNearTxFinishFuture<K, V> extends GridCompoundIdentityFutu
 
         futId = IgniteUuid.randomUuid();
 
-        if (log == null)
+        if (log == null) {
+            msgLog = cctx.txFinishMessageLogger();
             log = U.logger(cctx.kernalContext(), logRef, GridNearTxFinishFuture.class);
+        }
     }
 
     /** {@inheritDoc} */
@@ -140,6 +145,13 @@ public final class GridNearTxFinishFuture<K, V> extends GridCompoundIdentityFutu
         return false;
     }
 
+    /**
+     * @return Transaction.
+     */
+    public GridNearTxLocal tx() {
+        return tx;
+    }
+
     /** {@inheritDoc} */
     @Override public boolean trackable() {
         return trackable;
@@ -157,18 +169,38 @@ public final class GridNearTxFinishFuture<K, V> extends GridCompoundIdentityFutu
      * @param res Result.
      */
     public void onResult(UUID nodeId, GridNearTxFinishResponse res) {
-        if (!isDone())
+        if (!isDone()) {
+            boolean found = false;
+
             for (IgniteInternalFuture<IgniteInternalTx> fut : futures()) {
                 if (isMini(fut)) {
-                    MiniFuture f = (MiniFuture)fut;
+                    MiniFuture f = (MiniFuture) fut;
 
                     if (f.futureId().equals(res.miniId())) {
+                        found = true;
+
                         assert f.node().id().equals(nodeId);
 
                         f.onResult(res);
                     }
                 }
             }
+
+            if (!found && msgLog.isDebugEnabled()) {
+                msgLog.debug("Near finish fut, failed to find mini future [txId=" + tx.nearXidVersion() +
+                    ", node=" + nodeId +
+                    ", res=" + res +
+                    ", fut=" + this + ']');
+            }
+        }
+        else {
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("Near finish fut, response for finished future [txId=" + tx.nearXidVersion() +
+                    ", node=" + nodeId +
+                    ", res=" + res +
+                    ", fut=" + this + ']');
+            }
+        }
     }
 
     /**
@@ -176,18 +208,38 @@ public final class GridNearTxFinishFuture<K, V> extends GridCompoundIdentityFutu
      * @param res Result.
      */
     public void onResult(UUID nodeId, GridDhtTxFinishResponse res) {
-        if (!isDone())
+        if (!isDone()) {
+            boolean found = false;
+
             for (IgniteInternalFuture<IgniteInternalTx> fut : futures()) {
                 if (isMini(fut)) {
-                    MiniFuture f = (MiniFuture)fut;
+                    MiniFuture f = (MiniFuture) fut;
 
                     if (f.futureId().equals(res.miniId())) {
+                        found = true;
+
                         assert f.node().id().equals(nodeId);
 
                         f.onResult(res);
                     }
                 }
             }
+
+            if (!found && msgLog.isDebugEnabled()) {
+                msgLog.debug("Near finish fut, failed to find mini future [txId=" + tx.nearXidVersion() +
+                    ", node=" + nodeId +
+                    ", res=" + res +
+                    ", fut=" + this + ']');
+            }
+        }
+        else {
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("Near finish fut, response for finished future [txId=" + tx.nearXidVersion() +
+                    ", node=" + nodeId +
+                    ", res=" + res +
+                    ", fut=" + this + ']');
+            }
+        }
     }
 
     /** {@inheritDoc} */
@@ -455,8 +507,15 @@ public final class GridNearTxFinishFuture<K, V> extends GridCompoundIdentityFutu
                     finishReq.checkCommitted(true);
 
                     try {
-                        if (FINISH_NEAR_ONE_PHASE_SINCE.compareTo(backup.version()) <= 0)
+                        if (FINISH_NEAR_ONE_PHASE_SINCE.compareTo(backup.version()) <= 0) {
                             cctx.io().send(backup, finishReq, tx.ioPolicy());
+
+                            if (msgLog.isDebugEnabled()) {
+                                msgLog.debug("Near finish fut, sent check committed request [" +
+                                    "txId=" + tx.nearXidVersion() +
+                                    ", node=" + backup.id() + ']');
+                            }
+                        }
                         else
                             mini.onDone(new IgniteTxHeuristicCheckedException("Failed to check for tx commit on " +
                                 "the backup node (node has an old Ignite version) [rmtNodeId=" + backup.id() +
@@ -466,6 +525,13 @@ public final class GridNearTxFinishFuture<K, V> extends GridCompoundIdentityFutu
                         mini.onResult(e);
                     }
                     catch (IgniteCheckedException e) {
+                        if (msgLog.isDebugEnabled()) {
+                            msgLog.debug("Near finish fut, failed to send check committed request [" +
+                                "txId=" + tx.nearXidVersion() +
+                                ", node=" + backup.id() +
+                                ", err=" + e + ']');
+                        }
+
                         mini.onResult(e);
                     }
                 }
@@ -596,6 +662,12 @@ public final class GridNearTxFinishFuture<K, V> extends GridCompoundIdentityFutu
             try {
                 cctx.io().send(n, req, tx.ioPolicy());
 
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Near finish fut, sent request [" +
+                        "txId=" + tx.nearXidVersion() +
+                        ", node=" + n.id() + ']');
+                }
+
                 // If we don't wait for result, then mark future as done.
                 if (!isSync() && !m.explicitLock())
                     fut.onDone();
@@ -607,6 +679,13 @@ public final class GridNearTxFinishFuture<K, V> extends GridCompoundIdentityFutu
                 fut.onResult(e);
             }
             catch (IgniteCheckedException e) {
+                if (msgLog.isDebugEnabled()) {
+                    msgLog.debug("Near finish fut, failed to send request [" +
+                        "txId=" + tx.nearXidVersion() +
+                        ", node=" + n.id() +
+                        ", err=" + e + ']');
+                }
+
                 // Fail the whole thing.
                 fut.onResult(e);
             }
@@ -705,8 +784,10 @@ public final class GridNearTxFinishFuture<K, V> extends GridCompoundIdentityFutu
          * @param e Node failure.
          */
         void onResult(ClusterTopologyCheckedException e) {
-            if (log.isDebugEnabled())
-                log.debug("Remote node left grid while sending or waiting for reply (will fail): " + this);
+            if (msgLog.isDebugEnabled()) {
+                msgLog.debug("Near finish fut, mini future node left [txId=" + tx.nearXidVersion() +
+                    ", node=" + m.node().id() + ']');
+            }
 
             if (backup != null) {
                 readyNearMappingFromBackup(m);

http://git-wip-us.apache.org/repos/asf/ignite/blob/8ed13e84/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareFutureAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareFutureAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareFutureAdapter.java
index 6992aa5..f46af0d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareFutureAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/near/GridNearTxPrepareFutureAdapter.java
@@ -69,6 +69,9 @@ public abstract class GridNearTxPrepareFutureAdapter extends
     /** Logger. */
     protected static IgniteLogger log;
 
+    /** Logger. */
+    protected static IgniteLogger msgLog;
+
     /** Context. */
     protected GridCacheSharedContext<?, ?> cctx;
 
@@ -105,8 +108,10 @@ public abstract class GridNearTxPrepareFutureAdapter extends
 
         futId = IgniteUuid.randomUuid();
 
-        if (log == null)
+        if (log == null) {
+            msgLog = cctx.txFinishMessageLogger();
             log = U.logger(cctx.kernalContext(), logRef, GridNearTxPrepareFutureAdapter.class);
+        }
     }
 
     /** {@inheritDoc} */


[08/50] [abbrv] ignite git commit: ignite-3426: Compute Engine: job ID is generated in a non unique way

Posted by vo...@apache.org.
ignite-3426: Compute Engine: job ID is generated in a non unique way


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

Branch: refs/heads/ignite-1.5.31-1
Commit: d2524eb545bfa1eca91c6cf0316297e29ff17b8d
Parents: 5d9f899
Author: Denis Magda <dm...@gridgain.com>
Authored: Wed Jul 6 15:02:43 2016 +0300
Committer: Denis Magda <dm...@gridgain.com>
Committed: Wed Jul 6 15:02:43 2016 +0300

----------------------------------------------------------------------
 .../org/apache/ignite/internal/processors/task/GridTaskWorker.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/d2524eb5/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java
index fc56893..8ce005a 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java
@@ -561,7 +561,7 @@ class GridTaskWorker<T, R> extends GridWorker implements GridTimeoutObject {
             if (node == null)
                 throw new IgniteCheckedException("Node can not be null [mappedJob=" + mappedJob + ", ses=" + ses + ']');
 
-            IgniteUuid jobId = IgniteUuid.fromUuid(node.id());
+            IgniteUuid jobId = IgniteUuid.fromUuid(ctx.localNodeId());
 
             GridJobSiblingImpl sib = new GridJobSiblingImpl(ses.getId(), jobId, node.id(), ctx);
 


[31/50] [abbrv] ignite git commit: IGNITE-1849 minor fixes

Posted by vo...@apache.org.
IGNITE-1849 minor fixes


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 5ae31fa39758780ac279d4c1b0179b84405c11ac
Parents: 6f7df5e
Author: Alexander Paschenko <al...@gmail.com>
Authored: Mon Jul 18 14:09:46 2016 +0300
Committer: Alexander Paschenko <al...@gmail.com>
Committed: Mon Jul 18 14:09:46 2016 +0300

----------------------------------------------------------------------
 ...IgniteCacheInternalEventsIgnoreSelfTest.java | 61 ++++++++++++++++++++
 .../IgniteCacheInternalEventsIgnoreTest.java    | 53 -----------------
 .../testsuites/IgniteCacheTestSuite5.java       |  4 +-
 3 files changed, 63 insertions(+), 55 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/5ae31fa3/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheInternalEventsIgnoreSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheInternalEventsIgnoreSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheInternalEventsIgnoreSelfTest.java
new file mode 100644
index 0000000..e14a600
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheInternalEventsIgnoreSelfTest.java
@@ -0,0 +1,61 @@
+/*
+ * 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;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.cache.CachePeekMode;
+import org.apache.ignite.events.Event;
+import org.apache.ignite.events.EventType;
+import org.apache.ignite.lang.IgnitePredicate;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+/**
+ *
+ */
+public class IgniteCacheInternalEventsIgnoreSelfTest extends GridCommonAbstractTest {
+    /** */
+    private static final AtomicBoolean evtFlag = new AtomicBoolean();
+
+    /**
+     * @throws Exception if failed.
+     */
+    public void testInternalEventsIgnore() throws Exception {
+        Ignite ignite = startGrid(1);
+        ignite.events().localListen(new EventListener(), EventType.EVT_TASK_STARTED, EventType.EVT_TASK_REDUCED,
+            EventType.EVT_TASK_FINISHED);
+        IgniteCache cache = ignite.createCache(defaultCacheConfiguration().setName("myTestCache"));
+        cache.size(CachePeekMode.ALL);
+        cache.sizeLong(CachePeekMode.ALL);
+
+        assertFalse(evtFlag.get());
+    }
+
+    /**
+     *
+     */
+    private static final class EventListener implements IgnitePredicate<Event> {
+        /** {@inheritDoc} */
+        @Override public boolean apply(Event e) {
+            evtFlag.set(true);
+
+            return true;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/5ae31fa3/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheInternalEventsIgnoreTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheInternalEventsIgnoreTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheInternalEventsIgnoreTest.java
deleted file mode 100644
index e87206d..0000000
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/IgniteCacheInternalEventsIgnoreTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-import org.apache.ignite.Ignite;
-import org.apache.ignite.IgniteCache;
-import org.apache.ignite.cache.CachePeekMode;
-import org.apache.ignite.events.Event;
-import org.apache.ignite.events.EventType;
-import org.apache.ignite.lang.IgnitePredicate;
-import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
-
-/** */
-public class IgniteCacheInternalEventsIgnoreTest extends GridCommonAbstractTest {
-    /** */
-    private static final AtomicBoolean evtFlag = new AtomicBoolean();
-
-    /** */
-    public void testInternalEventsIgnore() throws Exception {
-        Ignite ignite = startGrid(1);
-        ignite.events().localListen(new EvtLsnr(), EventType.EVT_TASK_STARTED, EventType.EVT_TASK_REDUCED,
-            EventType.EVT_TASK_FINISHED);
-        IgniteCache cache = ignite.createCache(defaultCacheConfiguration().setName("myTestCache"));
-        cache.size(CachePeekMode.ALL);
-        cache.sizeLong(CachePeekMode.ALL);
-        assertFalse(evtFlag.get());
-    }
-
-    /** */
-    private static final class EvtLsnr implements IgnitePredicate<Event> {
-        /** {@inheritDoc} */
-        @Override public boolean apply(Event e) {
-            evtFlag.set(true);
-            return true;
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/ignite/blob/5ae31fa3/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite5.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite5.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite5.java
index af54f91..0341502 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite5.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite5.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
 import org.apache.ignite.internal.processors.cache.CacheNearReaderUpdateTest;
 import org.apache.ignite.internal.processors.cache.CacheSerializableTransactionsTest;
 import org.apache.ignite.internal.processors.cache.EntryVersionConsistencyReadThroughTest;
-import org.apache.ignite.internal.processors.cache.IgniteCacheInternalEventsIgnoreTest;
+import org.apache.ignite.internal.processors.cache.IgniteCacheInternalEventsIgnoreSelfTest;
 import org.apache.ignite.internal.processors.cache.IgniteCachePutStackOverflowSelfTest;
 import org.apache.ignite.internal.processors.cache.IgniteCacheStoreCollectionTest;
 import org.apache.ignite.internal.processors.cache.distributed.IgniteCacheTxIteratorSelfTest;
@@ -45,7 +45,7 @@ public class IgniteCacheTestSuite5 extends TestSuite {
         suite.addTestSuite(IgniteCachePutStackOverflowSelfTest.class);
         suite.addTestSuite(EntryVersionConsistencyReadThroughTest.class);
         suite.addTestSuite(IgniteCacheTxIteratorSelfTest.class);
-        suite.addTestSuite(IgniteCacheInternalEventsIgnoreTest.class);
+        suite.addTestSuite(IgniteCacheInternalEventsIgnoreSelfTest.class);
 
         return suite;
     }


[26/50] [abbrv] ignite git commit: Fixed NPE in OptimizedMarshaller when streams pool is used

Posted by vo...@apache.org.
Fixed NPE in OptimizedMarshaller when streams pool is used


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 27f6c5862940948669b6445a6839501327dacbb2
Parents: 4d2be72
Author: Valentin Kulichenko <va...@gmail.com>
Authored: Wed Jul 13 14:37:23 2016 -0700
Committer: Valentin Kulichenko <va...@gmail.com>
Committed: Wed Jul 13 14:37:23 2016 -0700

----------------------------------------------------------------------
 .../OptimizedObjectStreamRegistry.java          | 145 +++++++++++--------
 .../OptimizedMarshallerPooledSelfTest.java      |  44 ++++++
 .../testsuites/IgniteBinaryBasicTestSuite.java  |   2 +
 .../IgniteMarshallerSelfTestSuite.java          |   2 +
 4 files changed, 130 insertions(+), 63 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/27f6c586/modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedObjectStreamRegistry.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedObjectStreamRegistry.java b/modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedObjectStreamRegistry.java
index e0e4872..fd1b917 100644
--- a/modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedObjectStreamRegistry.java
+++ b/modules/core/src/main/java/org/apache/ignite/marshaller/optimized/OptimizedObjectStreamRegistry.java
@@ -33,8 +33,11 @@ class OptimizedObjectStreamRegistry {
     /** Holders. */
     private static final ThreadLocal<StreamHolder> holders = new ThreadLocal<>();
 
-    /** Holders pool. */
-    private static BlockingQueue<StreamHolder> pool;
+    /** Output streams pool. */
+    private static BlockingQueue<OptimizedObjectOutputStream> outPool;
+
+    /** Input streams pool. */
+    private static BlockingQueue<OptimizedObjectInputStream> inPool;
 
     /**
      * Ensures singleton.
@@ -50,16 +53,18 @@ class OptimizedObjectStreamRegistry {
      */
     static void poolSize(int size) {
         if (size > 0) {
-            pool = new LinkedBlockingQueue<>(size);
+            outPool = new LinkedBlockingQueue<>(size);
+            inPool = new LinkedBlockingQueue<>(size);
 
             for (int i = 0; i < size; i++) {
-                boolean b = pool.offer(new StreamHolder());
-
-                assert b;
+                outPool.offer(createOut());
+                inPool.offer(createIn());
             }
         }
-        else
-            pool = null;
+        else {
+            outPool = null;
+            inPool = null;
+        }
     }
 
     /**
@@ -69,7 +74,17 @@ class OptimizedObjectStreamRegistry {
      * @throws org.apache.ignite.internal.IgniteInterruptedCheckedException If thread is interrupted while trying to take holder from pool.
      */
     static OptimizedObjectOutputStream out() throws IgniteInterruptedCheckedException {
-        return holder().acquireOut();
+        if (outPool != null) {
+            try {
+                return outPool.take();
+            }
+            catch (InterruptedException e) {
+                throw new IgniteInterruptedCheckedException(
+                    "Failed to take output object stream from pool (thread interrupted).", e);
+            }
+        }
+        else
+            return holder().acquireOut();
     }
 
     /**
@@ -79,7 +94,17 @@ class OptimizedObjectStreamRegistry {
      * @throws org.apache.ignite.internal.IgniteInterruptedCheckedException If thread is interrupted while trying to take holder from pool.
      */
     static OptimizedObjectInputStream in() throws IgniteInterruptedCheckedException {
-        return holder().acquireIn();
+        if (inPool != null) {
+            try {
+                return inPool.take();
+            }
+            catch (InterruptedException e) {
+                throw new IgniteInterruptedCheckedException(
+                    "Failed to take input object stream from pool (thread interrupted).", e);
+            }
+        }
+        else
+            return holder().acquireIn();
     }
 
     /**
@@ -90,17 +115,17 @@ class OptimizedObjectStreamRegistry {
     static void closeOut(OptimizedObjectOutputStream out) {
         U.close(out, null);
 
-        StreamHolder holder = holders.get();
-
-        holder.releaseOut();
-
-        if (pool != null) {
-            holders.remove();
-
-            boolean b = pool.offer(holder);
+        if (outPool != null) {
+            boolean b = outPool.offer(out);
 
             assert b;
         }
+        else {
+            StreamHolder holder = holders.get();
+
+            if (holder != null)
+                holder.releaseOut();
+        }
     }
 
     /**
@@ -112,17 +137,17 @@ class OptimizedObjectStreamRegistry {
     static void closeIn(OptimizedObjectInputStream in) {
         U.close(in, null);
 
-        StreamHolder holder = holders.get();
-
-        holder.releaseIn();
-
-        if (pool != null) {
-            holders.remove();
-
-            boolean b = pool.offer(holder);
+        if (inPool != null) {
+            boolean b = inPool.offer(in);
 
             assert b;
         }
+        else {
+            StreamHolder holder = holders.get();
+
+            if (holder != null)
+                holder.releaseIn();
+        }
     }
 
     /**
@@ -134,19 +159,41 @@ class OptimizedObjectStreamRegistry {
     private static StreamHolder holder() throws IgniteInterruptedCheckedException {
         StreamHolder holder = holders.get();
 
-        if (holder == null) {
-            try {
-                holders.set(holder = pool != null ? pool.take() : new StreamHolder());
-            }
-            catch (InterruptedException e) {
-                throw new IgniteInterruptedCheckedException("Failed to take object stream from pool (thread interrupted).", e);
-            }
-        }
+        if (holder == null)
+            holders.set(holder = new StreamHolder());
 
         return holder;
     }
 
     /**
+     * Creates output stream.
+     *
+     * @return Object output stream.
+     */
+    private static OptimizedObjectOutputStream createOut() {
+        try {
+            return new OptimizedObjectOutputStream(new GridUnsafeDataOutput(4 * 1024));
+        }
+        catch (IOException e) {
+            throw new IgniteException("Failed to create object output stream.", e);
+        }
+    }
+
+    /**
+     * Creates input stream.
+     *
+     * @return Object input stream.
+     */
+    private static OptimizedObjectInputStream createIn() {
+        try {
+            return new OptimizedObjectInputStream(new GridUnsafeDataInput());
+        }
+        catch (IOException e) {
+            throw new IgniteException("Failed to create object input stream.", e);
+        }
+    }
+
+    /**
      * Streams holder.
      */
     private static class StreamHolder {
@@ -193,33 +240,5 @@ class OptimizedObjectStreamRegistry {
         void releaseIn() {
             inAcquireCnt--;
         }
-
-        /**
-         * Creates output stream.
-         *
-         * @return Object output stream.
-         */
-        private OptimizedObjectOutputStream createOut() {
-            try {
-                return new OptimizedObjectOutputStream(new GridUnsafeDataOutput(4 * 1024));
-            }
-            catch (IOException e) {
-                throw new IgniteException("Failed to create object output stream.", e);
-            }
-        }
-
-        /**
-         * Creates input stream.
-         *
-         * @return Object input stream.
-         */
-        private OptimizedObjectInputStream createIn() {
-            try {
-                return new OptimizedObjectInputStream(new GridUnsafeDataInput());
-            }
-            catch (IOException e) {
-                throw new IgniteException("Failed to create object input stream.", e);
-            }
-        }
     }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/27f6c586/modules/core/src/test/java/org/apache/ignite/marshaller/optimized/OptimizedMarshallerPooledSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/marshaller/optimized/OptimizedMarshallerPooledSelfTest.java b/modules/core/src/test/java/org/apache/ignite/marshaller/optimized/OptimizedMarshallerPooledSelfTest.java
new file mode 100644
index 0000000..a883270
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/marshaller/optimized/OptimizedMarshallerPooledSelfTest.java
@@ -0,0 +1,44 @@
+/*
+ * 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.marshaller.optimized;
+
+import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.testframework.junits.common.GridCommonTest;
+
+/**
+ * Optimized marshaller self test.
+ */
+@GridCommonTest(group = "Marshaller")
+public class OptimizedMarshallerPooledSelfTest extends OptimizedMarshallerSelfTest {
+    /** {@inheritDoc} */
+    @Override protected Marshaller marshaller() {
+        OptimizedMarshaller m = new OptimizedMarshaller(false);
+
+        m.setPoolSize(8);
+
+        return m;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        super.afterTestsStopped();
+
+        // Reset static registry.
+        new OptimizedMarshaller().setPoolSize(0);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/27f6c586/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryBasicTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryBasicTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryBasicTestSuite.java
index 2aabf4f..734e199 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryBasicTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBinaryBasicTestSuite.java
@@ -40,6 +40,7 @@ import org.apache.ignite.marshaller.DynamicProxySerializationMultiJvmSelfTest;
 import org.apache.ignite.marshaller.jdk.GridJdkMarshallerSelfTest;
 import org.apache.ignite.marshaller.optimized.OptimizedMarshallerEnumSelfTest;
 import org.apache.ignite.marshaller.optimized.OptimizedMarshallerNodeFailoverTest;
+import org.apache.ignite.marshaller.optimized.OptimizedMarshallerPooledSelfTest;
 import org.apache.ignite.marshaller.optimized.OptimizedMarshallerSelfTest;
 import org.apache.ignite.marshaller.optimized.OptimizedMarshallerSerialPersistentFieldsSelfTest;
 import org.apache.ignite.marshaller.optimized.OptimizedMarshallerTest;
@@ -88,6 +89,7 @@ public class IgniteBinaryBasicTestSuite extends TestSuite {
         ignoredTests.add(GridDeploymentMessageCountSelfTest.class);
         ignoredTests.add(DynamicProxySerializationMultiJvmSelfTest.class);
         ignoredTests.add(GridHandleTableSelfTest.class);
+        ignoredTests.add(OptimizedMarshallerPooledSelfTest.class);
 
         // TODO: check and delete if pass.
         ignoredTests.add(IgniteDaemonNodeMarshallerCacheTest.class);

http://git-wip-us.apache.org/repos/asf/ignite/blob/27f6c586/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMarshallerSelfTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMarshallerSelfTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMarshallerSelfTestSuite.java
index ec0ec23..99cbf60 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMarshallerSelfTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteMarshallerSelfTestSuite.java
@@ -24,6 +24,7 @@ import org.apache.ignite.internal.util.io.GridUnsafeDataOutputArraySizingSelfTes
 import org.apache.ignite.marshaller.jdk.GridJdkMarshallerSelfTest;
 import org.apache.ignite.marshaller.optimized.OptimizedMarshallerEnumSelfTest;
 import org.apache.ignite.marshaller.optimized.OptimizedMarshallerNodeFailoverTest;
+import org.apache.ignite.marshaller.optimized.OptimizedMarshallerPooledSelfTest;
 import org.apache.ignite.marshaller.optimized.OptimizedMarshallerSelfTest;
 import org.apache.ignite.marshaller.optimized.OptimizedMarshallerSerialPersistentFieldsSelfTest;
 import org.apache.ignite.marshaller.optimized.OptimizedMarshallerTest;
@@ -59,6 +60,7 @@ public class IgniteMarshallerSelfTestSuite extends TestSuite {
         GridTestUtils.addTestIfNeeded(suite, OptimizedMarshallerNodeFailoverTest.class, ignoredTests);
         GridTestUtils.addTestIfNeeded(suite, OptimizedMarshallerSerialPersistentFieldsSelfTest.class, ignoredTests);
         GridTestUtils.addTestIfNeeded(suite, GridHandleTableSelfTest.class, ignoredTests);
+        GridTestUtils.addTestIfNeeded(suite, OptimizedMarshallerPooledSelfTest.class, ignoredTests);
 
         return suite;
     }


[48/50] [abbrv] ignite git commit: IGNITE-2649: Ensured correct local Ignite instance processing during serialization and deserialization.

Posted by vo...@apache.org.
IGNITE-2649: Ensured correct local Ignite instance processing during serialization and deserialization.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: e5f3abd25e57b5cd206b8c4dcdbc9367cb118570
Parents: 2b1c82c
Author: vozerov-gridgain <vo...@gridgain.com>
Authored: Mon Aug 29 10:39:45 2016 +0300
Committer: vozerov-gridgain <vo...@gridgain.com>
Committed: Mon Aug 29 10:39:46 2016 +0300

----------------------------------------------------------------------
 .../socket/WordsSocketStreamerServer.java       |   2 +-
 .../rest/protocols/tcp/MockNioSession.java      |   8 +-
 .../rendezvous/RendezvousAffinityFunction.java  |  35 +-
 .../cache/store/jdbc/CacheJdbcBlobStore.java    |   5 +-
 .../internal/GridEventConsumeHandler.java       |  31 +-
 .../internal/GridJobSiblingsResponse.java       |   6 +-
 .../internal/GridMessageListenHandler.java      |  14 +-
 .../org/apache/ignite/internal/IgnitionEx.java  |  12 +-
 .../internal/binary/BinaryEnumObjectImpl.java   |   3 +-
 .../internal/binary/BinaryMarshaller.java       |  10 -
 .../internal/binary/BinaryReaderExImpl.java     |  23 ++
 .../ignite/internal/binary/BinaryUtils.java     |   4 +-
 .../internal/binary/BinaryWriterExImpl.java     |  20 +-
 .../client/GridClientConfiguration.java         |   1 -
 .../checkpoint/GridCheckpointManager.java       |  11 +-
 .../managers/communication/GridIoManager.java   |  13 +-
 .../deployment/GridDeploymentCommunication.java |   6 +-
 .../eventstorage/GridEventStorageManager.java   |  22 +-
 .../swapspace/GridSwapSpaceManager.java         |   5 +-
 .../processors/affinity/GridAffinityUtils.java  |   5 +-
 .../cache/CacheEntrySerializablePredicate.java  |   7 +-
 .../cache/CacheInvokeDirectResult.java          |  10 +-
 .../processors/cache/GridCacheMessage.java      |  13 +-
 .../processors/cache/GridCacheProcessor.java    |   7 +-
 .../processors/cache/GridCacheUtils.java        |  16 +-
 .../GridDistributedLockResponse.java            |  10 +-
 .../GridDistributedTxPrepareRequest.java        |   7 +-
 .../GridDistributedTxPrepareResponse.java       |  10 +-
 .../dht/GridDhtAffinityAssignmentResponse.java  |   7 +-
 .../dht/GridDhtTxFinishResponse.java            |  10 +-
 .../dht/atomic/GridDhtAtomicUpdateResponse.java |   7 +-
 .../dht/atomic/GridNearAtomicUpdateRequest.java |   9 +-
 .../atomic/GridNearAtomicUpdateResponse.java    |  10 +-
 .../dht/preloader/GridDhtForceKeysResponse.java |  10 +-
 .../GridDhtPartitionDemandMessage.java          |  10 +-
 .../preloader/GridDhtPartitionsFullMessage.java |  18 +-
 .../GridDhtPartitionsSingleMessage.java         |  18 +-
 .../distributed/near/GridNearGetResponse.java   |  10 +-
 .../near/GridNearSingleGetResponse.java         |  10 +-
 .../near/GridNearTxFinishResponse.java          |  10 +-
 .../cache/query/GridCacheLocalQueryFuture.java  |   5 +-
 .../cache/query/GridCacheQueryRequest.java      |  28 +-
 .../cache/query/GridCacheQueryResponse.java     |  10 +-
 .../cache/query/GridCacheSqlQuery.java          |   9 +-
 .../continuous/CacheContinuousQueryHandler.java |   6 +-
 .../jdbc/GridCacheQueryJdbcMetadataTask.java    |   5 +-
 .../query/jdbc/GridCacheQueryJdbcTask.java      |   8 +-
 .../cache/transactions/IgniteTxEntry.java       |  11 +-
 .../version/GridCacheRawVersionedEntry.java     |  11 +-
 .../IgniteCacheObjectProcessorImpl.java         |   5 +-
 .../closure/GridClosureProcessor.java           |  11 +-
 .../continuous/GridContinuousProcessor.java     |  13 +-
 .../processors/continuous/StartRequestData.java |  13 +-
 .../datastreamer/DataStreamProcessor.java       |  11 +-
 .../datastreamer/DataStreamerImpl.java          |   8 +-
 .../processors/igfs/IgfsAckMessage.java         |  15 +-
 .../igfs/IgfsCommunicationMessage.java          |   8 +-
 .../internal/processors/igfs/IgfsContext.java   |   4 +-
 .../processors/igfs/IgfsDataManager.java        |   2 +-
 .../processors/igfs/IgfsDeleteMessage.java      |  15 +-
 .../igfs/IgfsFragmentizerManager.java           |   2 +-
 .../internal/processors/igfs/IgfsImpl.java      |   2 +-
 .../internal/processors/igfs/IgfsPaths.java     |   7 +-
 .../processors/job/GridJobProcessor.java        |  28 +-
 .../internal/processors/job/GridJobWorker.java  |  10 +-
 .../offheap/GridOffHeapProcessor.java           |   5 +-
 .../handlers/task/GridTaskCommandHandler.java   |   9 +-
 .../rest/protocols/tcp/GridTcpRestParser.java   |  26 +-
 .../service/GridServiceProcessor.java           |  15 +-
 .../processors/task/GridTaskProcessor.java      |  10 +-
 .../processors/task/GridTaskWorker.java         |  17 +-
 .../ignite/internal/util/IgniteUtils.java       |  55 ++-
 .../internal/util/ipc/IpcToNioAdapter.java      |   6 +-
 .../ignite/internal/util/nio/GridNioServer.java |   8 +-
 .../internal/util/nio/GridNioSession.java       |   6 +
 .../internal/util/nio/GridNioSessionImpl.java   |  13 +-
 .../util/nio/GridSelectorNioSessionImpl.java    |   6 +-
 .../ignite/marshaller/AbstractMarshaller.java   |  41 +-
 .../ignite/marshaller/MarshallerUtils.java      | 157 ++++++++
 .../ignite/marshaller/jdk/JdkMarshaller.java    |  32 ++
 .../sharedfs/SharedFsCheckpointSpi.java         |   6 +-
 .../sharedfs/SharedFsTimeoutTask.java           |  10 +-
 .../spi/checkpoint/sharedfs/SharedFsUtils.java  |  13 +-
 .../communication/tcp/TcpCommunicationSpi.java  |   1 +
 .../ignite/spi/discovery/tcp/ClientImpl.java    |  17 +-
 .../ignite/spi/discovery/tcp/ServerImpl.java    |  44 ++-
 .../spi/discovery/tcp/TcpDiscoveryImpl.java     |  27 ++
 .../spi/discovery/tcp/TcpDiscoverySpi.java      |  14 +-
 .../TcpDiscoveryMulticastIpFinder.java          |  28 +-
 .../TcpDiscoveryCustomEventMessage.java         |  22 +-
 .../spi/swapspace/file/FileSwapSpaceSpi.java    |   3 +-
 .../stream/socket/SocketMessageConverter.java   |   3 +-
 .../ignite/stream/socket/SocketStreamer.java    |   7 +-
 .../cache/GridLocalIgniteSerializationTest.java | 373 +++++++++++++++++++
 .../nio/impl/GridNioFilterChainSelfTest.java    |   5 +
 .../spi/discovery/tcp/TcpDiscoverySelfTest.java |   2 +-
 .../stream/socket/SocketStreamerSelfTest.java   |   4 +-
 .../ignite/testsuites/IgniteBasicTestSuite.java |   2 +
 .../HadoopExternalCommunication.java            |   1 +
 .../communication/HadoopIpcToNioAdapter.java    |   5 +-
 .../communication/HadoopMarshallerFilter.java   |   6 +-
 .../processors/query/h2/IgniteH2Indexing.java   |  15 +-
 .../h2/twostep/GridReduceQueryExecutor.java     |   2 +-
 .../cache/websession/WebSessionFilter.java      |  12 +-
 .../ignite/cache/websession/WebSessionV2.java   |  11 +-
 105 files changed, 1333 insertions(+), 398 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/examples/src/main/java/org/apache/ignite/examples/streaming/wordcount/socket/WordsSocketStreamerServer.java
----------------------------------------------------------------------
diff --git a/examples/src/main/java/org/apache/ignite/examples/streaming/wordcount/socket/WordsSocketStreamerServer.java b/examples/src/main/java/org/apache/ignite/examples/streaming/wordcount/socket/WordsSocketStreamerServer.java
index 814d235..b104b34 100644
--- a/examples/src/main/java/org/apache/ignite/examples/streaming/wordcount/socket/WordsSocketStreamerServer.java
+++ b/examples/src/main/java/org/apache/ignite/examples/streaming/wordcount/socket/WordsSocketStreamerServer.java
@@ -99,7 +99,7 @@ public class WordsSocketStreamerServer {
 
         // Converter from zero-terminated string to Java strings.
         sockStmr.setConverter(new SocketMessageConverter<String>() {
-            @Override public String convert(byte[] msg) {
+            @Override public String convert(byte[] msg, String gridName) {
                 try {
                     return new String(msg, "ASCII");
                 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/MockNioSession.java
----------------------------------------------------------------------
diff --git a/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/MockNioSession.java b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/MockNioSession.java
index c82c73e..49fa88d 100644
--- a/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/MockNioSession.java
+++ b/modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/protocols/tcp/MockNioSession.java
@@ -17,7 +17,6 @@
 
 package org.apache.ignite.internal.processors.rest.protocols.tcp;
 
-import java.net.InetSocketAddress;
 import org.apache.ignite.internal.util.lang.GridMetadataAwareAdapter;
 import org.apache.ignite.internal.util.nio.GridNioFinishedFuture;
 import org.apache.ignite.internal.util.nio.GridNioFuture;
@@ -25,6 +24,8 @@ import org.apache.ignite.internal.util.nio.GridNioRecoveryDescriptor;
 import org.apache.ignite.internal.util.nio.GridNioSession;
 import org.jetbrains.annotations.Nullable;
 
+import java.net.InetSocketAddress;
+
 /**
  * Mock nio session with disabled functionality for testing parser.
  */
@@ -139,4 +140,9 @@ public class MockNioSession extends GridMetadataAwareAdapter implements GridNioS
     @Nullable @Override public GridNioRecoveryDescriptor recoveryDescriptor() {
         return null;
     }
+
+    /** {@inheritDoc} */
+    @Override public String gridName() {
+        return null;
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/cache/affinity/rendezvous/RendezvousAffinityFunction.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/cache/affinity/rendezvous/RendezvousAffinityFunction.java b/modules/core/src/main/java/org/apache/ignite/cache/affinity/rendezvous/RendezvousAffinityFunction.java
index 37258d4..1b90581 100644
--- a/modules/core/src/main/java/org/apache/ignite/cache/affinity/rendezvous/RendezvousAffinityFunction.java
+++ b/modules/core/src/main/java/org/apache/ignite/cache/affinity/rendezvous/RendezvousAffinityFunction.java
@@ -17,21 +17,6 @@
 
 package org.apache.ignite.cache.affinity.rendezvous;
 
-import java.io.ByteArrayOutputStream;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.io.Serializable;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
 import org.apache.ignite.Ignite;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteException;
@@ -49,10 +34,27 @@ import org.apache.ignite.internal.util.typedef.internal.LT;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteBiPredicate;
 import org.apache.ignite.lang.IgniteBiTuple;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.resources.IgniteInstanceResource;
 import org.apache.ignite.resources.LoggerResource;
 import org.jetbrains.annotations.Nullable;
 
+import java.io.ByteArrayOutputStream;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.io.Serializable;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
 /**
  * Affinity function for partitioned cache based on Highest Random Weight algorithm.
  * This function supports the following configuration:
@@ -335,7 +337,8 @@ public class RendezvousAffinityFunction implements AffinityFunction, Externaliza
             try {
                 ByteArrayOutputStream out = new ByteArrayOutputStream();
 
-                byte[] nodeHashBytes = ignite.configuration().getMarshaller().marshal(nodeHash);
+                byte[] nodeHashBytes =
+                    MarshallerUtils.marshal(ignite.name(), ignite.configuration().getMarshaller(), nodeHash);
 
                 out.write(U.intToBytes(part), 0, 4); // Avoid IOException.
                 out.write(nodeHashBytes, 0, nodeHashBytes.length); // Avoid IOException.

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/cache/store/jdbc/CacheJdbcBlobStore.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/cache/store/jdbc/CacheJdbcBlobStore.java b/modules/core/src/main/java/org/apache/ignite/cache/store/jdbc/CacheJdbcBlobStore.java
index 147f6c9..15aa111 100644
--- a/modules/core/src/main/java/org/apache/ignite/cache/store/jdbc/CacheJdbcBlobStore.java
+++ b/modules/core/src/main/java/org/apache/ignite/cache/store/jdbc/CacheJdbcBlobStore.java
@@ -44,6 +44,7 @@ import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.resources.CacheStoreSessionResource;
 import org.apache.ignite.resources.IgniteInstanceResource;
@@ -560,7 +561,7 @@ public class CacheJdbcBlobStore<K, V> extends CacheStoreAdapter<K, V> {
      * @throws IgniteCheckedException If failed to convert.
      */
     protected byte[] toBytes(Object obj) throws IgniteCheckedException {
-        return marsh.marshal(obj);
+        return MarshallerUtils.marshal(ignite.name(), marsh, obj);
     }
 
     /**
@@ -575,7 +576,7 @@ public class CacheJdbcBlobStore<K, V> extends CacheStoreAdapter<K, V> {
         if (bytes == null || bytes.length == 0)
             return null;
 
-        return marsh.unmarshal(bytes, getClass().getClassLoader());
+        return MarshallerUtils.unmarshal(ignite.name(), marsh, bytes, getClass().getClassLoader());
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/GridEventConsumeHandler.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridEventConsumeHandler.java b/modules/core/src/main/java/org/apache/ignite/internal/GridEventConsumeHandler.java
index 19bf1a7..243d5f2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridEventConsumeHandler.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridEventConsumeHandler.java
@@ -50,7 +50,7 @@ import org.apache.ignite.internal.util.typedef.T3;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteBiPredicate;
 import org.apache.ignite.lang.IgnitePredicate;
-import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.jetbrains.annotations.Nullable;
 
 import static org.apache.ignite.events.EventType.EVTS_ALL;
@@ -219,7 +219,7 @@ class GridEventConsumeHandler implements GridContinuousHandler {
 
                                                         if (cctx.deploymentEnabled() &&
                                                             ctx.discovery().cacheNode(node, cacheName)) {
-                                                            wrapper.p2pMarshal(ctx.config().getMarshaller());
+                                                            wrapper.p2pMarshal(ctx);
 
                                                             wrapper.cacheName = cacheName;
 
@@ -338,7 +338,7 @@ class GridEventConsumeHandler implements GridContinuousHandler {
                 }
 
                 try {
-                    wrapper.p2pUnmarshal(ctx.config().getMarshaller(), U.resolveClassLoader(ldr, ctx.config()));
+                    wrapper.p2pUnmarshal(ctx, U.resolveClassLoader(ldr, ctx.config()));
                 }
                 catch (IgniteCheckedException e) {
                     U.error(ctx.log(getClass()), "Failed to unmarshal event.", e);
@@ -370,7 +370,7 @@ class GridEventConsumeHandler implements GridContinuousHandler {
 
             depInfo = new GridDeploymentInfoBean(dep);
 
-            filterBytes = ctx.config().getMarshaller().marshal(filter);
+            filterBytes = MarshallerUtils.marshal(ctx, filter);
         }
     }
 
@@ -387,7 +387,8 @@ class GridEventConsumeHandler implements GridContinuousHandler {
             if (dep == null)
                 throw new IgniteDeploymentCheckedException("Failed to obtain deployment for class: " + clsName);
 
-            filter = ctx.config().getMarshaller().unmarshal(filterBytes, U.resolveClassLoader(dep.classLoader(), ctx.config()));
+            filter = MarshallerUtils.unmarshal(ctx.gridName(), ctx.config().getMarshaller(), filterBytes,
+                U.resolveClassLoader(dep.classLoader(), ctx.config()));
         }
     }
 
@@ -484,27 +485,27 @@ class GridEventConsumeHandler implements GridContinuousHandler {
         }
 
         /**
-         * @param marsh Marshaller.
-         * @throws IgniteCheckedException In case of error.
+         * @param ctx Kernal context.
+         * @throws IgniteCheckedException
          */
-        void p2pMarshal(Marshaller marsh) throws IgniteCheckedException {
-            assert marsh != null;
+        void p2pMarshal(final GridKernalContext ctx) throws IgniteCheckedException {
+            assert ctx.config().getMarshaller() != null;
 
-            bytes = marsh.marshal(evt);
+            bytes = MarshallerUtils.marshal(ctx, evt);
         }
 
         /**
-         * @param marsh Marshaller.
+         * @param ctx Kernal context.
          * @param ldr Class loader.
-         * @throws IgniteCheckedException In case of error.
+         * @throws IgniteCheckedException
          */
-        void p2pUnmarshal(Marshaller marsh, @Nullable ClassLoader ldr) throws IgniteCheckedException {
-            assert marsh != null;
+        void p2pUnmarshal(final GridKernalContext ctx, @Nullable ClassLoader ldr) throws IgniteCheckedException {
+            assert ctx.config().getMarshaller() != null;
 
             assert evt == null;
             assert bytes != null;
 
-            evt = marsh.unmarshal(bytes, ldr);
+            evt = MarshallerUtils.unmarshal(ctx.gridName(), ctx.config().getMarshaller(), bytes, ldr);
         }
 
         /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsResponse.java
index aa81cc5..55f332b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridJobSiblingsResponse.java
@@ -24,6 +24,7 @@ import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.compute.ComputeJobSibling;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.Message;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
@@ -68,13 +69,14 @@ public class GridJobSiblingsResponse implements Message {
 
     /**
      * @param marsh Marshaller.
+     * @param ctx kernal context.
      * @throws IgniteCheckedException In case of error.
      */
-    public void unmarshalSiblings(Marshaller marsh) throws IgniteCheckedException {
+    public void unmarshalSiblings(Marshaller marsh, final GridKernalContext ctx) throws IgniteCheckedException {
         assert marsh != null;
 
         if (siblingsBytes != null)
-            siblings = marsh.unmarshal(siblingsBytes, null);
+            siblings = MarshallerUtils.unmarshal(ctx.gridName(), marsh, siblingsBytes, null);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/GridMessageListenHandler.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/GridMessageListenHandler.java b/modules/core/src/main/java/org/apache/ignite/internal/GridMessageListenHandler.java
index 0ac6877..3d1f399 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/GridMessageListenHandler.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/GridMessageListenHandler.java
@@ -35,6 +35,7 @@ import org.apache.ignite.internal.util.lang.GridPeerDeployAware;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteBiPredicate;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.jetbrains.annotations.Nullable;
 
 /**
@@ -159,9 +160,9 @@ public class GridMessageListenHandler implements GridContinuousHandler {
         assert ctx.config().isPeerClassLoadingEnabled();
 
         if (topic != null)
-            topicBytes = ctx.config().getMarshaller().marshal(topic);
+            topicBytes = MarshallerUtils.marshal(ctx, topic);
 
-        predBytes = ctx.config().getMarshaller().marshal(pred);
+        predBytes = MarshallerUtils.marshal(ctx, pred);
 
         // Deploy only listener, as it is very likely to be of some user class.
         GridPeerDeployAware pda = U.peerDeployAware(pred);
@@ -192,10 +193,13 @@ public class GridMessageListenHandler implements GridContinuousHandler {
 
         ClassLoader ldr = dep.classLoader();
 
-        if (topicBytes != null)
-            topic = ctx.config().getMarshaller().unmarshal(topicBytes, U.resolveClassLoader(ldr, ctx.config()));
+        if (topicBytes != null) {
+            topic = MarshallerUtils.unmarshal(ctx.gridName(), ctx.config().getMarshaller(), topicBytes,
+                U.resolveClassLoader(ldr, ctx.config()));
+        }
 
-        pred = ctx.config().getMarshaller().unmarshal(predBytes, U.resolveClassLoader(ldr, ctx.config()));
+        pred = MarshallerUtils.unmarshal(ctx.gridName(), ctx.config().getMarshaller(), predBytes,
+            U.resolveClassLoader(ldr, ctx.config()));
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java b/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
index 6f5b9a6..5e55706 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/IgnitionEx.java
@@ -1279,17 +1279,21 @@ public class IgnitionEx {
     }
 
     /**
-     * Gets the grid, which is owner of current thread. An Exception is thrown if
-     * current thread is not an {@link IgniteThread}.
+     * Gets a name of the grid from thread local config, which is owner of current thread.
      *
      * @return Grid instance related to current thread
      * @throws IllegalArgumentException Thrown to indicate, that current thread is not an {@link IgniteThread}.
      */
     public static IgniteKernal localIgnite() throws IllegalArgumentException {
-        if (Thread.currentThread() instanceof IgniteThread)
+        String name = U.getCurrentIgniteName();
+
+        if (U.isCurrentIgniteNameSet(name))
+            return gridx(name);
+        else if (Thread.currentThread() instanceof IgniteThread)
             return gridx(((IgniteThread)Thread.currentThread()).getGridName());
         else
-            throw new IllegalArgumentException("This method should be accessed under " + IgniteThread.class.getName());
+            throw new IllegalArgumentException("Ignite grid name thread local must be set or" +
+                " this method should be accessed under " + IgniteThread.class.getName());
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryEnumObjectImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryEnumObjectImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryEnumObjectImpl.java
index afd0bdc..0f9e2e5 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryEnumObjectImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryEnumObjectImpl.java
@@ -33,6 +33,7 @@ import org.apache.ignite.internal.processors.cache.CacheObject;
 import org.apache.ignite.internal.processors.cache.CacheObjectContext;
 import org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl;
 import org.apache.ignite.internal.util.typedef.internal.SB;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
 import org.jetbrains.annotations.Nullable;
@@ -243,7 +244,7 @@ public class BinaryEnumObjectImpl implements BinaryObjectEx, Externalizable, Cac
 
     /** {@inheritDoc} */
     @Override public byte[] valueBytes(CacheObjectContext cacheCtx) throws IgniteCheckedException {
-        return ctx.marshaller().marshal(this);
+        return MarshallerUtils.marshal(ctx.configuration().getGridName(), ctx.marshaller(), this);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryMarshaller.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryMarshaller.java
index 5480967..1cbc9ad 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryMarshaller.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryMarshaller.java
@@ -26,7 +26,6 @@ import org.apache.ignite.binary.BinaryObjectException;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.util.GridUnsafe;
 import org.apache.ignite.marshaller.AbstractMarshaller;
-import org.apache.ignite.marshaller.MarshallerContext;
 import org.jetbrains.annotations.Nullable;
 import sun.misc.Unsafe;
 
@@ -70,15 +69,6 @@ public class BinaryMarshaller extends AbstractMarshaller {
     }
 
     /**
-     * Returns currently set {@link MarshallerContext}.
-     *
-     * @return Marshaller context.
-     */
-    public MarshallerContext getContext() {
-        return ctx;
-    }
-
-    /**
      * Sets {@link BinaryContext}.
      * <p/>
      * @param ctx Binary context.

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryReaderExImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryReaderExImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryReaderExImpl.java
index 9e7a1b3..3481ca3 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryReaderExImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryReaderExImpl.java
@@ -34,6 +34,7 @@ import org.apache.ignite.binary.BinaryObjectException;
 import org.apache.ignite.binary.BinaryRawReader;
 import org.apache.ignite.binary.BinaryReader;
 import org.apache.ignite.internal.binary.streams.BinaryInputStream;
+import org.apache.ignite.internal.util.IgniteUtils;
 import org.apache.ignite.internal.util.typedef.internal.SB;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -1420,6 +1421,21 @@ public class BinaryReaderExImpl implements BinaryReader, BinaryRawReaderEx, Bina
      * @throws BinaryObjectException If failed.
      */
     @Nullable Object deserialize() throws BinaryObjectException {
+        String oldName = IgniteUtils.setCurrentIgniteName(ctx.configuration().getGridName());
+
+        try {
+            return deserialize0();
+        }
+        finally {
+            IgniteUtils.restoreCurrentIgniteName(oldName);
+        }
+    }
+
+    /**
+     * @return Deserialized object.
+     * @throws BinaryObjectException If failed.
+     */
+    @Nullable private Object deserialize0() throws BinaryObjectException {
         Object obj;
 
         byte flag = in.readByte();
@@ -2028,6 +2044,13 @@ public class BinaryReaderExImpl implements BinaryReader, BinaryRawReaderEx, Bina
     }
 
     /**
+     * @return Binary context.
+     */
+    public BinaryContext context() {
+        return ctx;
+    }
+
+    /**
      * Flag.
      */
     private enum Flag {

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryUtils.java
index b6a95fb..5b048cd 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryUtils.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryUtils.java
@@ -61,6 +61,7 @@ import org.apache.ignite.internal.binary.streams.BinaryInputStream;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteBiTuple;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.lang.IgniteUuid;
 import org.jetbrains.annotations.Nullable;
 import org.jsr166.ConcurrentHashMap8;
@@ -1589,7 +1590,8 @@ public class BinaryUtils {
         ByteArrayInputStream input = new ByteArrayInputStream(in.array(), in.position(), len);
 
         try {
-            return ctx.optimizedMarsh().unmarshal(input, U.resolveClassLoader(clsLdr, ctx.configuration()));
+            return MarshallerUtils.unmarshal(ctx.configuration().getGridName(), ctx.optimizedMarsh(), input,
+                U.resolveClassLoader(clsLdr, ctx.configuration()));
         }
         catch (IgniteCheckedException e) {
             throw new BinaryObjectException("Failed to unmarshal object with optimized marshaller", e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java
index 30710f4..b3963d8 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryWriterExImpl.java
@@ -35,7 +35,9 @@ import org.apache.ignite.binary.BinaryRawWriter;
 import org.apache.ignite.binary.BinaryWriter;
 import org.apache.ignite.internal.binary.streams.BinaryHeapOutputStream;
 import org.apache.ignite.internal.binary.streams.BinaryOutputStream;
+import org.apache.ignite.internal.util.IgniteUtils;
 import org.apache.ignite.internal.util.typedef.internal.A;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.jetbrains.annotations.Nullable;
 
 import static java.nio.charset.StandardCharsets.UTF_8;
@@ -138,6 +140,22 @@ public class BinaryWriterExImpl implements BinaryWriter, BinaryRawWriterEx, Obje
      * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
      */
     void marshal(Object obj, boolean enableReplace) throws BinaryObjectException {
+        String oldName = IgniteUtils.setCurrentIgniteName(ctx.configuration().getGridName());
+
+        try {
+            marshal0(obj, enableReplace);
+        }
+        finally {
+            IgniteUtils.restoreCurrentIgniteName(oldName);
+        }
+    }
+
+    /**
+     * @param obj Object.
+     * @param enableReplace Object replacing enabled flag.
+     * @throws org.apache.ignite.binary.BinaryObjectException In case of error.
+     */
+    private void marshal0(Object obj, boolean enableReplace) throws BinaryObjectException {
         assert obj != null;
 
         Class<?> cls = obj.getClass();
@@ -157,7 +175,7 @@ public class BinaryWriterExImpl implements BinaryWriter, BinaryRawWriterEx, Obje
             out.writeByte(GridBinaryMarshaller.OPTM_MARSH);
 
             try {
-                byte[] arr = ctx.optimizedMarsh().marshal(obj);
+                byte[] arr = MarshallerUtils.marshal(ctx.configuration().getGridName(), ctx.optimizedMarsh(), obj);
 
                 writeInt(arr.length);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/client/GridClientConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/client/GridClientConfiguration.java b/modules/core/src/main/java/org/apache/ignite/internal/client/GridClientConfiguration.java
index e9d2958..cac1bb3 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/client/GridClientConfiguration.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/client/GridClientConfiguration.java
@@ -157,7 +157,6 @@ public class GridClientConfiguration {
         tcpNoDelay = cfg.isTcpNoDelay();
         topRefreshFreq = cfg.getTopologyRefreshFrequency();
         daemon = cfg.isDaemon();
-        marshaller = cfg.getMarshaller();
 
         setDataConfigurations(cfg.getDataConfigurations());
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/managers/checkpoint/GridCheckpointManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/checkpoint/GridCheckpointManager.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/checkpoint/GridCheckpointManager.java
index 6b95dad..f2fd64f 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/checkpoint/GridCheckpointManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/checkpoint/GridCheckpointManager.java
@@ -44,6 +44,7 @@ import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.spi.IgniteSpiException;
 import org.apache.ignite.spi.checkpoint.CheckpointListener;
 import org.apache.ignite.spi.checkpoint.CheckpointSpi;
@@ -173,7 +174,7 @@ public class GridCheckpointManager extends GridManagerAdapter<CheckpointSpi> {
         try {
             switch (scope) {
                 case GLOBAL_SCOPE: {
-                    byte[] data = state == null ? null : marsh.marshal(state);
+                    byte[] data = state == null ? null : MarshallerUtils.marshal(ctx, state);
 
                     saved = getSpi(ses.getCheckpointSpi()).saveCheckpoint(key, data, timeout, override);
 
@@ -204,7 +205,7 @@ public class GridCheckpointManager extends GridManagerAdapter<CheckpointSpi> {
                         timeout = ses.getEndTime() - now;
 
                     // Save it first to avoid getting null value on another node.
-                    byte[] data = state == null ? null : marsh.marshal(state);
+                    byte[] data = state == null ? null : MarshallerUtils.marshal(ctx, state);
 
                     Set<String> keys = keyMap.get(ses.getId());
 
@@ -337,8 +338,10 @@ public class GridCheckpointManager extends GridManagerAdapter<CheckpointSpi> {
             Serializable state = null;
 
             // Always deserialize with task/session class loader.
-            if (data != null)
-                state = marsh.unmarshal(data, U.resolveClassLoader(ses.getClassLoader(), ctx.config()));
+            if (data != null) {
+                state = MarshallerUtils.unmarshal(ctx.gridName(), marsh, data,
+                    U.resolveClassLoader(ses.getClassLoader(), ctx.config()));
+            }
 
             record(EVT_CHECKPOINT_LOADED, key);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
index 8ba6a1c..faedcea 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/communication/GridIoManager.java
@@ -67,6 +67,7 @@ import org.apache.ignite.lang.IgniteInClosure;
 import org.apache.ignite.lang.IgniteRunnable;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.IoPool;
 import org.apache.ignite.plugin.extensions.communication.Message;
 import org.apache.ignite.plugin.extensions.communication.MessageFactory;
@@ -594,7 +595,7 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
                 int topicOrd = msg.topicOrdinal();
 
                 msg.topic(topicOrd >= 0 ? GridTopic.fromOrdinal(topicOrd) :
-                    marsh.unmarshal(msg.topicBytes(), U.resolveClassLoader(ctx.config())));
+                    MarshallerUtils.unmarshal(ctx.gridName(), marsh, msg.topicBytes(), U.resolveClassLoader(ctx.config())));
             }
 
             if (!started) {
@@ -1117,7 +1118,7 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
         }
         else {
             if (topicOrd < 0)
-                ioMsg.topicBytes(marsh.marshal(topic));
+                ioMsg.topicBytes(MarshallerUtils.marshal(ctx, topic));
 
             try {
                 if ((CommunicationSpi)getSpi() instanceof TcpCommunicationSpi)
@@ -1377,10 +1378,10 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
         byte[] serTopic = null;
 
         if (!loc) {
-            serMsg = marsh.marshal(msg);
+            serMsg = MarshallerUtils.marshal(ctx, msg);
 
             if (topic != null)
-                serTopic = marsh.marshal(topic);
+                serTopic = MarshallerUtils.marshal(ctx, topic);
         }
 
         GridDeployment dep = null;
@@ -2037,7 +2038,7 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
 
                     // Unmarshall message topic if needed.
                     if (msgTopic == null && msgTopicBytes != null) {
-                        msgTopic = marsh.unmarshal(msgTopicBytes,
+                        msgTopic = MarshallerUtils.unmarshal(ctx.gridName(), marsh, msgTopicBytes,
                             U.resolveClassLoader(dep != null ? dep.classLoader() : null, ctx.config()));
 
                         ioMsg.topic(msgTopic); // Save topic to avoid future unmarshallings.
@@ -2047,7 +2048,7 @@ public class GridIoManager extends GridManagerAdapter<CommunicationSpi<Serializa
                         return;
 
                     if (msgBody == null) {
-                        msgBody = marsh.unmarshal(ioMsg.bodyBytes(),
+                        msgBody = MarshallerUtils.unmarshal(ctx.gridName(), marsh, ioMsg.bodyBytes(),
                             U.resolveClassLoader(dep != null ? dep.classLoader() : null, ctx.config()));
 
                         ioMsg.body(msgBody); // Save body to avoid future unmarshallings.

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentCommunication.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentCommunication.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentCommunication.java
index 76bd6e3..880cfca 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentCommunication.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/deployment/GridDeploymentCommunication.java
@@ -40,6 +40,7 @@ import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteNotPeerDeployable;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.Message;
 
 import static org.apache.ignite.events.EventType.EVT_NODE_FAILED;
@@ -183,7 +184,8 @@ class GridDeploymentCommunication {
 
         if (req.responseTopic() == null) {
             try {
-                req.responseTopic(marsh.unmarshal(req.responseTopicBytes(), U.resolveClassLoader(ctx.config())));
+                req.responseTopic(MarshallerUtils.unmarshal(ctx.gridName(), marsh, req.responseTopicBytes(),
+                    U.resolveClassLoader(ctx.config())));
             }
             catch (IgniteCheckedException e) {
                 U.error(log, "Failed to process deployment request (will ignore): " + req, e);
@@ -444,7 +446,7 @@ class GridDeploymentCommunication {
             long start = U.currentTimeMillis();
 
             if (req.responseTopic() != null && !ctx.localNodeId().equals(dstNode.id()))
-                req.responseTopicBytes(marsh.marshal(req.responseTopic()));
+                req.responseTopicBytes(MarshallerUtils.marshal(ctx, req.responseTopic()));
 
             ctx.io().send(dstNode, TOPIC_CLASSLOAD, req, GridIoPolicy.P2P_POOL);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageManager.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageManager.java
index 0095707..ac76cdc 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/eventstorage/GridEventStorageManager.java
@@ -58,6 +58,7 @@ import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgnitePredicate;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.security.SecurityPermission;
 import org.apache.ignite.spi.IgniteSpiException;
 import org.apache.ignite.spi.eventstorage.EventStorageSpi;
@@ -891,11 +892,11 @@ public class GridEventStorageManager extends GridManagerAdapter<EventStorageSpi>
 
                 try {
                     if (res.eventsBytes() != null)
-                        res.events(marsh.<Collection<Event>>unmarshal(res.eventsBytes(),
+                        res.events(MarshallerUtils.<Collection<Event>>unmarshal(ctx.gridName(), marsh, res.eventsBytes(),
                             U.resolveClassLoader(ctx.config())));
 
                     if (res.exceptionBytes() != null)
-                        res.exception(marsh.<Throwable>unmarshal(res.exceptionBytes(),
+                        res.exception(MarshallerUtils.<Throwable>unmarshal(ctx.gridName(), marsh, res.exceptionBytes(),
                             U.resolveClassLoader(ctx.config())));
                 }
                 catch (IgniteCheckedException e) {
@@ -932,7 +933,7 @@ public class GridEventStorageManager extends GridManagerAdapter<EventStorageSpi>
 
             ioMgr.addMessageListener(resTopic, resLsnr);
 
-            byte[] serFilter = marsh.marshal(p);
+            byte[] serFilter = MarshallerUtils.marshal(ctx, p);
 
             GridDeployment dep = ctx.deploy().deploy(p.getClass(), U.detectClassLoader(p.getClass()));
 
@@ -1023,7 +1024,7 @@ public class GridEventStorageManager extends GridManagerAdapter<EventStorageSpi>
             ctx.io().send(locNode, topic, msg, plc);
 
         if (!rmtNodes.isEmpty()) {
-            msg.responseTopicBytes(marsh.marshal(msg.responseTopic()));
+            msg.responseTopicBytes(MarshallerUtils.marshal(ctx, msg.responseTopic()));
 
             ctx.io().send(rmtNodes, topic, msg, plc);
         }
@@ -1088,8 +1089,10 @@ public class GridEventStorageManager extends GridManagerAdapter<EventStorageSpi>
                 Collection<Event> evts;
 
                 try {
-                    if (req.responseTopicBytes() != null)
-                        req.responseTopic(marsh.unmarshal(req.responseTopicBytes(), U.resolveClassLoader(ctx.config())));
+                    if (req.responseTopicBytes() != null) {
+                        req.responseTopic(MarshallerUtils.unmarshal(ctx.gridName(), marsh, req.responseTopicBytes(),
+                            U.resolveClassLoader(ctx.config())));
+                    }
 
                     GridDeployment dep = ctx.deploy().getGlobalDeployment(
                         req.deploymentMode(),
@@ -1105,7 +1108,8 @@ public class GridEventStorageManager extends GridManagerAdapter<EventStorageSpi>
                         throw new IgniteDeploymentCheckedException("Failed to obtain deployment for event filter " +
                             "(is peer class loading turned on?): " + req);
 
-                    filter = marsh.unmarshal(req.filter(), U.resolveClassLoader(dep.classLoader(), ctx.config()));
+                    filter = MarshallerUtils.unmarshal(ctx.gridName(), marsh, req.filter(),
+                        U.resolveClassLoader(dep.classLoader(), ctx.config()));
 
                     // Resource injection.
                     ctx.resource().inject(dep, dep.deployedClass(req.filterClassName()), filter);
@@ -1140,8 +1144,8 @@ public class GridEventStorageManager extends GridManagerAdapter<EventStorageSpi>
                         log.debug("Sending event query response to node [nodeId=" + nodeId + "res=" + res + ']');
 
                     if (!ctx.localNodeId().equals(nodeId)) {
-                        res.eventsBytes(marsh.marshal(res.events()));
-                        res.exceptionBytes(marsh.marshal(res.exception()));
+                        res.eventsBytes(MarshallerUtils.marshal(ctx, res.events()));
+                        res.exceptionBytes(MarshallerUtils.marshal(ctx, res.exception()));
                     }
 
                     ctx.io().send(node, req.responseTopic(), res, PUBLIC_POOL);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/managers/swapspace/GridSwapSpaceManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/managers/swapspace/GridSwapSpaceManager.java b/modules/core/src/main/java/org/apache/ignite/internal/managers/swapspace/GridSwapSpaceManager.java
index 437603a..767e459 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/managers/swapspace/GridSwapSpaceManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/managers/swapspace/GridSwapSpaceManager.java
@@ -32,6 +32,7 @@ import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteBiInClosure;
 import org.apache.ignite.lang.IgniteInClosure;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.spi.IgniteSpiCloseableIterator;
 import org.apache.ignite.spi.IgniteSpiException;
 import org.apache.ignite.spi.swapspace.SwapContext;
@@ -400,7 +401,7 @@ public class GridSwapSpaceManager extends GridManagerAdapter<SwapSpaceSpi> {
         if (swapBytes == null)
             return null;
 
-        return marsh.unmarshal(swapBytes, ldr != null ? ldr : U.gridClassLoader());
+        return MarshallerUtils.unmarshal(ctx.gridName(), marsh, swapBytes, ldr != null ? ldr : U.gridClassLoader());
     }
 
     /**
@@ -411,7 +412,7 @@ public class GridSwapSpaceManager extends GridManagerAdapter<SwapSpaceSpi> {
      * @throws IgniteCheckedException If failed.
      */
     private byte[] marshal(Object obj) throws IgniteCheckedException {
-        return ctx.config().getMarshaller().marshal(obj);
+        return MarshallerUtils.marshal(ctx, obj);
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/GridAffinityUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/GridAffinityUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/GridAffinityUtils.java
index f670960..6f42e4d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/GridAffinityUtils.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/affinity/GridAffinityUtils.java
@@ -37,6 +37,7 @@ import org.apache.ignite.internal.processors.task.GridInternal;
 import org.apache.ignite.internal.util.lang.GridTuple3;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.resources.IgniteInstanceResource;
 import org.apache.ignite.resources.LoggerResource;
 import org.jetbrains.annotations.NotNull;
@@ -77,7 +78,7 @@ class GridAffinityUtils {
             throw new IgniteDeploymentCheckedException("Failed to deploy affinity object with class: " + cls.getName());
 
         return new GridAffinityMessage(
-            ctx.config().getMarshaller().marshal(o),
+            MarshallerUtils.marshal(ctx, o),
             cls.getName(),
             dep.classLoaderId(),
             dep.deployMode(),
@@ -110,7 +111,7 @@ class GridAffinityUtils {
             throw new IgniteDeploymentCheckedException("Failed to obtain affinity object (is peer class loading turned on?): " +
                 msg);
 
-        Object src = ctx.config().getMarshaller().unmarshal(msg.source(),
+        Object src = MarshallerUtils.unmarshal(ctx.gridName(), ctx.config().getMarshaller(), msg.source(),
             U.resolveClassLoader(dep.classLoader(), ctx.config()));
 
         // Resource injection.

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntrySerializablePredicate.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntrySerializablePredicate.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntrySerializablePredicate.java
index 61b6db3..f3cf1e5 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntrySerializablePredicate.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheEntrySerializablePredicate.java
@@ -21,6 +21,8 @@ import java.nio.ByteBuffer;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
+import org.apache.ignite.internal.util.typedef.internal.CU;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
@@ -80,7 +82,8 @@ public class CacheEntrySerializablePredicate implements CacheEntryPredicate {
         assert p != null || bytes != null;
 
         if (p == null) {
-            p = ctx.marshaller().unmarshal(bytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+            p = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), bytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
 
             p.finishUnmarshal(ctx, ldr);
         }
@@ -92,7 +95,7 @@ public class CacheEntrySerializablePredicate implements CacheEntryPredicate {
 
         p.prepareMarshal(ctx);
 
-        bytes = ctx.marshaller().marshal(p);
+        bytes = CU.marshal(ctx, p);
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java
index c6e8bee..fb4b830 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java
@@ -23,7 +23,9 @@ import javax.cache.processor.MutableEntry;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.Message;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
@@ -106,7 +108,7 @@ public class CacheInvokeDirectResult implements Message {
         key.prepareMarshal(ctx.cacheObjectContext());
 
         if (err != null)
-            errBytes = ctx.marshaller().marshal(err);
+            errBytes = CU.marshal(ctx, err);
 
         if (res != null)
             res.prepareMarshal(ctx.cacheObjectContext());
@@ -120,8 +122,10 @@ public class CacheInvokeDirectResult implements Message {
     public void finishUnmarshal(GridCacheContext ctx, ClassLoader ldr) throws IgniteCheckedException {
         key.finishUnmarshal(ctx.cacheObjectContext(), ldr);
 
-        if (errBytes != null)
-            err = ctx.marshaller().unmarshal(errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (errBytes != null) {
+            err = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), errBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
 
         if (res != null)
             res.finishUnmarshal(ctx.cacheObjectContext(), ldr);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java
index f99d2cd..53a0c16 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMessage.java
@@ -37,6 +37,7 @@ import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.Message;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
@@ -457,8 +458,10 @@ public abstract class GridCacheMessage implements Message {
 
         Marshaller marsh = ctx.marshaller();
 
-        for (int i = 0; i < byteCol.length; i++)
-            args[i] = byteCol[i] == null ? null : marsh.unmarshal(byteCol[i], U.resolveClassLoader(ldr, ctx.gridConfig()));
+        for (int i = 0; i < byteCol.length; i++) {
+            args[i] = byteCol[i] == null ? null : MarshallerUtils.unmarshal(ctx.gridName(), marsh, byteCol[i],
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
 
         return args;
     }
@@ -608,8 +611,10 @@ public abstract class GridCacheMessage implements Message {
 
         Marshaller marsh = ctx.marshaller();
 
-        for (byte[] bytes : byteCol)
-            col.add(bytes == null ? null : marsh.<T>unmarshal(bytes, U.resolveClassLoader(ldr, ctx.gridConfig())));
+        for (byte[] bytes : byteCol) {
+            col.add(bytes == null ? null : MarshallerUtils.<T>unmarshal(ctx.gridName(), marsh, bytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig())));
+        }
 
         return col;
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
index 6761fac..3cc33b4 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
@@ -106,7 +106,6 @@ import org.apache.ignite.internal.util.future.GridFinishedFuture;
 import org.apache.ignite.internal.util.future.GridFutureAdapter;
 import org.apache.ignite.internal.util.lang.IgniteOutClosureX;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
-import org.apache.ignite.internal.util.typedef.CIX1;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.X;
 import org.apache.ignite.internal.util.typedef.internal.CU;
@@ -118,6 +117,7 @@ import org.apache.ignite.lang.IgnitePredicate;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.lifecycle.LifecycleAware;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.spi.IgniteNodeValidationResult;
 import org.jetbrains.annotations.Nullable;
@@ -3397,7 +3397,7 @@ public class GridCacheProcessor extends GridProcessorAdapter {
                         if (ldr == null)
                             ldr = val.getCacheStoreFactory().getClass().getClassLoader();
 
-                        marshaller.unmarshal(marshaller.marshal(val.getCacheStoreFactory()),
+                        MarshallerUtils.marshalUnmarshal(ctx.gridName(), marshaller, val.getCacheStoreFactory(),
                             U.resolveClassLoader(ldr, ctx.config()));
                     }
                     catch (IgniteCheckedException e) {
@@ -3407,7 +3407,8 @@ public class GridCacheProcessor extends GridProcessorAdapter {
                 }
 
                 try {
-                    return marshaller.unmarshal(marshaller.marshal(val), U.resolveClassLoader(ctx.config()));
+                    return MarshallerUtils.marshalUnmarshal(ctx.gridName(), marshaller, val,
+                        U.resolveClassLoader(ctx.config()));
                 }
                 catch (IgniteCheckedException e) {
                     throw new IgniteCheckedException("Failed to validate cache configuration " +

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java
index ba563e6..6264648 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheUtils.java
@@ -55,7 +55,6 @@ import org.apache.ignite.cache.affinity.Affinity;
 import org.apache.ignite.cache.store.CacheStoreSessionListener;
 import org.apache.ignite.cluster.ClusterNode;
 import org.apache.ignite.configuration.CacheConfiguration;
-import org.apache.ignite.configuration.FileSystemConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.configuration.TransactionConfiguration;
 import org.apache.ignite.internal.GridKernalContext;
@@ -92,6 +91,7 @@ import org.apache.ignite.lang.IgniteInClosure;
 import org.apache.ignite.lang.IgnitePredicate;
 import org.apache.ignite.lang.IgniteReducer;
 import org.apache.ignite.lifecycle.LifecycleAware;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.CachePluginConfiguration;
 import org.apache.ignite.transactions.Transaction;
 import org.apache.ignite.transactions.TransactionConcurrency;
@@ -991,7 +991,7 @@ public class GridCacheUtils {
             }
         }
 
-        return ctx.marshaller().marshal(obj);
+        return MarshallerUtils.marshal(ctx.gridName(), ctx.marshaller(), obj);
     }
 
     /**
@@ -1891,4 +1891,16 @@ public class GridCacheUtils {
             ? DEFAULT_TX_CFG
             : cfg.getTransactionConfiguration();
     }
+
+    /**
+     * Marshal object.
+     *
+     * @param ctx Shared context.
+     * @param obj Object.
+     * @return Result.
+     * @throws IgniteCheckedException If failed.
+     */
+    public static byte[] marshal(GridCacheSharedContext ctx, Object obj) throws IgniteCheckedException {
+        return MarshallerUtils.marshal(ctx.gridName(), ctx.marshaller(), obj);
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java
index f56ba8f..d0d9aa3 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedLockResponse.java
@@ -31,9 +31,11 @@ import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteUuid;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
@@ -202,7 +204,7 @@ public class GridDistributedLockResponse extends GridDistributedBaseMessage {
         prepareMarshalCacheObjects(vals, ctx.cacheContext(cacheId));
 
         if (err != null)
-            errBytes = ctx.marshaller().marshal(err);
+            errBytes = CU.marshal(ctx, err);
     }
 
     /** {@inheritDoc} */
@@ -211,8 +213,10 @@ public class GridDistributedLockResponse extends GridDistributedBaseMessage {
 
         finishUnmarshalCacheObjects(vals, ctx.cacheContext(cacheId), ldr);
 
-        if (errBytes != null)
-            err = ctx.marshaller().unmarshal(errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (errBytes != null) {
+            err = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), errBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java
index 871a599..2506d9a 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareRequest.java
@@ -41,8 +41,10 @@ import org.apache.ignite.internal.util.tostring.GridToStringBuilder;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.C1;
 import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteProductVersion;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
@@ -332,7 +334,7 @@ public class GridDistributedTxPrepareRequest extends GridDistributedBaseMessage
         // Marshal txNodes only if there is a node in topology with an older version.
         if (ctx.exchange().minimumNodeVersion(topologyVersion()).compareTo(TX_NODES_DIRECT_MARSHALLABLE_SINCE) < 0) {
             if (txNodes != null && txNodesBytes == null)
-                txNodesBytes = ctx.marshaller().marshal(txNodes);
+                txNodesBytes = CU.marshal(ctx, txNodes);
         }
         else {
             if (txNodesMsg == null)
@@ -372,7 +374,8 @@ public class GridDistributedTxPrepareRequest extends GridDistributedBaseMessage
             txNodes = F.viewReadOnly(txNodesMsg, MSG_TO_COL);
 
         if (txNodesBytes != null && txNodes == null)
-            txNodes = ctx.marshaller().unmarshal(txNodesBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+            txNodes = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), txNodesBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java
index 7011e80..8f5920d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/GridDistributedTxPrepareResponse.java
@@ -26,6 +26,8 @@ import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.tostring.GridToStringBuilder;
 import org.apache.ignite.internal.util.tostring.GridToStringExclude;
+import org.apache.ignite.internal.util.typedef.internal.CU;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
@@ -100,15 +102,17 @@ public class GridDistributedTxPrepareResponse extends GridDistributedBaseMessage
         super.prepareMarshal(ctx);
 
         if (err != null)
-            errBytes = ctx.marshaller().marshal(err);
+            errBytes = CU.marshal(ctx, err);
     }
 
     /** {@inheritDoc} */
     @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
         super.finishUnmarshal(ctx, ldr);
 
-        if (errBytes != null)
-            err = ctx.marshaller().unmarshal(errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (errBytes != null) {
+            err = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), errBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentResponse.java
index c1be30b..11d0f9c 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtAffinityAssignmentResponse.java
@@ -26,7 +26,9 @@ import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.processors.cache.GridCacheMessage;
 import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
@@ -106,7 +108,7 @@ public class GridDhtAffinityAssignmentResponse extends GridCacheMessage {
         super.prepareMarshal(ctx);
 
         if (affAssignment != null)
-            affAssignmentBytes = ctx.marshaller().marshal(affAssignment);
+            affAssignmentBytes = CU.marshal(ctx, affAssignment);
     }
 
     /** {@inheritDoc} */
@@ -115,7 +117,8 @@ public class GridDhtAffinityAssignmentResponse extends GridCacheMessage {
         super.finishUnmarshal(ctx, ldr);
 
         if (affAssignmentBytes != null) {
-            affAssignment = ctx.marshaller().unmarshal(affAssignmentBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+            affAssignment = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), affAssignmentBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
 
             // TODO IGNITE-2110: setting 'local' for nodes not needed when IGNITE-2110 is implemented.
             int assignments = affAssignment.size();

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishResponse.java
index 65c9024..df93f8a 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxFinishResponse.java
@@ -25,9 +25,11 @@ import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.distributed.GridDistributedTxFinishResponse;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteUuid;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
 
@@ -111,7 +113,7 @@ public class GridDhtTxFinishResponse extends GridDistributedTxFinishResponse {
         super.prepareMarshal(ctx);
 
         if (checkCommittedErr != null)
-            checkCommittedErrBytes = ctx.marshaller().marshal(checkCommittedErr);
+            checkCommittedErrBytes = CU.marshal(ctx, checkCommittedErr);
     }
 
     /** {@inheritDoc} */
@@ -119,8 +121,10 @@ public class GridDhtTxFinishResponse extends GridDistributedTxFinishResponse {
         throws IgniteCheckedException {
         super.finishUnmarshal(ctx, ldr);
 
-        if (checkCommittedErrBytes != null)
-            checkCommittedErr = ctx.marshaller().unmarshal(checkCommittedErrBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (checkCommittedErrBytes != null) {
+            checkCommittedErr = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), checkCommittedErrBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java
index 742b39c..7a5852d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridDhtAtomicUpdateResponse.java
@@ -33,7 +33,9 @@ import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.KeyCacheObject;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
@@ -167,7 +169,7 @@ public class GridDhtAtomicUpdateResponse extends GridCacheMessage implements Gri
 
         prepareMarshalCacheObjects(nearEvicted, cctx);
 
-        errBytes = ctx.marshaller().marshal(err);
+        errBytes = CU.marshal(ctx, err);
     }
 
     /** {@inheritDoc} */
@@ -180,7 +182,8 @@ public class GridDhtAtomicUpdateResponse extends GridCacheMessage implements Gri
 
         finishUnmarshalCacheObjects(nearEvicted, cctx, ldr);
 
-        err = ctx.marshaller().unmarshal(errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        err = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), errBytes,
+            U.resolveClassLoader(ldr, ctx.gridConfig()));
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java
index 1d03dd2..446e950 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateRequest.java
@@ -1,3 +1,5 @@
+//        if (expiryPlcBytes != null && expiryPlc == null)
+//            expiryPlc = MarshallerUtils.unmarshal(ctx.marshaller(), expiryPlcBytes, ldr, ctx.kernalContext());
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -45,6 +47,7 @@ import org.apache.ignite.internal.util.GridLongList;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
 import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
@@ -633,8 +636,10 @@ public class GridNearAtomicUpdateRequest extends GridCacheMessage implements Gri
 
         invokeArgs = unmarshalInvokeArguments(invokeArgsBytes, ctx, ldr);
 
-        if (expiryPlcBytes != null)
-            expiryPlc = ctx.marshaller().unmarshal(expiryPlcBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (expiryPlcBytes != null) {
+            expiryPlc = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), expiryPlcBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java
index dd52aae..f3bf5c0 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/atomic/GridNearAtomicUpdateResponse.java
@@ -38,7 +38,9 @@ import org.apache.ignite.internal.processors.cache.KeyCacheObject;
 import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
 import org.apache.ignite.internal.util.GridLongList;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
@@ -397,7 +399,7 @@ public class GridNearAtomicUpdateResponse extends GridCacheMessage implements Gr
         super.prepareMarshal(ctx);
 
         if (err != null)
-            errBytes = ctx.marshaller().marshal(err);
+            errBytes = CU.marshal(ctx, err);
 
         GridCacheContext cctx = ctx.cacheContext(cacheId);
 
@@ -415,8 +417,10 @@ public class GridNearAtomicUpdateResponse extends GridCacheMessage implements Gr
     @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
         super.finishUnmarshal(ctx, ldr);
 
-        if (errBytes != null)
-            err = ctx.marshaller().unmarshal(errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (errBytes != null) {
+            err = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), errBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
 
         GridCacheContext cctx = ctx.cacheContext(cacheId);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysResponse.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysResponse.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysResponse.java
index 12bf160..a516831 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysResponse.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtForceKeysResponse.java
@@ -33,9 +33,11 @@ import org.apache.ignite.internal.processors.cache.GridCacheMessage;
 import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
 import org.apache.ignite.internal.processors.cache.KeyCacheObject;
 import org.apache.ignite.internal.util.tostring.GridToStringInclude;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteUuid;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
 import org.apache.ignite.plugin.extensions.communication.MessageWriter;
@@ -171,7 +173,7 @@ public class GridDhtForceKeysResponse extends GridCacheMessage implements GridCa
                 info.marshal(cctx);
         }
 
-        errBytes = ctx.marshaller().marshal(err);
+        errBytes = CU.marshal(ctx, err);
     }
 
     /** {@inheritDoc} */
@@ -188,8 +190,10 @@ public class GridDhtForceKeysResponse extends GridCacheMessage implements GridCa
                 info.unmarshal(cctx, ldr);
         }
 
-        if (errBytes != null)
-            err = ctx.marshaller().unmarshal(errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (errBytes != null) {
+            err = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), errBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
     }
 
     /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionDemandMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionDemandMessage.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionDemandMessage.java
index 4426c44..f435dc3 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionDemandMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/preloader/GridDhtPartitionDemandMessage.java
@@ -27,7 +27,9 @@ import org.apache.ignite.internal.GridDirectTransient;
 import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
 import org.apache.ignite.internal.processors.cache.GridCacheMessage;
 import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
+import org.apache.ignite.internal.util.typedef.internal.CU;
 import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
 import org.apache.ignite.plugin.extensions.communication.MessageReader;
@@ -183,15 +185,17 @@ public class GridDhtPartitionDemandMessage extends GridCacheMessage {
         super.prepareMarshal(ctx);
 
         if (topic != null)
-            topicBytes = ctx.marshaller().marshal(topic);
+            topicBytes = CU.marshal(ctx, topic);
     }
 
     /** {@inheritDoc} */
     @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
         super.finishUnmarshal(ctx, ldr);
 
-        if (topicBytes != null)
-            topic = ctx.marshaller().unmarshal(topicBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
+        if (topicBytes != null) {
+            topic = MarshallerUtils.unmarshal(ctx.gridName(), ctx.marshaller(), topicBytes,
+                U.resolveClassLoader(ldr, ctx.gridConfig()));
+        }
     }
 
     /** {@inheritDoc} */


[12/50] [abbrv] ignite git commit: Backported test fixes.

Posted by vo...@apache.org.
Backported test fixes.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 5b6e7816260addfb3ed819e63147a0873bda9baf
Parents: f52fb79
Author: sboikov <sb...@gridgain.com>
Authored: Thu Jul 7 12:37:25 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Thu Jul 7 12:37:25 2016 +0300

----------------------------------------------------------------------
 .../GridEventStorageCheckAllEventsSelfTest.java | 30 ++++++++++++++++++--
 ...CommunicationRecoveryAckClosureSelfTest.java | 18 ++++++++++++
 2 files changed, 46 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/5b6e7816/modules/core/src/test/java/org/apache/ignite/internal/GridEventStorageCheckAllEventsSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/GridEventStorageCheckAllEventsSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/GridEventStorageCheckAllEventsSelfTest.java
index ad15894..0619391 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/GridEventStorageCheckAllEventsSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/GridEventStorageCheckAllEventsSelfTest.java
@@ -30,10 +30,12 @@ import org.apache.ignite.compute.ComputeJob;
 import org.apache.ignite.compute.ComputeJobAdapter;
 import org.apache.ignite.compute.ComputeJobResult;
 import org.apache.ignite.compute.ComputeTaskFuture;
+import org.apache.ignite.compute.ComputeTaskMapAsync;
 import org.apache.ignite.compute.ComputeTaskSession;
 import org.apache.ignite.compute.ComputeTaskSessionFullSupport;
 import org.apache.ignite.compute.ComputeTaskSplitAdapter;
 import org.apache.ignite.compute.ComputeTaskTimeoutException;
+import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.events.CheckpointEvent;
 import org.apache.ignite.events.DeploymentEvent;
 import org.apache.ignite.events.Event;
@@ -86,6 +88,16 @@ public class GridEventStorageCheckAllEventsSelfTest extends GridCommonAbstractTe
     }
 
     /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration() throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration();
+
+        // TODO: IGNITE-3099 (hotfix the test to check the event order in common case).
+        cfg.setPublicThreadPoolSize(1);
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
     @Override protected void beforeTestsStarted() throws Exception {
         ignite = G.ignite(getTestGridName());
 
@@ -140,10 +152,23 @@ public class GridEventStorageCheckAllEventsSelfTest extends GridCommonAbstractTe
      * @throws Exception If test failed.
      */
     public void testTaskUndeployEvents() throws Exception {
-        long tstamp = startTimestamp();
+        final long tstamp = startTimestamp();
 
         generateEvents(null, new GridAllEventsSuccessTestJob()).get();
 
+        // TODO: IGNITE-3099 (hotfix the test to check the event order in common case).
+        GridTestUtils.waitForCondition(new GridAbsPredicate() {
+            @Override public boolean apply() {
+                try {
+                    List<Event> evts = pullEvents(tstamp, 10);
+                    return evts.get(evts.size() - 1).type() == EVT_JOB_FINISHED;
+                }
+                catch (Exception e) {
+                    return false;
+                }
+            }
+        }, 500);
+
         ignite.compute().undeployTask(GridAllEventsTestTask.class.getName());
         ignite.compute().localDeployTask(GridAllEventsTestTask.class, GridAllEventsTestTask.class.getClassLoader());
 
@@ -198,7 +223,7 @@ public class GridEventStorageCheckAllEventsSelfTest extends GridCommonAbstractTe
         try {
             fut.get();
 
-            assert false : "Grid with locally executed job with timeout should throw GridComputeTaskTimeoutException.";
+            assert false : "Grid with locally executed job with timeout should throw ComputeTaskTimeoutException.";
         }
         catch (IgniteException e) {
             info("Expected exception caught [taskFuture=" + fut + ", exception=" + e + ']');
@@ -463,6 +488,7 @@ public class GridEventStorageCheckAllEventsSelfTest extends GridCommonAbstractTe
      *
      */
     @ComputeTaskSessionFullSupport
+    @ComputeTaskMapAsync // TODO: IGNITE-3099 (hotfix the test to check the event order in common case).
     private static class GridAllEventsTestTask extends ComputeTaskSplitAdapter<Object, Object> {
         /** {@inheritDoc} */
         @Override protected Collection<? extends ComputeJob> split(int gridSize, Object arg) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/5b6e7816/modules/core/src/test/java/org/apache/ignite/spi/communication/tcp/IgniteTcpCommunicationRecoveryAckClosureSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/spi/communication/tcp/IgniteTcpCommunicationRecoveryAckClosureSelfTest.java b/modules/core/src/test/java/org/apache/ignite/spi/communication/tcp/IgniteTcpCommunicationRecoveryAckClosureSelfTest.java
index 7521f2e..260bbd2 100644
--- a/modules/core/src/test/java/org/apache/ignite/spi/communication/tcp/IgniteTcpCommunicationRecoveryAckClosureSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/spi/communication/tcp/IgniteTcpCommunicationRecoveryAckClosureSelfTest.java
@@ -49,11 +49,13 @@ import org.apache.ignite.testframework.GridTestNode;
 import org.apache.ignite.testframework.GridTestUtils;
 import org.apache.ignite.testframework.junits.IgniteTestResources;
 import org.apache.ignite.testframework.junits.spi.GridSpiAbstractTest;
+import org.apache.ignite.testframework.junits.spi.GridSpiTest;
 import org.eclipse.jetty.util.ConcurrentHashSet;
 
 /**
  *
  */
+@GridSpiTest(spi = TcpCommunicationSpi.class, group = "Communication SPI")
 public class IgniteTcpCommunicationRecoveryAckClosureSelfTest<T extends CommunicationSpi>
     extends GridSpiAbstractTest<T> {
     /** */
@@ -151,6 +153,8 @@ public class IgniteTcpCommunicationRecoveryAckClosureSelfTest<T extends Communic
 
             int expMsgs = 0;
 
+            long totAcked = 0;
+
             for (int i = 0; i < 5; i++) {
                 info("Iteration: " + i);
 
@@ -172,6 +176,8 @@ public class IgniteTcpCommunicationRecoveryAckClosureSelfTest<T extends Communic
 
                 expMsgs += msgPerIter;
 
+                final long totAcked0 = totAcked;
+
                 for (TcpCommunicationSpi spi : spis) {
                     GridNioServer srv = U.field(spi, "nioSrvr");
 
@@ -189,6 +195,14 @@ public class IgniteTcpCommunicationRecoveryAckClosureSelfTest<T extends Communic
 
                             GridTestUtils.waitForCondition(new GridAbsPredicate() {
                                 @Override public boolean apply() {
+                                    long acked = GridTestUtils.getFieldValue(recoveryDesc, "acked");
+
+                                    return acked > totAcked0;
+                                }
+                            }, 5000);
+
+                            GridTestUtils.waitForCondition(new GridAbsPredicate() {
+                                @Override public boolean apply() {
                                     return recoveryDesc.messagesFutures().isEmpty();
                                 }
                             }, 10_000);
@@ -218,6 +232,8 @@ public class IgniteTcpCommunicationRecoveryAckClosureSelfTest<T extends Communic
                 }
 
                 assertEquals(msgPerIter * 2, ackMsgs.get());
+
+                totAcked += msgPerIter;
             }
         }
         finally {
@@ -337,6 +353,8 @@ public class IgniteTcpCommunicationRecoveryAckClosureSelfTest<T extends Communic
                 return expMsgs == ackMsgs.get();
             }
         }, 5000);
+
+        assertEquals(expMsgs, ackMsgs.get());
     }
 
     /**


[33/50] [abbrv] ignite git commit: ignite-3465 Do not call super.toString for not-initialized BinaryObjectImpl.

Posted by vo...@apache.org.
ignite-3465 Do not call super.toString for not-initialized BinaryObjectImpl.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 78d7c136a3860f1cb4346b37bf8853bc8b576636
Parents: 84e83c9
Author: sboikov <sb...@gridgain.com>
Authored: Tue Jul 19 13:35:59 2016 +0300
Committer: sboikov <sb...@gridgain.com>
Committed: Tue Jul 19 13:35:59 2016 +0300

----------------------------------------------------------------------
 .../org/apache/ignite/internal/binary/BinaryObjectImpl.java  | 8 ++++++++
 1 file changed, 8 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/78d7c136/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryObjectImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryObjectImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryObjectImpl.java
index 468cc25..3563fba 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryObjectImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryObjectImpl.java
@@ -586,4 +586,12 @@ public final class BinaryObjectImpl extends BinaryObjectExImpl implements Extern
     private BinaryReaderExImpl reader(@Nullable BinaryReaderHandles rCtx) {
         return reader(rCtx, null);
     }
+
+    /** {@inheritDoc} */
+    @Override public String toString() {
+        if (arr == null || ctx == null)
+            return "BinaryObjectImpl [arr= " + (arr != null) + ", ctx=" + (ctx != null) + ", start=" + start + "]";
+
+        return super.toString();
+    }
 }


[19/50] [abbrv] ignite git commit: ignite-3239 Fix of java.io.IOException: Resource deadlock avoided

Posted by vo...@apache.org.
ignite-3239 Fix of java.io.IOException: Resource deadlock avoided


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 762c43d67c2e500de1be2ae030a55658ad291574
Parents: 7aa609a
Author: agura <ag...@gridgain.com>
Authored: Thu Jun 16 13:03:03 2016 +0300
Committer: agura <ag...@gridgain.com>
Committed: Tue Jul 12 17:15:34 2016 +0300

----------------------------------------------------------------------
 .../ignite/internal/MarshallerContextImpl.java  | 29 ++++++++++++++++++--
 1 file changed, 27 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/762c43d6/modules/core/src/main/java/org/apache/ignite/internal/MarshallerContextImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/MarshallerContextImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/MarshallerContextImpl.java
index b4c9607..504ea6e 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/MarshallerContextImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/MarshallerContextImpl.java
@@ -25,9 +25,11 @@ import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
 import java.io.Writer;
+import java.nio.channels.FileChannel;
 import java.nio.channels.FileLock;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ThreadLocalRandom;
 import java.util.concurrent.locks.Lock;
 import javax.cache.event.CacheEntryEvent;
 import javax.cache.event.CacheEntryListenerException;
@@ -201,7 +203,7 @@ public class MarshallerContextImpl extends MarshallerContextAdapter {
                 File file = new File(workDir, fileName);
 
                 try (FileInputStream in = new FileInputStream(file)) {
-                    FileLock fileLock = in.getChannel().lock(0L, Long.MAX_VALUE, true);
+                    FileLock fileLock = fileLock(in.getChannel(), true);
 
                     assert fileLock != null : fileName;
 
@@ -235,6 +237,26 @@ public class MarshallerContextImpl extends MarshallerContextAdapter {
     }
 
     /**
+     * @param ch File channel.
+     * @param shared Shared.
+     */
+    private static FileLock fileLock(
+        FileChannel ch,
+        boolean shared
+    ) throws IOException, IgniteInterruptedCheckedException {
+        ThreadLocalRandom rnd = ThreadLocalRandom.current();
+
+        while (true) {
+            FileLock fileLock = ch.tryLock(0L, Long.MAX_VALUE, shared);
+
+            if (fileLock == null)
+                U.sleep(rnd.nextLong(50));
+            else
+                return fileLock;
+        }
+    }
+
+    /**
      */
     private static class ContinuousQueryListener implements CacheEntryUpdatedListener<Integer, String> {
         /** */
@@ -270,7 +292,7 @@ public class MarshallerContextImpl extends MarshallerContextAdapter {
                         File file = new File(workDir, fileName);
 
                         try (FileOutputStream out = new FileOutputStream(file)) {
-                            FileLock fileLock = out.getChannel().lock(0L, Long.MAX_VALUE, false);
+                            FileLock fileLock = fileLock(out.getChannel(), false);
 
                             assert fileLock != null : fileName;
 
@@ -284,6 +306,9 @@ public class MarshallerContextImpl extends MarshallerContextAdapter {
                             U.error(log, "Failed to write class name to file [id=" + evt.getKey() +
                                 ", clsName=" + evt.getValue() + ", file=" + file.getAbsolutePath() + ']', e);
                         }
+                        catch (IgniteInterruptedCheckedException e) {
+                            U.error(log, "Interrupted while waiting for acquiring file lock: " + file, e);
+                        }
                     }
                     finally {
                         lock.unlock();


[23/50] [abbrv] ignite git commit: IGNITE-3440: Ignite Services: ServiceTopologyCallable is executed before system cache is started

Posted by vo...@apache.org.
IGNITE-3440: Ignite Services: ServiceTopologyCallable is executed before system cache is started


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 06b24a9b3952598604e02d80d1ed76a52d85e743
Parents: 89d64e7
Author: Denis Magda <dm...@gridgain.com>
Authored: Wed Jul 13 14:19:51 2016 +0300
Committer: Denis Magda <dm...@gridgain.com>
Committed: Wed Jul 13 14:19:51 2016 +0300

----------------------------------------------------------------------
 .../processors/cache/GridCacheProcessor.java    |  2 +
 .../service/GridServiceProcessor.java           | 70 +++++++++++++++++++-
 2 files changed, 71 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/06b24a9b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
index 414a915..6484d4d 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
@@ -797,6 +797,8 @@ public class GridCacheProcessor extends GridProcessorAdapter {
         if (!ctx.config().isDaemon())
             ctx.cacheObjects().onUtilityCacheStarted();
 
+        ctx.service().onUtilityCacheStarted();
+
         // Wait for caches in SYNC preload mode.
         for (CacheConfiguration cfg : ctx.config().getCacheConfiguration()) {
             GridCacheAdapter cache = caches.get(maskNull(cfg.getName()));

http://git-wip-us.apache.org/repos/asf/ignite/blob/06b24a9b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java
index 53eaeb5..b418ba2 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/service/GridServiceProcessor.java
@@ -38,8 +38,10 @@ import javax.cache.event.CacheEntryEvent;
 import javax.cache.event.CacheEntryUpdatedListener;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteException;
+import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.cluster.ClusterGroup;
 import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.compute.ComputeJobContext;
 import org.apache.ignite.configuration.DeploymentMode;
 import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.events.DiscoveryEvent;
@@ -81,6 +83,8 @@ import org.apache.ignite.lang.IgniteProductVersion;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
 import org.apache.ignite.resources.IgniteInstanceResource;
+import org.apache.ignite.resources.JobContextResource;
+import org.apache.ignite.resources.LoggerResource;
 import org.apache.ignite.services.Service;
 import org.apache.ignite.services.ServiceConfiguration;
 import org.apache.ignite.services.ServiceDescriptor;
@@ -125,6 +129,9 @@ public class GridServiceProcessor extends GridProcessorAdapter {
     /** Deployment futures. */
     private final ConcurrentMap<String, GridFutureAdapter<?>> undepFuts = new ConcurrentHashMap8<>();
 
+    /** Pending compute job contexts that waiting for utility cache initialization. */
+    private final List<ComputeJobContext> pendingJobCtxs = new ArrayList<>(0);
+
     /** Deployment executor service. */
     private final ExecutorService depExe;
 
@@ -1304,6 +1311,23 @@ public class GridServiceProcessor extends GridProcessorAdapter {
     }
 
     /**
+     * Called right after utility cache is started and ready for the usage.
+     */
+    public void onUtilityCacheStarted() {
+        synchronized (pendingJobCtxs) {
+            if (pendingJobCtxs.size() == 0)
+                return;
+
+            Iterator<ComputeJobContext> iter = pendingJobCtxs.iterator();
+
+            while (iter.hasNext()) {
+                iter.next().callcc();
+                iter.remove();
+            }
+        }
+    }
+
+    /**
      * Service deployment listener.
      */
     @SuppressWarnings("unchecked")
@@ -1783,9 +1807,20 @@ public class GridServiceProcessor extends GridProcessorAdapter {
         private final String svcName;
 
         /** */
+        private boolean waitedCacheInit;
+
+        /** */
         @IgniteInstanceResource
         private IgniteEx ignite;
 
+        /** */
+        @JobContextResource
+        private ComputeJobContext jCtx;
+
+        /** */
+        @LoggerResource
+        private IgniteLogger log;
+
         /**
          * @param svcName Service name.
          */
@@ -1795,7 +1830,40 @@ public class GridServiceProcessor extends GridProcessorAdapter {
 
         /** {@inheritDoc} */
         @Override public Map<UUID, Integer> call() throws Exception {
-            return serviceTopology(ignite.context().cache().utilityCache(), svcName);
+            IgniteInternalCache<Object, Object> cache = ignite.context().cache().utilityCache();
+
+            if (cache == null) {
+                List<ComputeJobContext> pendingCtxs = ignite.context().service().pendingJobCtxs;
+
+                synchronized (pendingCtxs) {
+                    // Double check cache reference after lock acqusition.
+                    cache = ignite.context().cache().utilityCache();
+
+                    if (cache == null) {
+                        if (!waitedCacheInit) {
+                            log.debug("Utility cache hasn't been initialized yet. Waiting.");
+
+                            // waiting for a minute for cache initialization.
+                            jCtx.holdcc(60 * 1000);
+
+                            pendingCtxs.add(jCtx);
+
+                            waitedCacheInit = true;
+
+                            return null;
+                        }
+                        else {
+                            log.error("Failed to gather service topology. Utility " +
+                                "cache initialization is stuck.");
+
+                            throw new IgniteCheckedException("Failed to gather service topology. Utility " +
+                                "cache initialization is stuck.");
+                        }
+                    }
+                }
+            }
+
+            return serviceTopology(cache, svcName);
         }
     }
 


[40/50] [abbrv] ignite git commit: IGNITE-3470 - Support EXPIRED events in continuous queries

Posted by vo...@apache.org.
IGNITE-3470 - Support EXPIRED events in continuous queries


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

Branch: refs/heads/ignite-1.5.31-1
Commit: aedfde69af6e91277616052ab60fa0037693c2c6
Parents: b81dbbf
Author: Valentin Kulichenko <va...@gmail.com>
Authored: Tue Jul 19 16:01:32 2016 -0700
Committer: Valentin Kulichenko <va...@gmail.com>
Committed: Tue Jul 19 16:01:32 2016 -0700

----------------------------------------------------------------------
 .../ignite/cache/query/ContinuousQuery.java     | 47 +++++++++++++++----
 .../processors/cache/IgniteCacheProxy.java      |  3 +-
 .../continuous/CacheContinuousQueryManager.java |  9 ++--
 ...ridCacheContinuousQueryAbstractSelfTest.java | 48 +++++++++++++++++++-
 4 files changed, 91 insertions(+), 16 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/aedfde69/modules/core/src/main/java/org/apache/ignite/cache/query/ContinuousQuery.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/cache/query/ContinuousQuery.java b/modules/core/src/main/java/org/apache/ignite/cache/query/ContinuousQuery.java
index bbfe8cc..49d471e 100644
--- a/modules/core/src/main/java/org/apache/ignite/cache/query/ContinuousQuery.java
+++ b/modules/core/src/main/java/org/apache/ignite/cache/query/ContinuousQuery.java
@@ -21,6 +21,7 @@ import javax.cache.Cache;
 import javax.cache.configuration.Factory;
 import javax.cache.event.CacheEntryEventFilter;
 import javax.cache.event.CacheEntryUpdatedListener;
+import javax.cache.event.EventType;
 import org.apache.ignite.IgniteCache;
 import org.apache.ignite.cache.CacheEntryEventSerializableFilter;
 import org.apache.ignite.configuration.IgniteConfiguration;
@@ -142,6 +143,9 @@ public final class ContinuousQuery<K, V> extends Query<Cache.Entry<K, V>> {
     /** Automatic unsubscription flag. */
     private boolean autoUnsubscribe = DFLT_AUTO_UNSUBSCRIBE;
 
+    /** Whether to notify about {@link EventType#EXPIRED} events. */
+    private boolean includeExpired;
+
     /**
      * Creates new continuous query.
      */
@@ -324,6 +328,38 @@ public final class ContinuousQuery<K, V> extends Query<Cache.Entry<K, V>> {
         return this;
     }
 
+    /**
+     * Gets automatic unsubscription flag value.
+     *
+     * @return Automatic unsubscription flag.
+     */
+    public boolean isAutoUnsubscribe() {
+        return autoUnsubscribe;
+    }
+
+    /**
+     * Sets the flag value defining whether to notify about {@link EventType#EXPIRED} events.
+     * If {@code true}, then the remote listener will get notifications about entries
+     * expired in cache. Otherwise, only {@link EventType#CREATED}, {@link EventType#UPDATED}
+     * and {@link EventType#REMOVED} events will be fired in the remote listener.
+     * <p>
+     * This flag is {@code false} by default, so {@link EventType#EXPIRED} events are disabled.
+     *
+     * @param includeExpired Whether to notify about {@link EventType#EXPIRED} events.
+     */
+    public void setIncludeExpired(boolean includeExpired) {
+        this.includeExpired = includeExpired;
+    }
+
+    /**
+     * Gets the flag value defining whether to notify about {@link EventType#EXPIRED} events.
+     *
+     * @return Whether to notify about {@link EventType#EXPIRED} events.
+     */
+    public boolean isIncludeExpired() {
+        return includeExpired;
+    }
+
     /** {@inheritDoc} */
     @Override public ContinuousQuery<K, V> setPageSize(int pageSize) {
         return (ContinuousQuery<K, V>)super.setPageSize(pageSize);
@@ -333,13 +369,4 @@ public final class ContinuousQuery<K, V> extends Query<Cache.Entry<K, V>> {
     @Override public ContinuousQuery<K, V> setLocal(boolean loc) {
         return (ContinuousQuery<K, V>)super.setLocal(loc);
     }
-
-    /**
-     * Gets automatic unsubscription flag value.
-     *
-     * @return Automatic unsubscription flag.
-     */
-    public boolean isAutoUnsubscribe() {
-        return autoUnsubscribe;
-    }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/aedfde69/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
index 92e59db..249cfae 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/IgniteCacheProxy.java
@@ -598,7 +598,8 @@ public class IgniteCacheProxy<K, V> extends AsyncSupportAdapter<IgniteCache<K, V
                 qry.getTimeInterval(),
                 qry.isAutoUnsubscribe(),
                 loc,
-                keepBinary);
+                keepBinary,
+                qry.isIncludeExpired());
 
             final QueryCursor<Cache.Entry<K, V>> cur =
                 qry.getInitialQuery() != null ? query(qry.getInitialQuery()) : null;

http://git-wip-us.apache.org/repos/asf/ignite/blob/aedfde69/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java
index 195f3ae..a8e5a6b 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/cache/query/continuous/CacheContinuousQueryManager.java
@@ -421,7 +421,8 @@ public class CacheContinuousQueryManager extends GridCacheManagerAdapter {
         long timeInterval,
         boolean autoUnsubscribe,
         boolean loc,
-        final boolean keepBinary) throws IgniteCheckedException
+        final boolean keepBinary,
+        final boolean includeExpired) throws IgniteCheckedException
     {
         IgniteClosure<Boolean, CacheContinuousQueryHandler> clsr;
 
@@ -438,7 +439,7 @@ public class CacheContinuousQueryManager extends GridCacheManagerAdapter {
                             rmtFilterFactory,
                             true,
                             false,
-                            true,
+                            !includeExpired,
                             false,
                             null);
                     else {
@@ -456,7 +457,7 @@ public class CacheContinuousQueryManager extends GridCacheManagerAdapter {
                             (CacheEntryEventSerializableFilter)fltr,
                             true,
                             false,
-                            true,
+                            !includeExpired,
                             false);
                     }
 
@@ -473,7 +474,7 @@ public class CacheContinuousQueryManager extends GridCacheManagerAdapter {
                         rmtFilter,
                         true,
                         false,
-                        true,
+                        !includeExpired,
                         false);
                 }
             };

http://git-wip-us.apache.org/repos/asf/ignite/blob/aedfde69/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryAbstractSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryAbstractSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryAbstractSelfTest.java
index 3d238af..08acc42 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryAbstractSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/query/continuous/GridCacheContinuousQueryAbstractSelfTest.java
@@ -34,6 +34,9 @@ import javax.cache.Cache;
 import javax.cache.configuration.Factory;
 import javax.cache.event.CacheEntryEvent;
 import javax.cache.event.CacheEntryUpdatedListener;
+import javax.cache.event.EventType;
+import javax.cache.expiry.CreatedExpiryPolicy;
+import javax.cache.expiry.Duration;
 import javax.cache.integration.CacheWriterException;
 import org.apache.ignite.Ignite;
 import org.apache.ignite.IgniteCache;
@@ -71,7 +74,6 @@ import org.apache.ignite.testframework.GridTestUtils;
 import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
 import org.jetbrains.annotations.Nullable;
 import org.jsr166.ConcurrentHashMap8;
-import org.jsr166.ConcurrentLinkedDeque8;
 
 import static java.util.concurrent.TimeUnit.MILLISECONDS;
 import static java.util.concurrent.TimeUnit.SECONDS;
@@ -1094,6 +1096,50 @@ public abstract class GridCacheContinuousQueryAbstractSelfTest extends GridCommo
     }
 
     /**
+     * @throws Exception If failed.
+     */
+    public void testExpired() throws Exception {
+        IgniteCache<Object, Object> cache = grid(0).cache(null).
+            withExpiryPolicy(new CreatedExpiryPolicy(new Duration(MILLISECONDS, 1000)));
+
+        final Map<Object, Object> map = new ConcurrentHashMap8<>();
+        final CountDownLatch latch = new CountDownLatch(2);
+
+        ContinuousQuery<Object, Object> qry = new ContinuousQuery<>();
+
+        qry.setIncludeExpired(true);
+
+        qry.setLocalListener(new CacheEntryUpdatedListener<Object, Object>() {
+            @Override public void onUpdated(Iterable<CacheEntryEvent<?, ?>> evts) {
+                for (CacheEntryEvent<?, ?> e : evts) {
+                    if (e.getEventType() == EventType.EXPIRED) {
+                        assertNull(e.getValue());
+
+                        map.put(e.getKey(), e.getOldValue());
+
+                        latch.countDown();
+                    }
+                }
+            }
+        });
+
+        try (QueryCursor<Cache.Entry<Object, Object>> ignored = cache.query(qry)) {
+            cache.put(1, 1);
+            cache.put(2, 2);
+
+            // Wait for expiration.
+            Thread.sleep(2000);
+
+            assert latch.await(LATCH_TIMEOUT, MILLISECONDS);
+
+            assertEquals(2, map.size());
+
+            assertEquals(1, (int)map.get(1));
+            assertEquals(2, (int)map.get(2));
+        }
+    }
+
+    /**
      *
      */
     private static class StoreFactory implements Factory<CacheStore> {


[24/50] [abbrv] ignite git commit: IGNITE-3055: IgniteDataStreamer can't be timed out

Posted by vo...@apache.org.
IGNITE-3055: IgniteDataStreamer can't be timed out


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 10224dfee22b497bc671f878028881f99465a4c8
Parents: 06b24a9
Author: Vladislav Pyatkov <vl...@gmail.com>
Authored: Wed Jul 13 15:24:53 2016 +0300
Committer: Denis Magda <dm...@gridgain.com>
Committed: Wed Jul 13 15:24:53 2016 +0300

----------------------------------------------------------------------
 .../org/apache/ignite/IgniteDataStreamer.java   |  52 +++++-
 .../IgniteDataStreamerTimeoutException.java     |  45 +++++
 .../datastreamer/DataStreamerImpl.java          |  71 ++++++--
 .../ignite/internal/util/IgniteUtils.java       |  21 +++
 .../datastreamer/DataStreamerTimeoutTest.java   | 163 +++++++++++++++++++
 .../ignite/testsuites/IgniteCacheTestSuite.java |   2 +
 6 files changed, 335 insertions(+), 19 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/10224dfe/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamer.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamer.java b/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamer.java
index 20d0057..887443f 100644
--- a/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamer.java
+++ b/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamer.java
@@ -96,6 +96,9 @@ public interface IgniteDataStreamer<K, V> extends AutoCloseable {
     /** Default per node buffer size. */
     public static final int DFLT_PER_NODE_BUFFER_SIZE = 1024;
 
+    /** Default timeout for streamer's operations. */
+    public static final long DFLT_UNLIMIT_TIMEOUT = -1;
+
     /**
      * Name of cache to stream data to.
      *
@@ -198,6 +201,29 @@ public interface IgniteDataStreamer<K, V> extends AutoCloseable {
     public void perNodeParallelOperations(int parallelOps);
 
     /**
+     * Sets the timeout that is used in the following cases:
+     * <ul>
+     * <li>any data addition method can be blocked when all per node parallel operations are exhausted.
+     * The timeout defines the max time you will be blocked waiting for a permit to add a chunk of data
+     * into the streamer;</li>
+     * <li>Total timeout time for {@link #flush()} operation;</li>
+     * <li>Total timeout time for {@link #close()} operation.</li>
+     * </ul>
+     * By default the timeout is disabled.
+     *
+     * @param timeout Timeout in milliseconds.
+     * @throws IllegalArgumentException If {@param timeout} is zero or less than {@code -1}.
+     */
+    public void timeout(long timeout);
+
+    /**
+     * Gets timeout set by {@link #timeout(long)}.
+     *
+     * @return Timeout in milliseconds.
+     */
+    public long timeout();
+
+    /**
      * Gets automatic flush frequency. Essentially, this is the time after which the
      * streamer will make an attempt to submit all data added so far to remote nodes.
      * Note that there is no guarantee that data will be delivered after this concrete
@@ -287,10 +313,11 @@ public interface IgniteDataStreamer<K, V> extends AutoCloseable {
      * @throws IgniteInterruptedException If thread has been interrupted.
      * @throws IllegalStateException If grid has been concurrently stopped or
      *      {@link #close(boolean)} has already been called on streamer.
+     * @throws IgniteDataStreamerTimeoutException If {@code timeout} is exceeded.
      * @see #allowOverwrite()
      */
     public IgniteFuture<?> addData(K key, @Nullable V val) throws CacheException, IgniteInterruptedException,
-        IllegalStateException;
+        IllegalStateException, IgniteDataStreamerTimeoutException;
 
     /**
      * Adds data for streaming on remote node. This method can be called from multiple
@@ -310,10 +337,11 @@ public interface IgniteDataStreamer<K, V> extends AutoCloseable {
      * @throws IgniteInterruptedException If thread has been interrupted.
      * @throws IllegalStateException If grid has been concurrently stopped or
      *      {@link #close(boolean)} has already been called on streamer.
+     * @throws IgniteDataStreamerTimeoutException If {@code timeout} is exceeded.
      * @see #allowOverwrite()
      */
     public IgniteFuture<?> addData(Map.Entry<K, V> entry) throws CacheException, IgniteInterruptedException,
-        IllegalStateException;
+        IllegalStateException, IgniteDataStreamerTimeoutException;
 
     /**
      * Adds data for streaming on remote node. This method can be called from multiple
@@ -330,10 +358,12 @@ public interface IgniteDataStreamer<K, V> extends AutoCloseable {
      * @param entries Collection of entries to be streamed.
      * @throws IllegalStateException If grid has been concurrently stopped or
      *      {@link #close(boolean)} has already been called on streamer.
+     * @throws IgniteDataStreamerTimeoutException If {@code timeout} is exceeded.
      * @return Future for this stream operation.
      * @see #allowOverwrite()
      */
-    public IgniteFuture<?> addData(Collection<? extends Map.Entry<K, V>> entries) throws IllegalStateException;
+    public IgniteFuture<?> addData(Collection<? extends Map.Entry<K, V>> entries) throws IllegalStateException,
+        IgniteDataStreamerTimeoutException;
 
     /**
      * Adds data for streaming on remote node. This method can be called from multiple
@@ -350,10 +380,12 @@ public interface IgniteDataStreamer<K, V> extends AutoCloseable {
      * @param entries Map to be streamed.
      * @throws IllegalStateException If grid has been concurrently stopped or
      *      {@link #close(boolean)} has already been called on streamer.
+     * @throws IgniteDataStreamerTimeoutException If {@code timeout} is exceeded.
      * @return Future for this stream operation.
      * @see #allowOverwrite()
      */
-    public IgniteFuture<?> addData(Map<K, V> entries) throws IllegalStateException;
+    public IgniteFuture<?> addData(Map<K, V> entries) throws IllegalStateException,
+        IgniteDataStreamerTimeoutException;
 
     /**
      * Streams any remaining data, but doesn't close the streamer. Data can be still added after
@@ -368,9 +400,11 @@ public interface IgniteDataStreamer<K, V> extends AutoCloseable {
      * @throws IgniteInterruptedException If thread has been interrupted.
      * @throws IllegalStateException If grid has been concurrently stopped or
      *      {@link #close(boolean)} has already been called on streamer.
+     * @throws IgniteDataStreamerTimeoutException If {@code timeout} is exceeded.
      * @see #tryFlush()
      */
-    public void flush() throws CacheException, IgniteInterruptedException, IllegalStateException;
+    public void flush() throws CacheException, IgniteInterruptedException, IllegalStateException,
+        IgniteDataStreamerTimeoutException;
 
     /**
      * Makes an attempt to stream remaining data. This method is mostly similar to {@link #flush},
@@ -390,8 +424,10 @@ public interface IgniteDataStreamer<K, V> extends AutoCloseable {
      * @param cancel {@code True} to cancel ongoing streaming operations.
      * @throws CacheException If failed to map key to node.
      * @throws IgniteInterruptedException If thread has been interrupted.
+     * @throws IgniteDataStreamerTimeoutException If {@code timeout} is exceeded, only if {@param cancel} is {@code false}.
      */
-    public void close(boolean cancel) throws CacheException, IgniteInterruptedException;
+    public void close(boolean cancel) throws CacheException, IgniteInterruptedException,
+        IgniteDataStreamerTimeoutException;
 
     /**
      * Closes data streamer. This method is identical to calling {@link #close(boolean) close(false)} method.
@@ -401,7 +437,9 @@ public interface IgniteDataStreamer<K, V> extends AutoCloseable {
      *
      * @throws CacheException If failed to close data streamer.
      * @throws IgniteInterruptedException If thread has been interrupted.
+     * @throws IgniteDataStreamerTimeoutException If {@code timeout} is exceeded.
      */
-    @Override public void close() throws CacheException, IgniteInterruptedException;
+    @Override public void close() throws CacheException, IgniteInterruptedException,
+        IgniteDataStreamerTimeoutException;
 
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/10224dfe/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamerTimeoutException.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamerTimeoutException.java b/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamerTimeoutException.java
new file mode 100644
index 0000000..c6c7367
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamerTimeoutException.java
@@ -0,0 +1,45 @@
+/*
+ * 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;
+
+/**
+ * Exception is thrown when timeout of some {@link IgniteDataStreamer} operations occurs.
+ */
+public class IgniteDataStreamerTimeoutException extends IgniteException {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /**
+     * Creates new timeout exception with given error message.
+     *
+     * @param msg Error message.
+     */
+    public IgniteDataStreamerTimeoutException(String msg) {
+        super(msg);
+    }
+
+    /**
+     * Creates new timeout exception with given error message and optional nested exception.
+     *
+     * @param msg Error message.
+     * @param cause Optional nested exception (can be {@code null}).
+     */
+    public IgniteDataStreamerTimeoutException(String msg, Throwable cause) {
+        super(msg, cause);
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/10224dfe/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerImpl.java
index 9dc6a7f..21df559 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerImpl.java
@@ -46,6 +46,7 @@ import org.apache.ignite.IgniteDataStreamer;
 import org.apache.ignite.IgniteException;
 import org.apache.ignite.IgniteInterruptedException;
 import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.IgniteDataStreamerTimeoutException;
 import org.apache.ignite.cluster.ClusterNode;
 import org.apache.ignite.cluster.ClusterTopologyException;
 import org.apache.ignite.configuration.CacheConfiguration;
@@ -53,6 +54,7 @@ import org.apache.ignite.events.DiscoveryEvent;
 import org.apache.ignite.events.Event;
 import org.apache.ignite.internal.GridKernalContext;
 import org.apache.ignite.internal.IgniteClientDisconnectedCheckedException;
+import org.apache.ignite.internal.IgniteFutureTimeoutCheckedException;
 import org.apache.ignite.internal.IgniteInternalFuture;
 import org.apache.ignite.internal.IgniteInterruptedCheckedException;
 import org.apache.ignite.internal.cluster.ClusterTopologyCheckedException;
@@ -147,6 +149,9 @@ public class DataStreamerImpl<K, V> implements IgniteDataStreamer<K, V>, Delayed
     private int parallelOps = DFLT_MAX_PARALLEL_OPS;
 
     /** */
+    private long timeout = DFLT_UNLIMIT_TIMEOUT;
+
+    /** */
     private long autoFlushFreq;
 
     /** Mapping. */
@@ -453,6 +458,19 @@ public class DataStreamerImpl<K, V> implements IgniteDataStreamer<K, V>, Delayed
     }
 
     /** {@inheritDoc} */
+    @Override public void timeout(long timeout) {
+        if (timeout < -1 || timeout == 0)
+            throw new IllegalArgumentException();
+
+        this.timeout = timeout;
+    }
+
+    /** {@inheritDoc} */
+    @Override public long timeout() {
+        return this.timeout;
+    }
+
+    /** {@inheritDoc} */
     @Override public long autoFlushFrequency() {
         return autoFlushFreq;
     }
@@ -517,6 +535,9 @@ public class DataStreamerImpl<K, V> implements IgniteDataStreamer<K, V>, Delayed
 
             return new IgniteCacheFutureImpl<>(resFut);
         }
+        catch (IgniteDataStreamerTimeoutException e) {
+            throw e;
+        }
         catch (IgniteException e) {
             return new IgniteFinishedFutureImpl<>(e);
         }
@@ -572,7 +593,7 @@ public class DataStreamerImpl<K, V> implements IgniteDataStreamer<K, V>, Delayed
         catch (Throwable e) {
             resFut.onDone(e);
 
-            if (e instanceof Error)
+            if (e instanceof Error || e instanceof IgniteDataStreamerTimeoutException)
                 throw e;
 
             return new IgniteFinishedFutureImpl<>(e);
@@ -854,9 +875,20 @@ public class DataStreamerImpl<K, V> implements IgniteDataStreamer<K, V>, Delayed
 
                 boolean err = false;
 
+                long startTimeMillis = U.currentTimeMillis();
+
                 for (IgniteInternalFuture fut = q.poll(); fut != null; fut = q.poll()) {
                     try {
-                        fut.get();
+                        if (timeout == DFLT_UNLIMIT_TIMEOUT)
+                            fut.get();
+                        else {
+                            long timeRemain = timeout - U.currentTimeMillis() + startTimeMillis;
+
+                            if (timeRemain <= 0)
+                                throw new IgniteDataStreamerTimeoutException("Data streamer exceeded timeout on flush.");
+
+                            fut.get(timeRemain);
+                        }
                     }
                     catch (IgniteClientDisconnectedCheckedException e) {
                         if (log.isDebugEnabled())
@@ -864,6 +896,12 @@ public class DataStreamerImpl<K, V> implements IgniteDataStreamer<K, V>, Delayed
 
                         throw CU.convertToCacheException(e);
                     }
+                    catch (IgniteFutureTimeoutCheckedException e) {
+                        if (log.isDebugEnabled())
+                            log.debug("Failed to flush buffer: " + e);
+
+                        throw new IgniteDataStreamerTimeoutException("Data streamer exceeded timeout on flush.", e);
+                    }
                     catch (IgniteCheckedException e) {
                         if (log.isDebugEnabled())
                             log.debug("Failed to flush buffer: " + e);
@@ -976,8 +1014,6 @@ public class DataStreamerImpl<K, V> implements IgniteDataStreamer<K, V>, Delayed
         if (log.isDebugEnabled())
             log.debug("Closing data streamer [ldr=" + this + ", cancel=" + cancel + ']');
 
-        IgniteCheckedException e = null;
-
         try {
             // Assuming that no methods are called on this loader after this method is called.
             if (cancel) {
@@ -993,14 +1029,12 @@ public class DataStreamerImpl<K, V> implements IgniteDataStreamer<K, V>, Delayed
 
             ctx.io().removeMessageListener(topic);
         }
-        catch (IgniteCheckedException e0) {
-            e = e0;
+        catch (IgniteCheckedException | IgniteDataStreamerTimeoutException e) {
+            fut.onDone(e);
+            throw e;
         }
 
-        fut.onDone(null, e != null ? e : err);
-
-        if (e != null)
-            throw e;
+        fut.onDone(err);
     }
 
     /**
@@ -1242,7 +1276,15 @@ public class DataStreamerImpl<K, V> implements IgniteDataStreamer<K, V>, Delayed
          * @throws IgniteInterruptedCheckedException If thread has been interrupted.
          */
         private void incrementActiveTasks() throws IgniteInterruptedCheckedException {
-            U.acquire(sem);
+            if (timeout == DFLT_UNLIMIT_TIMEOUT)
+                U.acquire(sem);
+            else
+                if (!U.tryAcquire(sem, timeout, TimeUnit.MILLISECONDS)) {
+                    if (log.isDebugEnabled())
+                        log.debug("Failed to add parallel operation.");
+
+                    throw new IgniteDataStreamerTimeoutException("Data streamer exceeded timeout when starts parallel operation.");
+                }
         }
 
         /**
@@ -1268,7 +1310,12 @@ public class DataStreamerImpl<K, V> implements IgniteDataStreamer<K, V>, Delayed
             assert !entries.isEmpty();
             assert curFut != null;
 
-            incrementActiveTasks();
+            try {
+                incrementActiveTasks();
+            } catch (IgniteDataStreamerTimeoutException e) {
+                curFut.onDone(e);
+                throw e;
+            }
 
             IgniteInternalFuture<Object> fut;
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/10224dfe/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
index fa18923..08c9219 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
@@ -7447,6 +7447,27 @@ public abstract class IgniteUtils {
     }
 
     /**
+     * Tries to acquire a permit from provided semaphore during {@code timeout}.
+     *
+     * @param sem Semaphore.
+     * @param timeout The maximum time to wait.
+     * @param unit The unit of the {@code time} argument.
+     * @throws org.apache.ignite.internal.IgniteInterruptedCheckedException Wrapped {@link InterruptedException}.
+     * @return {@code True} if acquires a permit, {@code false} another.
+     */
+    public static boolean tryAcquire(Semaphore sem, long timeout, TimeUnit unit)
+        throws IgniteInterruptedCheckedException {
+        try {
+            return sem.tryAcquire(timeout, unit);
+        }
+        catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+
+            throw new IgniteInterruptedCheckedException(e);
+        }
+    }
+
+    /**
      * Gets cache attributes for the node.
      *
      * @param n Node to get cache attributes for.

http://git-wip-us.apache.org/repos/asf/ignite/blob/10224dfe/modules/core/src/test/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerTimeoutTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerTimeoutTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerTimeoutTest.java
new file mode 100644
index 0000000..4e981b7
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/datastreamer/DataStreamerTimeoutTest.java
@@ -0,0 +1,163 @@
+/*
+ * 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.datastreamer;
+
+import java.util.Collection;
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.IgniteDataStreamer;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.IgniteDataStreamerTimeoutException;
+import org.apache.ignite.configuration.CacheConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgniteInterruptedCheckedException;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.stream.StreamReceiver;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+import static org.apache.ignite.cache.CacheMode.PARTITIONED;
+import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
+
+/**
+ * Test timeout for Data streamer.
+ */
+public class DataStreamerTimeoutTest extends GridCommonAbstractTest {
+
+    /** Cache name. */
+    public static final String CACHE_NAME = "cacheName";
+
+    /** Timeout. */
+    public static final int TIMEOUT = 1_000;
+
+    /** Amount of entries. */
+    public static final int ENTRY_AMOUNT = 100;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        cfg.setCacheConfiguration(cacheConfiguration());
+
+        return cfg;
+    }
+
+    /**
+     * Gets cache configuration.
+     *
+     * @return Cache configuration.
+     */
+    private CacheConfiguration cacheConfiguration() {
+        CacheConfiguration cacheCfg = defaultCacheConfiguration();
+
+        cacheCfg.setCacheMode(PARTITIONED);
+        cacheCfg.setBackups(1);
+        cacheCfg.setWriteSynchronizationMode(FULL_SYNC);
+        cacheCfg.setName(CACHE_NAME);
+
+        return cacheCfg;
+    }
+
+    /**
+     * Test timeout on {@code DataStreamer.addData()} method
+     * @throws Exception If fail.
+     */
+    public void testTimeoutOnCloseMethod() throws Exception {
+        Ignite ignite = startGrid(1);
+
+        boolean thrown = false;
+
+        try (IgniteDataStreamer ldr = ignite.dataStreamer(CACHE_NAME)) {
+            ldr.timeout(TIMEOUT);
+            ldr.receiver(new TestDataReceiver());
+            ldr.perNodeBufferSize(ENTRY_AMOUNT);
+
+            for (int i=0; i < ENTRY_AMOUNT; i++)
+                ldr.addData(i, i);
+
+        }
+        catch (IgniteDataStreamerTimeoutException e) {
+            assertEquals(e.getMessage(), "Data streamer exceeded timeout on flush.");
+            thrown = true;
+        }
+        finally {
+            stopAllGrids();
+        }
+
+        assertTrue(thrown);
+    }
+
+    /**
+     * Test timeout on {@code DataStreamer.close()} method
+     * @throws Exception If fail.
+     */
+    public void testTimeoutOnAddDataMethod() throws Exception {
+        Ignite ignite = startGrid(1);
+
+        boolean thrown = false;
+
+        IgniteDataStreamer ldr = ignite.dataStreamer(CACHE_NAME);
+
+        try {
+            ldr.timeout(TIMEOUT);
+            ldr.receiver(new TestDataReceiver());
+            ldr.perNodeBufferSize(ENTRY_AMOUNT/2);
+            ldr.perNodeParallelOperations(1);
+
+            try {
+                for (int i=0; i < ENTRY_AMOUNT; i++)
+                    ldr.addData(i, i);
+            }
+            catch (IgniteDataStreamerTimeoutException e) {
+                assertEquals(e.getMessage(), "Data streamer exceeded timeout when starts parallel operation.");
+
+                thrown = true;
+            }
+
+        }
+        finally {
+            if (thrown)
+                ldr.close(true);
+
+            stopAllGrids();
+        }
+
+        assertTrue(thrown);
+    }
+
+    /**
+     * Test receiver for timeout expiration emulation.
+     */
+    private static class TestDataReceiver implements StreamReceiver {
+
+        /** Is first. */
+        boolean isFirst = true;
+
+        /** {@inheritDoc} */
+        @Override public void receive(IgniteCache cache, Collection collection) throws IgniteException {
+            try {
+                if (isFirst)
+                    U.sleep(2 * TIMEOUT);
+
+                isFirst = false;
+            }
+            catch (IgniteInterruptedCheckedException e) {
+                throw new IgniteException(e);
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/10224dfe/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
index 33aae9a..0b9345d 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteCacheTestSuite.java
@@ -138,6 +138,7 @@ import org.apache.ignite.internal.processors.datastreamer.DataStreamProcessorSel
 import org.apache.ignite.internal.processors.datastreamer.DataStreamerImplSelfTest;
 import org.apache.ignite.internal.processors.datastreamer.DataStreamerMultiThreadedSelfTest;
 import org.apache.ignite.internal.processors.datastreamer.DataStreamerMultinodeCreateCacheTest;
+import org.apache.ignite.internal.processors.datastreamer.DataStreamerTimeoutTest;
 import org.apache.ignite.internal.processors.datastreamer.DataStreamerUpdateAfterLoadTest;
 import org.apache.ignite.testframework.GridTestUtils;
 
@@ -244,6 +245,7 @@ public class IgniteCacheTestSuite extends TestSuite {
             suite.addTestSuite(DataStreamerMultiThreadedSelfTest.class);
         suite.addTestSuite(DataStreamerMultinodeCreateCacheTest.class);
         suite.addTestSuite(DataStreamerImplSelfTest.class);
+        suite.addTestSuite(DataStreamerTimeoutTest.class);
         GridTestUtils.addTestIfNeeded(suite, GridCacheEntryMemorySizeSelfTest.class, ignoredTests);
         suite.addTestSuite(GridCacheClearAllSelfTest.class);
         suite.addTestSuite(GridCacheObjectToStringSelfTest.class);


[11/50] [abbrv] ignite git commit: Merge remote-tracking branch 'community/gridgain-7.5.29' into gridgain-7.5.29

Posted by vo...@apache.org.
Merge remote-tracking branch 'community/gridgain-7.5.29' into gridgain-7.5.29


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

Branch: refs/heads/ignite-1.5.31-1
Commit: f52fb797b61b5f870206e54795d379a8d023279b
Parents: 1b7428b 920005d
Author: Valentin Kulichenko <va...@gmail.com>
Authored: Thu Jul 7 00:08:47 2016 -0700
Committer: Valentin Kulichenko <va...@gmail.com>
Committed: Thu Jul 7 00:08:47 2016 -0700

----------------------------------------------------------------------
 .../apache/ignite/IgniteSystemProperties.java   |   8 +-
 .../apache/ignite/internal/IgniteKernal.java    |  21 ++
 .../processors/cache/GridCacheAdapter.java      |   4 +
 .../processors/cache/GridCacheIoManager.java    | 150 +++++++++-
 .../processors/cache/GridCacheMessage.java      |   9 +
 .../GridCachePartitionExchangeManager.java      | 147 +++++++++-
 .../cache/GridCacheSharedContext.java           |  68 +++++
 .../processors/cache/GridCacheUtils.java        |  21 ++
 .../distributed/GridCacheTxRecoveryFuture.java  |  70 ++++-
 .../distributed/GridCacheTxRecoveryRequest.java |   8 +
 .../GridCacheTxRecoveryResponse.java            |   8 +
 .../distributed/GridDistributedLockRequest.java |   6 +
 .../GridDistributedLockResponse.java            |   6 +
 .../GridDistributedTxFinishRequest.java         |   7 +-
 .../GridDistributedTxFinishResponse.java        |   8 +
 .../GridDistributedTxPrepareRequest.java        |   6 +
 .../GridDistributedTxPrepareResponse.java       |   9 +-
 .../GridDistributedUnlockRequest.java           |   6 +
 .../distributed/dht/GridDhtLockFuture.java      |  52 ++--
 .../dht/GridDhtTransactionalCacheAdapter.java   |  77 ++++-
 .../distributed/dht/GridDhtTxFinishFuture.java  |  92 +++++-
 .../cache/distributed/dht/GridDhtTxLocal.java   |  27 +-
 .../distributed/dht/GridDhtTxPrepareFuture.java | 124 +++++++-
 .../dht/atomic/GridDhtAtomicCache.java          | 137 ++++++---
 .../GridDhtAtomicDeferredUpdateResponse.java    |   7 +
 .../dht/atomic/GridDhtAtomicUpdateFuture.java   |  47 +++-
 .../dht/atomic/GridDhtAtomicUpdateRequest.java  |   6 +
 .../dht/atomic/GridDhtAtomicUpdateResponse.java |   6 +
 .../dht/atomic/GridNearAtomicUpdateFuture.java  |  54 +++-
 .../dht/atomic/GridNearAtomicUpdateRequest.java |   6 +
 .../atomic/GridNearAtomicUpdateResponse.java    |   6 +
 .../dht/colocated/GridDhtColocatedCache.java    |  10 +
 .../colocated/GridDhtColocatedLockFuture.java   |  71 +++--
 .../GridDhtPartitionsExchangeFuture.java        |  26 +-
 .../near/GridNearOptimisticTxPrepareFuture.java |  32 +++
 .../GridNearPessimisticTxPrepareFuture.java     |  34 ++-
 .../near/GridNearTxFinishFuture.java            |  97 ++++++-
 .../near/GridNearTxPrepareFutureAdapter.java    |   7 +-
 .../cache/transactions/IgniteTxHandler.java     | 281 ++++++++++++++-----
 .../processors/task/GridTaskWorker.java         |   2 +-
 .../util/nio/GridNioRecoveryDescriptor.java     |  19 +-
 .../ignite/internal/util/nio/GridNioServer.java |  50 +++-
 .../util/nio/GridSelectorNioSessionImpl.java    |   7 +
 .../visor/compute/VisorGatewayTask.java         |   3 +-
 .../visor/node/VisorNodeDataCollectorTask.java  |  26 --
 .../communication/tcp/TcpCommunicationSpi.java  | 167 +++++++----
 .../resources/META-INF/classnames.properties    |  78 ++++-
 modules/core/src/test/config/log4j-test.xml     |   6 +
 ...gniteCacheMessageRecoveryIdleConnection.java | 154 ++++++++++
 .../ignite/testsuites/IgniteCacheTestSuite.java |   2 +
 50 files changed, 1886 insertions(+), 389 deletions(-)
----------------------------------------------------------------------



[27/50] [abbrv] ignite git commit: IgniteDataStreamer: fixed JavaDoc

Posted by vo...@apache.org.
IgniteDataStreamer: fixed JavaDoc


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 2537e0f62a1a1ecba315b18f4ed9bf38ff99d5df
Parents: 10224df
Author: Denis Magda <dm...@gridgain.com>
Authored: Fri Jul 15 09:35:41 2016 +0300
Committer: Denis Magda <dm...@gridgain.com>
Committed: Fri Jul 15 09:35:41 2016 +0300

----------------------------------------------------------------------
 .../core/src/main/java/org/apache/ignite/IgniteDataStreamer.java | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/2537e0f6/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamer.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamer.java b/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamer.java
index 887443f..472c5e4 100644
--- a/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamer.java
+++ b/modules/core/src/main/java/org/apache/ignite/IgniteDataStreamer.java
@@ -212,7 +212,7 @@ public interface IgniteDataStreamer<K, V> extends AutoCloseable {
      * By default the timeout is disabled.
      *
      * @param timeout Timeout in milliseconds.
-     * @throws IllegalArgumentException If {@param timeout} is zero or less than {@code -1}.
+     * @throws IllegalArgumentException If timeout is zero or less than {@code -1}.
      */
     public void timeout(long timeout);
 
@@ -424,7 +424,7 @@ public interface IgniteDataStreamer<K, V> extends AutoCloseable {
      * @param cancel {@code True} to cancel ongoing streaming operations.
      * @throws CacheException If failed to map key to node.
      * @throws IgniteInterruptedException If thread has been interrupted.
-     * @throws IgniteDataStreamerTimeoutException If {@code timeout} is exceeded, only if {@param cancel} is {@code false}.
+     * @throws IgniteDataStreamerTimeoutException If {@code timeout} is exceeded, only if cancel is {@code false}.
      */
     public void close(boolean cancel) throws CacheException, IgniteInterruptedException,
         IgniteDataStreamerTimeoutException;


[36/50] [abbrv] ignite git commit: IGNITE-3414: Hadoop: implemented new weight-based map-reduce planner.

Posted by vo...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopDefaultMapReducePlannerSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopDefaultMapReducePlannerSelfTest.java b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopDefaultMapReducePlannerSelfTest.java
index ffa6f7d..a69b72a 100644
--- a/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopDefaultMapReducePlannerSelfTest.java
+++ b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopDefaultMapReducePlannerSelfTest.java
@@ -17,47 +17,27 @@
 
 package org.apache.ignite.internal.processors.hadoop;
 
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteFileSystem;
-import org.apache.ignite.IgniteSpringBean;
 import org.apache.ignite.cluster.ClusterNode;
-import org.apache.ignite.configuration.FileSystemConfiguration;
 import org.apache.ignite.hadoop.mapreduce.IgniteHadoopMapReducePlanner;
 import org.apache.ignite.igfs.IgfsBlockLocation;
-import org.apache.ignite.igfs.IgfsFile;
-import org.apache.ignite.igfs.IgfsMetrics;
-import org.apache.ignite.igfs.IgfsOutputStream;
 import org.apache.ignite.igfs.IgfsPath;
-import org.apache.ignite.igfs.IgfsPathSummary;
-import org.apache.ignite.igfs.mapreduce.IgfsRecordResolver;
-import org.apache.ignite.igfs.mapreduce.IgfsTask;
-import org.apache.ignite.igfs.secondary.IgfsSecondaryFileSystem;
-import org.apache.ignite.internal.GridKernalContext;
-import org.apache.ignite.internal.IgniteEx;
-import org.apache.ignite.internal.cluster.IgniteClusterEx;
-import org.apache.ignite.internal.processors.cache.GridCacheUtilityKey;
-import org.apache.ignite.internal.processors.cache.IgniteInternalCache;
+import org.apache.ignite.internal.processors.hadoop.planner.HadoopAbstractMapReducePlanner;
 import org.apache.ignite.internal.processors.igfs.IgfsBlockLocationImpl;
-import org.apache.ignite.internal.processors.igfs.IgfsContext;
-import org.apache.ignite.internal.processors.igfs.IgfsEx;
-import org.apache.ignite.internal.processors.igfs.IgfsInputStreamAdapter;
-import org.apache.ignite.internal.processors.igfs.IgfsLocalMetrics;
-import org.apache.ignite.internal.processors.igfs.IgfsPaths;
-import org.apache.ignite.internal.processors.igfs.IgfsStatus;
+import org.apache.ignite.internal.processors.igfs.IgfsIgniteMock;
+import org.apache.ignite.internal.processors.igfs.IgfsMock;
 import org.apache.ignite.internal.util.typedef.F;
-import org.apache.ignite.lang.IgniteFuture;
-import org.apache.ignite.lang.IgnitePredicate;
-import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.testframework.GridTestNode;
 import org.apache.ignite.testframework.GridTestUtils;
-import org.jetbrains.annotations.Nullable;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
 
 /**
  *
@@ -90,12 +70,12 @@ public class HadoopDefaultMapReducePlannerSelfTest extends HadoopAbstractSelfTes
     /** */
     private static final String INVALID_HOST_3 = "invalid_host3";
 
-    /** Mocked Grid. */
-    private static final MockIgnite GRID = new MockIgnite();
-
     /** Mocked IGFS. */
     private static final IgniteFileSystem IGFS = new MockIgfs();
 
+    /** Mocked Grid. */
+    private static final IgfsIgniteMock GRID = new IgfsIgniteMock(null, IGFS);
+
     /** Planner. */
     private static final HadoopMapReducePlanner PLANNER = new IgniteHadoopMapReducePlanner();
 
@@ -109,15 +89,15 @@ public class HadoopDefaultMapReducePlannerSelfTest extends HadoopAbstractSelfTes
     private static final ThreadLocal<HadoopMapReducePlan> PLAN = new ThreadLocal<>();
 
     /**
-     *
+     * Static initializer.
      */
     static {
-        GridTestUtils.setFieldValue(PLANNER, "ignite", GRID);
+        GridTestUtils.setFieldValue(PLANNER, HadoopAbstractMapReducePlanner.class, "ignite", GRID);
     }
 
     /** {@inheritDoc} */
     @Override protected void beforeTest() throws Exception {
-        GridTestUtils.setFieldValue(PLANNER, "log", log());
+        GridTestUtils.setFieldValue(PLANNER, HadoopAbstractMapReducePlanner.class, "log", log());
 
         BLOCK_MAP.clear();
         PROXY_MAP.clear();
@@ -445,7 +425,7 @@ public class HadoopDefaultMapReducePlannerSelfTest extends HadoopAbstractSelfTes
         top.add(node2);
         top.add(node3);
 
-        HadoopMapReducePlan plan = PLANNER.preparePlan(new MockJob(reducers, splitList), top, null);
+        HadoopMapReducePlan plan = PLANNER.preparePlan(new HadoopPlannerMockJob(splitList, reducers), top, null);
 
         PLAN.set(plan);
 
@@ -607,81 +587,17 @@ public class HadoopDefaultMapReducePlannerSelfTest extends HadoopAbstractSelfTes
     }
 
     /**
-     * Mocked job.
+     * Mocked IGFS.
      */
-    private static class MockJob implements HadoopJob {
-        /** Reducers count. */
-        private final int reducers;
-
-        /** */
-        private Collection<HadoopInputSplit> splitList;
-
+    private static class MockIgfs extends IgfsMock {
         /**
          * Constructor.
-         *
-         * @param reducers Reducers count.
-         * @param splitList Splits.
          */
-        private MockJob(int reducers, Collection<HadoopInputSplit> splitList) {
-            this.reducers = reducers;
-            this.splitList = splitList;
-        }
-
-        /** {@inheritDoc} */
-        @Override public HadoopJobId id() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public HadoopJobInfo info() {
-            return new HadoopDefaultJobInfo() {
-                @Override public int reducers() {
-                    return reducers;
-                }
-            };
+        public MockIgfs() {
+            super("igfs");
         }
 
         /** {@inheritDoc} */
-        @Override public Collection<HadoopInputSplit> input() throws IgniteCheckedException {
-            return splitList;
-        }
-
-        /** {@inheritDoc} */
-        @Override public HadoopTaskContext getTaskContext(HadoopTaskInfo info) throws IgniteCheckedException {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public void initialize(boolean external, UUID nodeId) throws IgniteCheckedException {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Override public void dispose(boolean external) throws IgniteCheckedException {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Override public void prepareTaskEnvironment(HadoopTaskInfo info) throws IgniteCheckedException {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Override public void cleanupTaskEnvironment(HadoopTaskInfo info) throws IgniteCheckedException {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Override public void cleanupStagingDirectory() {
-            // No-op.
-        }
-    }
-
-    /**
-     * Mocked IGFS.
-     */
-    private static class MockIgfs implements IgfsEx {
-        /** {@inheritDoc} */
         @Override public boolean isProxy(URI path) {
             return PROXY_MAP.containsKey(path) && PROXY_MAP.get(path);
         }
@@ -692,331 +608,8 @@ public class HadoopDefaultMapReducePlannerSelfTest extends HadoopAbstractSelfTes
         }
 
         /** {@inheritDoc} */
-        @Override public Collection<IgfsBlockLocation> affinity(IgfsPath path, long start, long len,
-            long maxLen) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public void stop(boolean cancel) {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsContext context() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsPaths proxyPaths() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsInputStreamAdapter open(IgfsPath path, int bufSize, int seqReadsBeforePrefetch) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsInputStreamAdapter open(IgfsPath path) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsInputStreamAdapter open(IgfsPath path, int bufSize) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsStatus globalSpace() throws IgniteCheckedException {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public void globalSampling(@Nullable Boolean val) throws IgniteCheckedException {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Nullable @Override public Boolean globalSampling() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsLocalMetrics localMetrics() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public long groupBlockSize() {
-            return 0;
-        }
-
-        /** {@inheritDoc} */
-        @Nullable @Override public String clientLogDirectory() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public void clientLogDirectory(String logDir) {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Override public boolean evictExclude(IgfsPath path, boolean primary) {
-            return false;
-        }
-
-        /** {@inheritDoc} */
-        @Nullable @Override public String name() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public FileSystemConfiguration configuration() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
         @Override public boolean exists(IgfsPath path) {
             return true;
         }
-
-        /** {@inheritDoc} */
-        @Nullable @Override public IgfsFile info(IgfsPath path) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsPathSummary summary(IgfsPath path) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Nullable @Override public IgfsFile update(IgfsPath path, Map<String, String> props) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public void rename(IgfsPath src, IgfsPath dest) {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Override public boolean delete(IgfsPath path, boolean recursive) {
-            return false;
-        }
-
-        /** {@inheritDoc} */
-        @Override public void mkdirs(IgfsPath path) {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Override public void mkdirs(IgfsPath path, @Nullable Map<String, String> props) {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Override public Collection<IgfsPath> listPaths(IgfsPath path) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public Collection<IgfsFile> listFiles(IgfsPath path) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public long usedSpaceSize() {
-            return 0;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsOutputStream create(IgfsPath path, boolean overwrite) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsOutputStream create(IgfsPath path, int bufSize, boolean overwrite, int replication,
-            long blockSize, @Nullable Map<String, String> props) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsOutputStream create(IgfsPath path, int bufSize, boolean overwrite,
-            @Nullable IgniteUuid affKey, int replication, long blockSize, @Nullable Map<String, String> props) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsOutputStream append(IgfsPath path, boolean create) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsOutputStream append(IgfsPath path, int bufSize, boolean create,
-            @Nullable Map<String, String> props) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public void setTimes(IgfsPath path, long accessTime, long modificationTime) {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsMetrics metrics() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public void resetMetrics() {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Override public long size(IgfsPath path) {
-            return 0;
-        }
-
-        /** {@inheritDoc} */
-        @Override public void format() {
-            // No-op.
-        }
-
-        /** {@inheritDoc} */
-        @Override public <T, R> R execute(IgfsTask<T, R> task, @Nullable IgfsRecordResolver rslvr,
-            Collection<IgfsPath> paths, @Nullable T arg) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public <T, R> R execute(IgfsTask<T, R> task, @Nullable IgfsRecordResolver rslvr,
-            Collection<IgfsPath> paths, boolean skipNonExistentFiles, long maxRangeLen, @Nullable T arg) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public <T, R> R execute(Class<? extends IgfsTask<T, R>> taskCls,
-            @Nullable IgfsRecordResolver rslvr, Collection<IgfsPath> paths, @Nullable T arg) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public <T, R> R execute(Class<? extends IgfsTask<T, R>> taskCls,
-            @Nullable IgfsRecordResolver rslvr, Collection<IgfsPath> paths, boolean skipNonExistentFiles,
-            long maxRangeLen, @Nullable T arg) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgniteUuid nextAffinityKey() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgniteFileSystem withAsync() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public boolean isAsync() {
-            return false;
-        }
-
-        /** {@inheritDoc} */
-        @Override public <R> IgniteFuture<R> future() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgfsSecondaryFileSystem asSecondary() {
-            return null;
-        }
-    }
-
-    /**
-     * Mocked Grid.
-     */
-    @SuppressWarnings("ExternalizableWithoutPublicNoArgConstructor")
-    private static class MockIgnite extends IgniteSpringBean implements IgniteEx {
-        /** {@inheritDoc} */
-        @Override public IgniteClusterEx cluster() {
-            return (IgniteClusterEx)super.cluster();
-        }
-
-        /** {@inheritDoc} */
-        @Override public IgniteFileSystem igfsx(String name) {
-            assert F.eq("igfs", name);
-
-            return IGFS;
-        }
-
-        /** {@inheritDoc} */
-        @Override public Hadoop hadoop() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public String name() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public <K extends GridCacheUtilityKey, V> IgniteInternalCache<K, V> utilityCache() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Nullable @Override public <K, V> IgniteInternalCache<K, V> cachex(@Nullable String name) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Nullable @Override public <K, V> IgniteInternalCache<K, V> cachex() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @SuppressWarnings("unchecked")
-        @Override public Collection<IgniteInternalCache<?, ?>> cachesx(@Nullable IgnitePredicate<? super IgniteInternalCache<?, ?>>... p) {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public boolean eventUserRecordable(int type) {
-            return false;
-        }
-
-        /** {@inheritDoc} */
-        @Override public boolean allEventsUserRecordable(int[] types) {
-            return false;
-        }
-
-        /** {@inheritDoc} */
-        @Override public boolean isJmxRemoteEnabled() {
-            return false;
-        }
-
-        /** {@inheritDoc} */
-        @Override public boolean isRestartEnabled() {
-            return false;
-        }
-
-        /** {@inheritDoc} */
-        @Override public ClusterNode localNode() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public String latestVersion() {
-            return null;
-        }
-
-        /** {@inheritDoc} */
-        @Override public GridKernalContext context() {
-            return null;
-        }
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopMapReduceTest.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopMapReduceTest.java b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopMapReduceTest.java
index 1cb4f74..5d1de38 100644
--- a/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopMapReduceTest.java
+++ b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopMapReduceTest.java
@@ -20,9 +20,7 @@ package org.apache.ignite.internal.processors.hadoop;
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
-import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 import java.util.SortedMap;
 import java.util.TreeMap;
@@ -395,10 +393,24 @@ public class HadoopMapReduceTest extends HadoopAbstractWordCountTest {
         cfg.setLocalHost("127.0.0.1");
         cfg.setConnectorConfiguration(null);
 
+        HadoopConfiguration hadoopCfg = createHadoopConfiguration();
+
+        if (hadoopCfg != null)
+            cfg.setHadoopConfiguration(hadoopCfg);
+
         return G.start(cfg);
     }
 
     /**
+     * Creates custom Hadoop configuration.
+     *
+     * @return The Hadoop configuration.
+     */
+    protected HadoopConfiguration createHadoopConfiguration() {
+        return null;
+    }
+
+    /**
      * @return IGFS configuration.
      */
     @Override public FileSystemConfiguration igfsConfiguration() throws Exception {

http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopPlannerMockJob.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopPlannerMockJob.java b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopPlannerMockJob.java
new file mode 100644
index 0000000..88d0f80
--- /dev/null
+++ b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopPlannerMockJob.java
@@ -0,0 +1,168 @@
+/*
+ * 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.hadoop;
+
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteLogger;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.Collection;
+import java.util.UUID;
+
+/**
+ * Mock job for planner tests.
+ */
+public class HadoopPlannerMockJob implements HadoopJob {
+    /** Input splits. */
+    private final Collection<HadoopInputSplit> splits;
+
+    /** Reducers count. */
+    private final int reducers;
+
+    /**
+     * Constructor.
+     *
+     * @param splits Input splits.
+     * @param reducers Reducers.
+     */
+    public HadoopPlannerMockJob(Collection<HadoopInputSplit> splits, int reducers) {
+        this.splits = splits;
+        this.reducers = reducers;
+    }
+
+    /** {@inheritDoc} */
+    @Override public Collection<HadoopInputSplit> input() throws IgniteCheckedException {
+        return splits;
+    }
+
+    /** {@inheritDoc} */
+    @Override public HadoopJobInfo info() {
+        return new JobInfo(reducers);
+    }
+
+    /** {@inheritDoc} */
+    @Override public HadoopJobId id() {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public HadoopTaskContext getTaskContext(HadoopTaskInfo info) throws IgniteCheckedException {
+        throwUnsupported();
+
+        return null;
+    }
+
+    /** {@inheritDoc} */
+    @Override public void initialize(boolean external, UUID nodeId) throws IgniteCheckedException {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void dispose(boolean external) throws IgniteCheckedException {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void prepareTaskEnvironment(HadoopTaskInfo info) throws IgniteCheckedException {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void cleanupTaskEnvironment(HadoopTaskInfo info) throws IgniteCheckedException {
+        throwUnsupported();
+    }
+
+    /** {@inheritDoc} */
+    @Override public void cleanupStagingDirectory() {
+        throwUnsupported();
+    }
+
+    /**
+     * Throw {@link UnsupportedOperationException}.
+     */
+    private static void throwUnsupported() {
+        throw new UnsupportedOperationException("Should not be called!");
+    }
+
+    /**
+     * Mocked job info.
+     */
+    private static class JobInfo implements HadoopJobInfo {
+        /** Reducers. */
+        private final int reducers;
+
+        /**
+         * Constructor.
+         *
+         * @param reducers Reducers.
+         */
+        public JobInfo(int reducers) {
+            this.reducers = reducers;
+        }
+
+        /** {@inheritDoc} */
+        @Override public int reducers() {
+            return reducers;
+        }
+
+        /** {@inheritDoc} */
+        @Nullable @Override public String property(String name) {
+            throwUnsupported();
+
+            return null;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean hasCombiner() {
+            throwUnsupported();
+
+            return false;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean hasReducer() {
+            throwUnsupported();
+
+            return false;
+        }
+
+        /** {@inheritDoc} */
+        @Override public HadoopJob createJob(Class<? extends HadoopJob> jobCls, HadoopJobId jobId, IgniteLogger log,
+            @Nullable String[] libNames) throws IgniteCheckedException {
+            throwUnsupported();
+
+            return null;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String jobName() {
+            throwUnsupported();
+
+            return null;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String user() {
+            throwUnsupported();
+
+            return null;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopWeightedMapReducePlannerTest.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopWeightedMapReducePlannerTest.java b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopWeightedMapReducePlannerTest.java
new file mode 100644
index 0000000..4e7cc50
--- /dev/null
+++ b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopWeightedMapReducePlannerTest.java
@@ -0,0 +1,599 @@
+/*
+ * 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.hadoop;
+
+import org.apache.ignite.cluster.ClusterMetrics;
+import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.hadoop.mapreduce.IgniteHadoopWeightedMapReducePlanner;
+import org.apache.ignite.igfs.IgfsBlockLocation;
+import org.apache.ignite.igfs.IgfsPath;
+import org.apache.ignite.internal.IgniteNodeAttributes;
+import org.apache.ignite.internal.processors.hadoop.planner.HadoopAbstractMapReducePlanner;
+import org.apache.ignite.internal.processors.igfs.IgfsIgniteMock;
+import org.apache.ignite.internal.processors.igfs.IgfsMock;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.lang.IgniteProductVersion;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.jetbrains.annotations.Nullable;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.UUID;
+
+/**
+ * Tests for weighted map-reduce planned.
+ */
+public class HadoopWeightedMapReducePlannerTest extends GridCommonAbstractTest {
+    /** ID 1. */
+    private static final UUID ID_1 = new UUID(0, 1);
+
+    /** ID 2. */
+    private static final UUID ID_2 = new UUID(0, 2);
+
+    /** ID 3. */
+    private static final UUID ID_3 = new UUID(0, 3);
+
+    /** MAC 1. */
+    private static final String MAC_1 = "mac1";
+
+    /** MAC 2. */
+    private static final String MAC_2 = "mac2";
+
+    /** MAC 3. */
+    private static final String MAC_3 = "mac3";
+
+    /** Host 1. */
+    private static final String HOST_1 = "host1";
+
+    /** Host 2. */
+    private static final String HOST_2 = "host2";
+
+    /** Host 3. */
+    private static final String HOST_3 = "host3";
+
+    /** Host 4. */
+    private static final String HOST_4 = "host4";
+
+    /** Host 5. */
+    private static final String HOST_5 = "host5";
+
+    /** Standard node 1. */
+    private static final MockNode NODE_1 = new MockNode(ID_1, MAC_1, HOST_1);
+
+    /** Standard node 2. */
+    private static final MockNode NODE_2 = new MockNode(ID_2, MAC_2, HOST_2);
+
+    /** Standard node 3. */
+    private static final MockNode NODE_3 = new MockNode(ID_3, MAC_3, HOST_3);
+
+    /** Standard nodes. */
+    private static final Collection<ClusterNode> NODES;
+
+    /**
+     * Static initializer.
+     */
+    static {
+        NODES = new ArrayList<>();
+
+        NODES.add(NODE_1);
+        NODES.add(NODE_2);
+        NODES.add(NODE_3);
+    }
+
+    /**
+     * Test one IGFS split being assigned to affinity node.
+     *
+     * @throws Exception If failed.
+     */
+    public void testOneIgfsSplitAffinity() throws Exception {
+        IgfsMock igfs = LocationsBuilder.create().add(0, NODE_1).add(50, NODE_2).add(100, NODE_3).buildIgfs();
+
+        List<HadoopInputSplit> splits = new ArrayList<>();
+
+        splits.add(new HadoopFileBlock(new String[] { HOST_1 }, URI.create("igfs://igfs@/file"), 0, 50));
+
+        final int expReducers = 4;
+
+        HadoopPlannerMockJob job = new HadoopPlannerMockJob(splits, expReducers);
+
+        IgniteHadoopWeightedMapReducePlanner planner = createPlanner(igfs);
+
+        HadoopMapReducePlan plan = planner.preparePlan(job, NODES, null);
+
+        assert plan.mappers() == 1;
+        assert plan.mapperNodeIds().size() == 1;
+        assert plan.mapperNodeIds().contains(ID_1);
+
+        checkPlanMappers(plan, splits, NODES, false/*only 1 split*/);
+        checkPlanReducers(plan, NODES, expReducers, false/* because of threshold behavior.*/);
+    }
+
+    /**
+     * Test one HDFS splits.
+     *
+     * @throws Exception If failed.
+     */
+    public void testHdfsSplitsAffinity() throws Exception {
+        IgfsMock igfs = LocationsBuilder.create().add(0, NODE_1).add(50, NODE_2).add(100, NODE_3).buildIgfs();
+
+        final List<HadoopInputSplit> splits = new ArrayList<>();
+
+        splits.add(new HadoopFileBlock(new String[] { HOST_1 }, URI.create("hfds://" + HOST_1 + "/x"), 0, 50));
+        splits.add(new HadoopFileBlock(new String[] { HOST_2 }, URI.create("hfds://" + HOST_2 + "/x"), 50, 100));
+        splits.add(new HadoopFileBlock(new String[] { HOST_3 }, URI.create("hfds://" + HOST_3 + "/x"), 100, 37));
+
+        // The following splits belong to hosts that are out of Ignite topology at all.
+        // This means that these splits should be assigned to any least loaded modes:
+        splits.add(new HadoopFileBlock(new String[] { HOST_4 }, URI.create("hfds://" + HOST_4 + "/x"), 138, 2));
+        splits.add(new HadoopFileBlock(new String[] { HOST_5 }, URI.create("hfds://" + HOST_5 + "/x"), 140, 3));
+
+        final int expReducers = 7;
+
+        HadoopPlannerMockJob job = new HadoopPlannerMockJob(splits, expReducers);
+
+        IgniteHadoopWeightedMapReducePlanner planner = createPlanner(igfs);
+
+        final HadoopMapReducePlan plan = planner.preparePlan(job, NODES, null);
+
+        checkPlanMappers(plan, splits, NODES, true);
+
+        checkPlanReducers(plan, NODES, expReducers, true);
+    }
+
+    /**
+     * Test HDFS splits with Replication == 3.
+     *
+     * @throws Exception If failed.
+     */
+    public void testHdfsSplitsReplication() throws Exception {
+        IgfsMock igfs = LocationsBuilder.create().add(0, NODE_1).add(50, NODE_2).add(100, NODE_3).buildIgfs();
+
+        final List<HadoopInputSplit> splits = new ArrayList<>();
+
+        splits.add(new HadoopFileBlock(new String[] { HOST_1, HOST_2, HOST_3 }, URI.create("hfds://" + HOST_1 + "/x"), 0, 50));
+        splits.add(new HadoopFileBlock(new String[] { HOST_2, HOST_3, HOST_4 }, URI.create("hfds://" + HOST_2 + "/x"), 50, 100));
+        splits.add(new HadoopFileBlock(new String[] { HOST_3, HOST_4, HOST_5 }, URI.create("hfds://" + HOST_3 + "/x"), 100, 37));
+        // The following splits belong to hosts that are out of Ignite topology at all.
+        // This means that these splits should be assigned to any least loaded modes:
+        splits.add(new HadoopFileBlock(new String[] { HOST_4, HOST_5, HOST_1 }, URI.create("hfds://" + HOST_4 + "/x"), 138, 2));
+        splits.add(new HadoopFileBlock(new String[] { HOST_5, HOST_1, HOST_2 }, URI.create("hfds://" + HOST_5 + "/x"), 140, 3));
+
+        final int expReducers = 8;
+
+        HadoopPlannerMockJob job = new HadoopPlannerMockJob(splits, expReducers);
+
+        IgniteHadoopWeightedMapReducePlanner planner = createPlanner(igfs);
+
+        final HadoopMapReducePlan plan = planner.preparePlan(job, NODES, null);
+
+        checkPlanMappers(plan, splits, NODES, true);
+
+        checkPlanReducers(plan, NODES, expReducers, true);
+    }
+
+    /**
+     * Get all IDs.
+     *
+     * @param nodes Nodes.
+     * @return IDs.
+     */
+    private static Set<UUID> allIds(Collection<ClusterNode> nodes) {
+        Set<UUID> allIds = new HashSet<>();
+
+        for (ClusterNode n : nodes)
+            allIds.add(n.id());
+
+        return allIds;
+    }
+
+    /**
+     * Check mappers for the plan.
+     *
+     * @param plan Plan.
+     * @param splits Splits.
+     * @param nodes Nodes.
+     * @param expectUniformity WHether uniformity is expected.
+     */
+    private static void checkPlanMappers(HadoopMapReducePlan plan, List<HadoopInputSplit> splits,
+        Collection<ClusterNode> nodes, boolean expectUniformity) {
+        // Number of mappers should correspomd to the number of input splits:
+        assertEquals(splits.size(), plan.mappers());
+
+        if (expectUniformity) {
+            // mappers are assigned to all available nodes:
+            assertEquals(nodes.size(), plan.mapperNodeIds().size());
+
+
+            assertEquals(allIds(nodes), plan.mapperNodeIds());
+        }
+
+        // Check all splits are covered by mappers:
+        Set<HadoopInputSplit> set = new HashSet<>();
+
+        for (UUID id: plan.mapperNodeIds()) {
+            Collection<HadoopInputSplit> sp = plan.mappers(id);
+
+            assert sp != null;
+
+            for (HadoopInputSplit s: sp)
+                assertTrue(set.add(s));
+        }
+
+        // must be of the same size & contain same elements:
+        assertEquals(set, new HashSet<>(splits));
+    }
+
+    /**
+     * Check plan reducers.
+     *
+     * @param plan Plan.
+     * @param nodes Nodes.
+     * @param expReducers Expected reducers.
+     * @param expectUniformity Expected uniformity.
+     */
+    private static void checkPlanReducers(HadoopMapReducePlan plan,
+        Collection<ClusterNode> nodes, int expReducers, boolean expectUniformity) {
+
+        assertEquals(expReducers, plan.reducers());
+
+        if (expectUniformity)
+            assertEquals(allIds(nodes), plan.reducerNodeIds());
+
+        int sum = 0;
+        int lenSum = 0;
+
+        for (UUID uuid: plan.reducerNodeIds()) {
+            int[] rr = plan.reducers(uuid);
+
+            assert rr != null;
+
+            lenSum += rr.length;
+
+            for (int i: rr)
+                sum += i;
+        }
+
+        assertEquals(expReducers, lenSum);
+
+        // Numbers in the arrays must be consequtive integers stating from 0,
+        // check that simply calculating their total sum:
+        assertEquals((lenSum * (lenSum - 1) / 2), sum);
+    }
+
+    /**
+     * Create planner for IGFS.
+     *
+     * @param igfs IGFS.
+     * @return Planner.
+     */
+    private static IgniteHadoopWeightedMapReducePlanner createPlanner(IgfsMock igfs) {
+        IgniteHadoopWeightedMapReducePlanner planner = new IgniteHadoopWeightedMapReducePlanner();
+
+        IgfsIgniteMock ignite = new IgfsIgniteMock(null, igfs);
+
+        GridTestUtils.setFieldValue(planner, HadoopAbstractMapReducePlanner.class, "ignite", ignite);
+
+        return planner;
+    }
+
+    /**
+     * Throw {@link UnsupportedOperationException}.
+     */
+    private static void throwUnsupported() {
+        throw new UnsupportedOperationException("Should not be called!");
+    }
+
+    /**
+     * Mocked node.
+     */
+    private static class MockNode implements ClusterNode {
+        /** ID. */
+        private final UUID id;
+
+        /** MAC addresses. */
+        private final String macs;
+
+        /** Addresses. */
+        private final List<String> addrs;
+
+        /**
+         * Constructor.
+         *
+         * @param id Node ID.
+         * @param macs MAC addresses.
+         * @param addrs Addresses.
+         */
+        public MockNode(UUID id, String macs, String... addrs) {
+            assert addrs != null;
+
+            this.id = id;
+            this.macs = macs;
+
+            this.addrs = Arrays.asList(addrs);
+        }
+
+        /** {@inheritDoc} */
+        @Override public UUID id() {
+            return id;
+        }
+
+        /** {@inheritDoc} */
+        @SuppressWarnings("unchecked")
+        @Nullable @Override public <T> T attribute(String name) {
+            if (F.eq(name, IgniteNodeAttributes.ATTR_MACS))
+                return (T)macs;
+
+            throwUnsupported();
+
+            return null;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Collection<String> addresses() {
+            return addrs;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Object consistentId() {
+            throwUnsupported();
+
+            return null;
+        }
+
+        /** {@inheritDoc} */
+        @Override public ClusterMetrics metrics() {
+            throwUnsupported();
+
+            return null;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Map<String, Object> attributes() {
+            throwUnsupported();
+
+            return null;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Collection<String> hostNames() {
+            throwUnsupported();
+
+            return null;
+        }
+
+        /** {@inheritDoc} */
+        @Override public long order() {
+            throwUnsupported();
+
+            return 0;
+        }
+
+        /** {@inheritDoc} */
+        @Override public IgniteProductVersion version() {
+            throwUnsupported();
+
+            return null;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean isLocal() {
+            throwUnsupported();
+
+            return false;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean isDaemon() {
+            throwUnsupported();
+
+            return false;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean isClient() {
+            throwUnsupported();
+
+            return false;
+        }
+    }
+
+    /**
+     * Locations builder.
+     */
+    private static class LocationsBuilder {
+        /** Locations. */
+        private final TreeMap<Long, Collection<MockNode>> locs = new TreeMap<>();
+
+        /**
+         * Create new locations builder.
+         *
+         * @return Locations builder.
+         */
+        public static LocationsBuilder create() {
+            return new LocationsBuilder();
+        }
+
+        /**
+         * Add locations.
+         *
+         * @param start Start.
+         * @param nodes Nodes.
+         * @return This builder for chaining.
+         */
+        public LocationsBuilder add(long start, MockNode... nodes) {
+            locs.put(start, Arrays.asList(nodes));
+
+            return this;
+        }
+
+        /**
+         * Build locations.
+         *
+         * @return Locations.
+         */
+        public TreeMap<Long, Collection<MockNode>> build() {
+            return locs;
+        }
+
+        /**
+         * Build IGFS.
+         *
+         * @return IGFS.
+         */
+        public MockIgfs buildIgfs() {
+            return new MockIgfs(build());
+        }
+    }
+
+    /**
+     * Mocked IGFS.
+     */
+    private static class MockIgfs extends IgfsMock {
+        /** Block locations. */
+        private final TreeMap<Long, Collection<MockNode>> locs;
+
+        /**
+         * Constructor.
+         *
+         * @param locs Block locations.
+         */
+        public MockIgfs(TreeMap<Long, Collection<MockNode>> locs) {
+            super("igfs");
+
+            this.locs = locs;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Collection<IgfsBlockLocation> affinity(IgfsPath path, long start, long len) {
+            Collection<IgfsBlockLocation> res = new ArrayList<>();
+
+            long cur = start;
+            long remaining = len;
+
+            long prevLocStart = -1;
+            Collection<MockNode> prevLocNodes = null;
+
+            for (Map.Entry<Long, Collection<MockNode>> locEntry : locs.entrySet()) {
+                long locStart = locEntry.getKey();
+                Collection<MockNode> locNodes = locEntry.getValue();
+
+                if (prevLocNodes != null) {
+                    if (cur < locStart) {
+                        // Add part from previous block.
+                        long prevLen = locStart - prevLocStart;
+
+                        res.add(new IgfsBlockLocationMock(cur, prevLen, prevLocNodes));
+
+                        cur = locStart;
+                        remaining -= prevLen;
+                    }
+                }
+
+                prevLocStart = locStart;
+                prevLocNodes = locNodes;
+
+                if (remaining == 0)
+                    break;
+            }
+
+            // Add remainder.
+            if (remaining != 0)
+                res.add(new IgfsBlockLocationMock(cur, remaining, prevLocNodes));
+
+            return res;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean exists(IgfsPath path) {
+            return true;
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean isProxy(URI path) {
+            return false;
+        }
+    }
+
+    /**
+     * Mocked block location.
+     */
+    private static class IgfsBlockLocationMock implements IgfsBlockLocation {
+        /** Start. */
+        private final long start;
+
+        /** Length. */
+        private final long len;
+
+        /** Node IDs. */
+        private final List<UUID> nodeIds;
+
+        /**
+         * Constructor.
+         *
+         * @param start Start.
+         * @param len Length.
+         * @param nodes Nodes.
+         */
+        public IgfsBlockLocationMock(long start, long len, Collection<MockNode> nodes) {
+            this.start = start;
+            this.len = len;
+
+            this.nodeIds = new ArrayList<>(nodes.size());
+
+            for (MockNode node : nodes)
+                nodeIds.add(node.id);
+        }
+
+        /** {@inheritDoc} */
+        @Override public long start() {
+            return start;
+        }
+
+        /** {@inheritDoc} */
+        @Override public long length() {
+            return len;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Collection<UUID> nodeIds() {
+            return nodeIds;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Collection<String> names() {
+            throwUnsupported();
+
+            return null;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Collection<String> hosts() {
+            throwUnsupported();
+
+            return null;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopWeightedPlannerMapReduceTest.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopWeightedPlannerMapReduceTest.java b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopWeightedPlannerMapReduceTest.java
new file mode 100644
index 0000000..e0403c2
--- /dev/null
+++ b/modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/HadoopWeightedPlannerMapReduceTest.java
@@ -0,0 +1,38 @@
+/*
+ * 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.hadoop;
+
+import org.apache.ignite.configuration.HadoopConfiguration;
+import org.apache.ignite.hadoop.mapreduce.IgniteHadoopWeightedMapReducePlanner;
+
+/**
+ * Tests whole map-red execution Weighted planner.
+ */
+public class HadoopWeightedPlannerMapReduceTest extends HadoopMapReduceTest {
+    /** {@inheritDoc} */
+    @Override protected HadoopConfiguration createHadoopConfiguration() {
+        HadoopConfiguration hadoopCfg = new HadoopConfiguration();
+
+        // Use weighted planner with default settings:
+        IgniteHadoopWeightedMapReducePlanner planner = new IgniteHadoopWeightedMapReducePlanner();
+
+        hadoopCfg.setMapReducePlanner(planner);
+
+        return hadoopCfg;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/73649386/modules/hadoop/src/test/java/org/apache/ignite/testsuites/IgniteHadoopTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/test/java/org/apache/ignite/testsuites/IgniteHadoopTestSuite.java b/modules/hadoop/src/test/java/org/apache/ignite/testsuites/IgniteHadoopTestSuite.java
index e0d1142..52104a8 100644
--- a/modules/hadoop/src/test/java/org/apache/ignite/testsuites/IgniteHadoopTestSuite.java
+++ b/modules/hadoop/src/test/java/org/apache/ignite/testsuites/IgniteHadoopTestSuite.java
@@ -28,7 +28,6 @@ import org.apache.ignite.hadoop.cache.HadoopTxConfigCacheTest;
 import org.apache.ignite.hadoop.fs.KerberosHadoopFileSystemFactorySelfTest;
 import org.apache.ignite.hadoop.util.BasicUserNameMapperSelfTest;
 import org.apache.ignite.hadoop.util.ChainedUserNameMapperSelfTest;
-import org.apache.ignite.hadoop.util.KerberosUserNameMapper;
 import org.apache.ignite.hadoop.util.KerberosUserNameMapperSelfTest;
 import org.apache.ignite.igfs.Hadoop1OverIgfsDualAsyncTest;
 import org.apache.ignite.igfs.Hadoop1OverIgfsDualSyncTest;
@@ -70,6 +69,8 @@ import org.apache.ignite.internal.processors.hadoop.HadoopTasksV1Test;
 import org.apache.ignite.internal.processors.hadoop.HadoopTasksV2Test;
 import org.apache.ignite.internal.processors.hadoop.HadoopV2JobSelfTest;
 import org.apache.ignite.internal.processors.hadoop.HadoopValidationSelfTest;
+import org.apache.ignite.internal.processors.hadoop.HadoopWeightedMapReducePlannerTest;
+import org.apache.ignite.internal.processors.hadoop.HadoopWeightedPlannerMapReduceTest;
 import org.apache.ignite.internal.processors.hadoop.shuffle.collections.HadoopConcurrentHashMultimapSelftest;
 import org.apache.ignite.internal.processors.hadoop.shuffle.collections.HadoopHashMapSelfTest;
 import org.apache.ignite.internal.processors.hadoop.shuffle.collections.HadoopSkipListSelfTest;
@@ -108,6 +109,9 @@ public class IgniteHadoopTestSuite extends TestSuite {
 
         TestSuite suite = new TestSuite("Ignite Hadoop MR Test Suite");
 
+        suite.addTest(new TestSuite(ldr.loadClass(HadoopDefaultMapReducePlannerSelfTest.class.getName())));
+        suite.addTest(new TestSuite(ldr.loadClass(HadoopWeightedMapReducePlannerTest.class.getName())));
+
         suite.addTest(new TestSuite(ldr.loadClass(BasicUserNameMapperSelfTest.class.getName())));
         suite.addTest(new TestSuite(ldr.loadClass(KerberosUserNameMapperSelfTest.class.getName())));
         suite.addTest(new TestSuite(ldr.loadClass(ChainedUserNameMapperSelfTest.class.getName())));
@@ -154,7 +158,6 @@ public class IgniteHadoopTestSuite extends TestSuite {
 
         suite.addTest(new TestSuite(ldr.loadClass(HadoopValidationSelfTest.class.getName())));
 
-        suite.addTest(new TestSuite(ldr.loadClass(HadoopDefaultMapReducePlannerSelfTest.class.getName())));
         suite.addTest(new TestSuite(ldr.loadClass(HadoopJobTrackerSelfTest.class.getName())));
 
         suite.addTest(new TestSuite(ldr.loadClass(HadoopHashMapSelfTest.class.getName())));
@@ -174,6 +177,7 @@ public class IgniteHadoopTestSuite extends TestSuite {
         suite.addTest(new TestSuite(ldr.loadClass(HadoopTasksV2Test.class.getName())));
 
         suite.addTest(new TestSuite(ldr.loadClass(HadoopMapReduceTest.class.getName())));
+        suite.addTest(new TestSuite(ldr.loadClass(HadoopWeightedPlannerMapReduceTest.class.getName())));
 
         suite.addTest(new TestSuite(ldr.loadClass(HadoopMapReduceEmbeddedSelfTest.class.getName())));
 


[46/50] [abbrv] ignite git commit: IGNITE-2649: Ensured correct local Ignite instance processing during serialization and deserialization.

Posted by vo...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskProcessor.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskProcessor.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskProcessor.java
index 0c3cf0e..9633a65 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskProcessor.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskProcessor.java
@@ -71,6 +71,7 @@ import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteFuture;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.security.SecurityPermission;
 import org.jetbrains.annotations.Nullable;
 import org.jsr166.LongAdder8;
@@ -913,7 +914,7 @@ public class GridTaskProcessor extends GridProcessorAdapter {
                     GridTaskSessionRequest req = new GridTaskSessionRequest(
                         ses.getId(),
                         null,
-                        loc ? null : marsh.marshal(attrs),
+                        loc ? null : MarshallerUtils.marshal(ctx, attrs),
                         attrs);
 
                     // Make sure to go through IO manager always, since order
@@ -1029,7 +1030,7 @@ public class GridTaskProcessor extends GridProcessorAdapter {
             boolean loc = ctx.localNodeId().equals(nodeId) && !ctx.config().isMarshalLocalJobs();
 
             Map<?, ?> attrs = loc ? msg.getAttributes() :
-                marsh.<Map<?, ?>>unmarshal(msg.getAttributesBytes(),
+                MarshallerUtils.<Map<?, ?>>unmarshal(ctx.gridName(), marsh, msg.getAttributesBytes(),
                     U.resolveClassLoader(task.getTask().getClass().getClassLoader(), ctx.config()));
 
             GridTaskSessionImpl ses = task.getSession();
@@ -1305,7 +1306,8 @@ public class GridTaskProcessor extends GridProcessorAdapter {
                     if (topic == null) {
                         assert req.topicBytes() != null;
 
-                        topic = marsh.unmarshal(req.topicBytes(), U.resolveClassLoader(ctx.config()));
+                        topic = MarshallerUtils.unmarshal(ctx.gridName(), marsh, req.topicBytes(),
+                            U.resolveClassLoader(ctx.config()));
                     }
 
                     boolean loc = ctx.localNodeId().equals(nodeId);
@@ -1313,7 +1315,7 @@ public class GridTaskProcessor extends GridProcessorAdapter {
                     ctx.io().send(nodeId, topic,
                         new GridJobSiblingsResponse(
                             loc ? siblings : null,
-                            loc ? null : marsh.marshal(siblings)),
+                            loc ? null : MarshallerUtils.marshal(ctx, siblings)),
                         SYSTEM_POOL);
                 }
                 catch (IgniteCheckedException e) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java
index 8ce005a..10942da 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/task/GridTaskWorker.java
@@ -81,6 +81,7 @@ import org.apache.ignite.internal.visor.util.VisorClusterGroupEmptyException;
 import org.apache.ignite.lang.IgniteInClosure;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.resources.TaskContinuousMapperResource;
 import org.jetbrains.annotations.Nullable;
 import org.jsr166.ConcurrentLinkedDeque8;
@@ -774,15 +775,15 @@ class GridTaskWorker<T, R> extends GridWorker implements GridTimeoutObject {
                     try {
                         boolean loc = ctx.localNodeId().equals(res.getNodeId()) && !ctx.config().isMarshalLocalJobs();
 
-                        Object res0 = loc ? res.getJobResult() : marsh.unmarshal(res.getJobResultBytes(),
-                            U.resolveClassLoader(clsLdr, ctx.config()));
+                        Object res0 = loc ? res.getJobResult() : MarshallerUtils.unmarshal(ctx.gridName(), marsh,
+                            res.getJobResultBytes(), U.resolveClassLoader(clsLdr, ctx.config()));
 
                         IgniteException ex = loc ? res.getException() :
-                            marsh.<IgniteException>unmarshal(res.getExceptionBytes(),
+                            MarshallerUtils.<IgniteException>unmarshal(ctx.gridName(), marsh, res.getExceptionBytes(),
                                 U.resolveClassLoader(clsLdr, ctx.config()));
 
                         Map<Object, Object> attrs = loc ? res.getJobAttributes() :
-                            marsh.<Map<Object, Object>>unmarshal(res.getJobAttributesBytes(),
+                            MarshallerUtils.<Map<Object, Object>>unmarshal(ctx.gridName(), marsh, res.getJobAttributesBytes(),
                                 U.resolveClassLoader(clsLdr, ctx.config()));
 
                         jobRes.onResponse(res0, ex, attrs, res.isCancelled());
@@ -1253,16 +1254,16 @@ class GridTaskWorker<T, R> extends GridWorker implements GridTimeoutObject {
                         ses.getTaskName(),
                         ses.getUserVersion(),
                         ses.getTaskClassName(),
-                        loc ? null : marsh.marshal(res.getJob()),
+                        loc ? null : MarshallerUtils.marshal(ctx, res.getJob()),
                         loc ? res.getJob() : null,
                         ses.getStartTime(),
                         timeout,
                         ses.getTopology(),
-                        loc ? null : marsh.marshal(ses.getJobSiblings()),
+                        loc ? null : MarshallerUtils.marshal(ctx, ses.getJobSiblings()),
                         loc ? ses.getJobSiblings() : null,
-                        loc ? null : marsh.marshal(sesAttrs),
+                        loc ? null : MarshallerUtils.marshal(ctx, sesAttrs),
                         loc ? sesAttrs : null,
-                        loc ? null : marsh.marshal(jobAttrs),
+                        loc ? null : MarshallerUtils.marshal(ctx, jobAttrs),
                         loc ? jobAttrs : null,
                         ses.getCheckpointSpi(),
                         dep.classLoaderId(),

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java b/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
index 08c9219..b6f2081 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java
@@ -250,7 +250,7 @@ import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_MACS;
 /**
  * Collection of utility methods used throughout the system.
  */
-@SuppressWarnings({"UnusedReturnValue", "UnnecessaryFullyQualifiedName"})
+@SuppressWarnings({"UnusedReturnValue", "UnnecessaryFullyQualifiedName", "RedundantStringConstructorCall"})
 public abstract class IgniteUtils {
     /** Unsafe. */
     private static final Unsafe UNSAFE = GridUnsafe.unsafe();
@@ -489,6 +489,16 @@ public abstract class IgniteUtils {
     /** Object.toString() */
     private static Method toStringMtd;
 
+    /** Empty local Ignite name. */
+    private static final String LOC_IGNITE_NAME_EMPTY = new String();
+
+    /** Local Ignite name thread local. */
+    private static final ThreadLocal<String> LOC_IGNITE_NAME = new ThreadLocal<String>() {
+        @Override protected String initialValue() {
+            return LOC_IGNITE_NAME_EMPTY;
+        }
+    };
+
     /**
      * Initializes enterprise check.
      */
@@ -9555,4 +9565,47 @@ public abstract class IgniteUtils {
     public static boolean isToStringMethod(Method mtd) {
         return toStringMtd.equals(mtd);
     }
+
+    /**
+     * Get current Ignite name.
+     *
+     * @return Current Ignite name.
+     */
+    @Nullable public static String getCurrentIgniteName() {
+        return LOC_IGNITE_NAME.get();
+    }
+
+    /**
+     * Check if current Ignite name is set.
+     *
+     * @param name Name to check.
+     * @return {@code True} if set.
+     */
+    @SuppressWarnings("StringEquality")
+    public static boolean isCurrentIgniteNameSet(@Nullable String name) {
+        return name != LOC_IGNITE_NAME_EMPTY;
+    }
+
+    /**
+     * Set current Ignite name.
+     *
+     * @param newName New name.
+     * @return Old name.
+     */
+    @Nullable public static String setCurrentIgniteName(@Nullable String newName) {
+        String oldName = LOC_IGNITE_NAME.get();
+
+        LOC_IGNITE_NAME.set(newName);
+
+        return oldName;
+    }
+
+    /**
+     * Restore current Ignite name.
+     *
+     * @param oldName Old name.
+     */
+    public static void restoreCurrentIgniteName(@Nullable String oldName) {
+        LOC_IGNITE_NAME.set(oldName);
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/util/ipc/IpcToNioAdapter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/ipc/IpcToNioAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/util/ipc/IpcToNioAdapter.java
index 6820dc7..262140a 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/ipc/IpcToNioAdapter.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/ipc/IpcToNioAdapter.java
@@ -73,10 +73,12 @@ public class IpcToNioAdapter<T> {
      * @param endp Endpoint.
      * @param lsnr Listener.
      * @param writerFactory Writer factory.
+     * @param gridName Grid name.
      * @param filters Filters.
      */
     public IpcToNioAdapter(GridNioMetricsListener metricsLsnr, IgniteLogger log, IpcEndpoint endp,
-        GridNioServerListener<T> lsnr, GridNioMessageWriterFactory writerFactory, GridNioFilter... filters) {
+                           GridNioServerListener<T> lsnr, GridNioMessageWriterFactory writerFactory,
+                           String gridName, GridNioFilter... filters) {
         assert metricsLsnr != null;
 
         this.metricsLsnr = metricsLsnr;
@@ -84,7 +86,7 @@ public class IpcToNioAdapter<T> {
         this.writerFactory = writerFactory;
 
         chain = new GridNioFilterChain<>(log, lsnr, new HeadFilter(), filters);
-        ses = new GridNioSessionImpl(chain, null, null, true);
+        ses = new GridNioSessionImpl(chain, null, null, true, gridName);
 
         writeBuf = ByteBuffer.allocate(8 << 10);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioServer.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioServer.java b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioServer.java
index ac55a14..7470759 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioServer.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioServer.java
@@ -47,6 +47,7 @@ import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteException;
 import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.configuration.ConnectorConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.IgniteInternalFuture;
 import org.apache.ignite.internal.IgniteInterruptedCheckedException;
 import org.apache.ignite.internal.util.GridConcurrentHashSet;
@@ -196,6 +197,9 @@ public class GridNioServer<T> {
         }
     }
 
+    /** Grid name */
+    private String gridName;
+
     /**
      * @param addr Address.
      * @param port Port.
@@ -260,6 +264,7 @@ public class GridNioServer<T> {
         this.sockSndBuf = sockSndBuf;
         this.sndQueueLimit = sndQueueLimit;
         this.msgQueueLsnr = msgQueueLsnr;
+        this.gridName = gridName;
 
         filterChain = new GridNioFilterChain<>(log, lsnr, new HeadFilter(), filters);
 
@@ -1639,7 +1644,8 @@ public class GridNioServer<T> {
                     req.accepted(),
                     sndQueueLimit,
                     writeBuf,
-                    readBuf);
+                    readBuf,
+                    gridName);
 
                 Map<Integer, ?> meta = req.meta();
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioSession.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioSession.java b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioSession.java
index e4a7225..74ac775 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioSession.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioSession.java
@@ -18,6 +18,7 @@
 package org.apache.ignite.internal.util.nio;
 
 import java.net.InetSocketAddress;
+
 import org.jetbrains.annotations.Nullable;
 
 /**
@@ -164,4 +165,9 @@ public interface GridNioSession {
      * @return Recovery descriptor if recovery is supported, {@code null otherwise.}
      */
     @Nullable public GridNioRecoveryDescriptor recoveryDescriptor();
+
+    /**
+     * @return Grid name.
+     */
+    public String gridName();
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioSessionImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioSessionImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioSessionImpl.java
index 0bcfe64..100165e 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioSessionImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridNioSessionImpl.java
@@ -69,22 +69,28 @@ public class GridNioSessionImpl implements GridNioSession {
     /** Accepted flag. */
     private final boolean accepted;
 
+    /** Grid name. */
+    private String gridName;
+
     /**
      * @param filterChain Chain.
      * @param locAddr Local address.
      * @param rmtAddr Remote address.
+     * @param gridName Grid name.
      * @param accepted {@code True} if this session was initiated from remote host.
      */
     public GridNioSessionImpl(
         GridNioFilterChain filterChain,
         @Nullable InetSocketAddress locAddr,
         @Nullable InetSocketAddress rmtAddr,
-        boolean accepted
+        boolean accepted,
+        String gridName
     ) {
         this.filterChain = filterChain;
         this.locAddr = locAddr;
         this.rmtAddr = rmtAddr;
         this.accepted = accepted;
+        this.gridName = gridName;
 
         long now = U.currentTimeMillis();
 
@@ -309,4 +315,9 @@ public class GridNioSessionImpl implements GridNioSession {
     @Override public String toString() {
         return S.toString(GridNioSessionImpl.class, this);
     }
+
+    /** {@inheritDoc} */
+    @Override public String gridName() {
+        return gridName;
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridSelectorNioSessionImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridSelectorNioSessionImpl.java b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridSelectorNioSessionImpl.java
index 360b3d4..7b2a8f7 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridSelectorNioSessionImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridSelectorNioSessionImpl.java
@@ -77,6 +77,7 @@ class GridSelectorNioSessionImpl extends GridNioSessionImpl {
      * @param sndQueueLimit Send queue limit.
      * @param writeBuf Write buffer.
      * @param readBuf Read buffer.
+     * @param gridName Grid name.
      */
     GridSelectorNioSessionImpl(
         IgniteLogger log,
@@ -87,9 +88,10 @@ class GridSelectorNioSessionImpl extends GridNioSessionImpl {
         boolean accepted,
         int sndQueueLimit,
         @Nullable ByteBuffer writeBuf,
-        @Nullable ByteBuffer readBuf
+        @Nullable ByteBuffer readBuf,
+        String gridName
     ) {
-        super(filterChain, locAddr, rmtAddr, accepted);
+        super(filterChain, locAddr, rmtAddr, accepted, gridName);
 
         assert selectorIdx >= 0;
         assert sndQueueLimit >= 0;

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/marshaller/AbstractMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/marshaller/AbstractMarshaller.java b/modules/core/src/main/java/org/apache/ignite/marshaller/AbstractMarshaller.java
index dd5bad0..6c3428e 100644
--- a/modules/core/src/main/java/org/apache/ignite/marshaller/AbstractMarshaller.java
+++ b/modules/core/src/main/java/org/apache/ignite/marshaller/AbstractMarshaller.java
@@ -17,12 +17,9 @@
 
 package org.apache.ignite.marshaller;
 
-import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.internal.util.GridByteArrayList;
 import org.apache.ignite.internal.util.io.GridByteArrayInputStream;
 import org.apache.ignite.internal.util.io.GridByteArrayOutputStream;
-import org.apache.ignite.internal.util.typedef.internal.U;
-import org.jetbrains.annotations.Nullable;
 
 /**
  * Base class for marshallers. Provides default implementations of methods
@@ -37,7 +34,6 @@ public abstract class AbstractMarshaller implements Marshaller {
     /** Context. */
     protected MarshallerContext ctx;
 
-
     /**
      * Undeployment callback invoked when class loader is being undeployed.
      *
@@ -47,38 +43,15 @@ public abstract class AbstractMarshaller implements Marshaller {
      */
     public abstract void onUndeploy(ClassLoader ldr);
 
-    /** {@inheritDoc} */
-    @Override public void setContext(MarshallerContext ctx) {
-        this.ctx = ctx;
-    }
-
-    /** {@inheritDoc} */
-    @Override public byte[] marshal(@Nullable Object obj) throws IgniteCheckedException {
-        GridByteArrayOutputStream out = null;
-
-        try {
-            out = new GridByteArrayOutputStream(DFLT_BUFFER_SIZE);
-
-            marshal(obj, out);
-
-            return out.toByteArray();
-        }
-        finally {
-            U.close(out, null);
-        }
+    /**
+     * @return Marshaller context.
+     */
+    public MarshallerContext getContext() {
+        return ctx;
     }
 
     /** {@inheritDoc} */
-    @Override public <T> T unmarshal(byte[] arr, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
-        GridByteArrayInputStream in = null;
-
-        try {
-            in = new GridByteArrayInputStream(arr, 0, arr.length);
-
-            return unmarshal(in, clsLdr);
-        }
-        finally {
-            U.close(in, null);
-        }
+    @Override public void setContext(MarshallerContext ctx) {
+        this.ctx = ctx;
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/marshaller/MarshallerUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/marshaller/MarshallerUtils.java b/modules/core/src/main/java/org/apache/ignite/marshaller/MarshallerUtils.java
new file mode 100644
index 0000000..0775622
--- /dev/null
+++ b/modules/core/src/main/java/org/apache/ignite/marshaller/MarshallerUtils.java
@@ -0,0 +1,157 @@
+/*
+ * 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.marshaller;
+
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.internal.GridKernalContext;
+import org.apache.ignite.internal.util.IgniteUtils;
+import org.jetbrains.annotations.Nullable;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * Utility marshaller methods.
+ */
+public class MarshallerUtils {
+    /**
+     * Marshal object with provided node name.
+     *
+     * @param name Grid name.
+     * @param marsh Marshaller.
+     * @param obj Object to marshal.
+     * @return Result.
+     * @throws IgniteCheckedException If failed.
+     */
+    public static byte[] marshal(String name, Marshaller marsh, @Nullable Object obj) throws IgniteCheckedException {
+        String oldName = IgniteUtils.setCurrentIgniteName(name);
+
+        try {
+            return marsh.marshal(obj);
+        }
+        finally {
+            IgniteUtils.restoreCurrentIgniteName(oldName);
+        }
+    }
+
+    /**
+     * Marshal object to stream and set grid name thread local.
+     *
+     * @param name Grid name.
+     * @param marshaller Marshaller.
+     * @param obj Object to marshal.
+     * @param out Output stream.
+     * @throws IgniteCheckedException If fail.
+     */
+    public static void marshal(String name, Marshaller marshaller, @Nullable Object obj, OutputStream out)
+        throws IgniteCheckedException {
+        String oldName = IgniteUtils.setCurrentIgniteName(name);
+
+        try {
+            marshaller.marshal(obj, out);
+        }
+        finally {
+            IgniteUtils.restoreCurrentIgniteName(oldName);
+        }
+    }
+
+    /**
+     * Marshal object with node name taken from provided kernal context.
+     *
+     * @param ctx Kernal context.
+     * @param obj Object to marshal.
+     * @return Result.
+     * @throws IgniteCheckedException If failed.
+     */
+    public static byte[] marshal(GridKernalContext ctx, @Nullable Object obj) throws IgniteCheckedException {
+        return marshal(ctx.gridName(), ctx.config().getMarshaller(), obj);
+    }
+
+    /**
+     * Unmarshal object and set grid name thread local.
+     *
+     * @param name Grid name.
+     * @param marsh Marshaller.
+     * @param arr Binary data.
+     * @param ldr Class loader.
+     * @return Deserialized object.
+     * @throws IgniteCheckedException If failed.
+     */
+    public static <T> T unmarshal(String name, Marshaller marsh, byte[] arr, @Nullable ClassLoader ldr)
+        throws IgniteCheckedException {
+        String oldName = IgniteUtils.setCurrentIgniteName(name);
+
+        try {
+            return marsh.unmarshal(arr, ldr);
+        }
+        finally {
+            IgniteUtils.restoreCurrentIgniteName(oldName);
+        }
+    }
+
+    /**
+     * Unmarshal object from stream and set grid name thread local.
+     *
+     * @param name Grid name.
+     * @param marsh Marshaller.
+     * @param in Input stream.
+     * @param ldr Class loader.
+     * @return Deserialized object.
+     * @throws IgniteCheckedException If failed.
+     */
+    public static <T> T unmarshal(String name, Marshaller marsh, InputStream in, @Nullable ClassLoader ldr)
+        throws IgniteCheckedException {
+        String oldName = IgniteUtils.setCurrentIgniteName(name);
+
+        try {
+            return marsh.unmarshal(in, ldr);
+        }
+        finally {
+            IgniteUtils.restoreCurrentIgniteName(oldName);
+        }
+    }
+
+    /**
+     * Marshal and unmarshal object.
+     *
+     * @param name Grid name.
+     * @param marsh Marshaller.
+     * @param obj Object to clone.
+     * @param clsLdr Class loader.
+     * @return Deserialized value.
+     * @throws IgniteCheckedException If failed.
+     */
+    public static <T> T marshalUnmarshal(String name, Marshaller marsh, T obj, @Nullable ClassLoader clsLdr)
+        throws IgniteCheckedException {
+        String oldName = IgniteUtils.setCurrentIgniteName(name);
+
+        try {
+            return marsh.unmarshal(marsh.marshal(obj), clsLdr);
+        }
+        finally {
+            IgniteUtils.restoreCurrentIgniteName(oldName);
+        }
+    }
+
+    /**
+     * Private constructor.
+     */
+    private MarshallerUtils() {
+        // No-op.
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java b/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java
index deb3953..c8bb383 100644
--- a/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java
+++ b/modules/core/src/main/java/org/apache/ignite/marshaller/jdk/JdkMarshaller.java
@@ -23,6 +23,8 @@ import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.io.OutputStream;
 import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.internal.util.io.GridByteArrayInputStream;
+import org.apache.ignite.internal.util.io.GridByteArrayOutputStream;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.AbstractMarshaller;
@@ -87,6 +89,22 @@ public class JdkMarshaller extends AbstractMarshaller {
     }
 
     /** {@inheritDoc} */
+    @Override public byte[] marshal(@Nullable Object obj) throws IgniteCheckedException {
+        GridByteArrayOutputStream out = null;
+
+        try {
+            out = new GridByteArrayOutputStream(DFLT_BUFFER_SIZE);
+
+            marshal(obj, out);
+
+            return out.toByteArray();
+        }
+        finally {
+            U.close(out, null);
+        }
+    }
+
+    /** {@inheritDoc} */
     @SuppressWarnings({"unchecked"})
     @Override public <T> T unmarshal(InputStream in, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
         assert in != null;
@@ -115,6 +133,20 @@ public class JdkMarshaller extends AbstractMarshaller {
     }
 
     /** {@inheritDoc} */
+    @Override public <T> T unmarshal(byte[] arr, @Nullable ClassLoader clsLdr) throws IgniteCheckedException {
+        GridByteArrayInputStream in = null;
+
+        try {
+            in = new GridByteArrayInputStream(arr, 0, arr.length);
+
+            return unmarshal(in, clsLdr);
+        }
+        finally {
+            U.close(in, null);
+        }
+    }
+
+    /** {@inheritDoc} */
     @Override public void onUndeploy(ClassLoader ldr) {
         // No-op.
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsCheckpointSpi.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsCheckpointSpi.java b/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsCheckpointSpi.java
index 36a4ea6..7a12582 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsCheckpointSpi.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsCheckpointSpi.java
@@ -323,7 +323,7 @@ public class SharedFsCheckpointSpi extends IgniteSpiAdapter implements Checkpoin
                         log.debug("Checking checkpoint file: " + file.getAbsolutePath());
 
                     try {
-                        SharedFsCheckpointData data = SharedFsUtils.read(file, marsh, log);
+                        SharedFsCheckpointData data = SharedFsUtils.read(file, marsh, log, ignite.configuration());
 
                         if (data.getHost().equals(host)) {
                             files.put(file, new SharedFsTimeData(data.getExpireTime(), file.lastModified(),
@@ -386,7 +386,7 @@ public class SharedFsCheckpointSpi extends IgniteSpiAdapter implements Checkpoin
 
         if (file.exists())
             try {
-                SharedFsCheckpointData data = SharedFsUtils.read(file, marsh, log);
+                SharedFsCheckpointData data = SharedFsUtils.read(file, marsh, log, ignite.configuration());
 
                 return data != null ?
                     data.getExpireTime() == 0 || data.getExpireTime() > U.currentTimeMillis() ?
@@ -434,7 +434,7 @@ public class SharedFsCheckpointSpi extends IgniteSpiAdapter implements Checkpoin
 
             try {
                 SharedFsUtils.write(file, new SharedFsCheckpointData(state, expireTime, host, key),
-                    marsh, log);
+                    marsh, log, ignite.configuration());
             }
             catch (IOException e) {
                 // Select next shared directory if exists, otherwise throw exception

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsTimeoutTask.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsTimeoutTask.java b/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsTimeoutTask.java
index 3cf11f8..07619c0 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsTimeoutTask.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsTimeoutTask.java
@@ -25,6 +25,7 @@ import java.util.HashSet;
 import java.util.Map;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.Marshaller;
@@ -116,8 +117,13 @@ class SharedFsTimeoutTask extends IgniteSpiThread {
                     SharedFsTimeData timeData = entry.getValue();
 
                     try {
-                        if (timeData.getLastAccessTime() != file.lastModified())
-                            timeData.setExpireTime(SharedFsUtils.read(file, marshaller, log).getExpireTime());
+                        if (timeData.getLastAccessTime() != file.lastModified()) {
+                            final IgniteConfiguration igniteCfg = new IgniteConfiguration();
+
+                            igniteCfg.setGridName(getGridName());
+
+                            timeData.setExpireTime(SharedFsUtils.read(file, marshaller, log, igniteCfg).getExpireTime());
+                        }
                     }
                     catch (IgniteCheckedException e) {
                         U.error(log, "Failed to marshal/unmarshal in checkpoint file: " + file.getAbsolutePath(), e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsUtils.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsUtils.java b/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsUtils.java
index b1698fa..29a6a36 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsUtils.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/checkpoint/sharedfs/SharedFsUtils.java
@@ -25,8 +25,10 @@ import java.io.InputStream;
 import java.io.OutputStream;
 import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteLogger;
+import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 
 /**
  * Utility class that helps to manage files. It provides read/write
@@ -52,7 +54,7 @@ final class SharedFsUtils {
      *    to {@link SharedFsCheckpointData} object.
      * @throws IOException Thrown if file read error occurred.
      */
-    static SharedFsCheckpointData read(File file, Marshaller m, IgniteLogger log)
+    static SharedFsCheckpointData read(File file, Marshaller m, IgniteLogger log, final IgniteConfiguration igniteCfg)
         throws IOException, IgniteCheckedException {
         assert file != null;
         assert m != null;
@@ -61,7 +63,7 @@ final class SharedFsUtils {
         InputStream in = new FileInputStream(file);
 
         try {
-            return (SharedFsCheckpointData)m.unmarshal(in, U.gridClassLoader());
+            return (SharedFsCheckpointData) MarshallerUtils.unmarshal(igniteCfg.getGridName(), m, in, U.gridClassLoader());
         }
         finally {
             U.close(in, log);
@@ -76,11 +78,12 @@ final class SharedFsUtils {
      * @param data Checkpoint data.
      * @param m Grid marshaller.
      * @param log Messages logger.
+     * @param igniteCfg Ignite config.
      * @throws IgniteCheckedException Thrown if data could not be marshalled.
      * @throws IOException Thrown if file write operation failed.
      */
-    static void write(File file, SharedFsCheckpointData data, Marshaller m, IgniteLogger log)
-        throws IOException, IgniteCheckedException {
+    static void write(File file, SharedFsCheckpointData data, Marshaller m, IgniteLogger log,
+        final IgniteConfiguration igniteCfg) throws IOException, IgniteCheckedException {
         assert file != null;
         assert m != null;
         assert data != null;
@@ -91,7 +94,7 @@ final class SharedFsUtils {
         try {
             out = new FileOutputStream(file);
 
-            m.marshal(data, out);
+            MarshallerUtils.marshal(igniteCfg.getGridName(), m, data, out);
         }
         finally {
             U.close(out, log);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java b/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java
index ed29b59..5938db6 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/communication/tcp/TcpCommunicationSpi.java
@@ -3013,6 +3013,7 @@ public class TcpCommunicationSpi extends IgniteSpiAdapter
                     endpoint,
                     srvLsnr,
                     writerFactory,
+                    gridName,
                     new GridNioCodecFilter(new GridDirectParser(msgFactory, readerFactory), log, true),
                     new GridConnectionBytesVerifyFilter(log)
                 );

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ClientImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ClientImpl.java b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ClientImpl.java
index 79e58b1..78a1911 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ClientImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ClientImpl.java
@@ -64,6 +64,7 @@ import org.apache.ignite.internal.util.typedef.internal.LT;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteInClosure;
 import org.apache.ignite.lang.IgniteUuid;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.spi.IgniteSpiContext;
 import org.apache.ignite.spi.IgniteSpiException;
 import org.apache.ignite.spi.IgniteSpiOperationTimeoutHelper;
@@ -429,8 +430,7 @@ class ClientImpl extends TcpDiscoveryImpl {
             throw new IgniteClientDisconnectedException(null, "Failed to send custom message: client is disconnected.");
 
         try {
-            sockWriter.sendMessage(new TcpDiscoveryCustomEventMessage(getLocalNodeId(), evt,
-                spi.marsh.marshal(evt)));
+            sockWriter.sendMessage(new TcpDiscoveryCustomEventMessage(getLocalNodeId(), evt, marshal(evt)));
         }
         catch (IgniteCheckedException e) {
             throw new IgniteSpiException("Failed to marshal custom event: " + evt, e);
@@ -683,8 +683,10 @@ class ClientImpl extends TcpDiscoveryImpl {
             // Use security-unsafe getter.
             Map<String, Object> attrs = new HashMap<>(node.getAttributes());
 
-            attrs.put(IgniteNodeAttributes.ATTR_SECURITY_CREDENTIALS,
-                spi.marsh.marshal(attrs.get(IgniteNodeAttributes.ATTR_SECURITY_CREDENTIALS)));
+            attrs.put(
+                IgniteNodeAttributes.ATTR_SECURITY_CREDENTIALS,
+                marshal(attrs.get(IgniteNodeAttributes.ATTR_SECURITY_CREDENTIALS))
+            );
 
             node.setAttributes(attrs);
         }
@@ -885,7 +887,7 @@ class ClientImpl extends TcpDiscoveryImpl {
                         TcpDiscoveryAbstractMessage msg;
 
                         try {
-                            msg = spi.marsh.unmarshal(in, U.resolveClassLoader(spi.ignite().configuration()));
+                            msg = unmarshal(in);
                         }
                         catch (IgniteCheckedException e) {
                             if (log.isDebugEnabled())
@@ -1210,8 +1212,7 @@ class ClientImpl extends TcpDiscoveryImpl {
                         List<TcpDiscoveryAbstractMessage> msgs = null;
 
                         while (!isInterrupted()) {
-                            TcpDiscoveryAbstractMessage msg = spi.marsh.unmarshal(in,
-                                U.resolveClassLoader(spi.ignite().configuration()));
+                            TcpDiscoveryAbstractMessage msg = unmarshal(in);
 
                             if (msg instanceof TcpDiscoveryClientReconnectMessage) {
                                 TcpDiscoveryClientReconnectMessage res = (TcpDiscoveryClientReconnectMessage)msg;
@@ -1965,7 +1966,7 @@ class ClientImpl extends TcpDiscoveryImpl {
                     if (node != null && node.visible()) {
                         try {
                             DiscoverySpiCustomMessage msgObj = msg.message(spi.marsh,
-                                U.resolveClassLoader(spi.ignite().configuration()));
+                                U.resolveClassLoader(spi.ignite().configuration()), spi.ignite().name());
 
                             notifyDiscovery(EVT_DISCOVERY_CUSTOM_EVT, topVer, node, allVisibleNodes(), msgObj);
                         }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java
index 7f689c5..9211722 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ServerImpl.java
@@ -65,6 +65,7 @@ import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.cache.CacheMetrics;
 import org.apache.ignite.cluster.ClusterMetrics;
 import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.configuration.IgniteConfiguration;
 import org.apache.ignite.internal.IgniteFutureTimeoutCheckedException;
 import org.apache.ignite.internal.IgniteInterruptedCheckedException;
 import org.apache.ignite.internal.IgniteNodeAttributes;
@@ -90,6 +91,7 @@ import org.apache.ignite.lang.IgniteBiTuple;
 import org.apache.ignite.lang.IgniteInClosure;
 import org.apache.ignite.lang.IgniteProductVersion;
 import org.apache.ignite.lang.IgniteUuid;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.plugin.security.SecurityCredentials;
 import org.apache.ignite.plugin.security.SecurityPermissionSet;
 import org.apache.ignite.spi.IgniteNodeValidationResult;
@@ -740,7 +742,7 @@ class ServerImpl extends TcpDiscoveryImpl {
     /** {@inheritDoc} */
     @Override public void sendCustomEvent(DiscoverySpiCustomMessage evt) {
         try {
-            msgWorker.addMessage(new TcpDiscoveryCustomEventMessage(getLocalNodeId(), evt, spi.marsh.marshal(evt)));
+            msgWorker.addMessage(new TcpDiscoveryCustomEventMessage(getLocalNodeId(), evt, marshal(evt)));
         }
         catch (IgniteCheckedException e) {
             throw new IgniteSpiException("Failed to marshal custom event: " + evt, e);
@@ -823,7 +825,7 @@ class ServerImpl extends TcpDiscoveryImpl {
 
                         Map<String, Object> attrs = new HashMap<>(locNode.attributes());
 
-                        attrs.put(IgniteNodeAttributes.ATTR_SECURITY_SUBJECT, spi.marsh.marshal(subj));
+                        attrs.put(IgniteNodeAttributes.ATTR_SECURITY_SUBJECT, marshal(subj));
                         attrs.remove(IgniteNodeAttributes.ATTR_SECURITY_CREDENTIALS);
 
                         locNode.setAttributes(attrs);
@@ -1238,8 +1240,10 @@ class ServerImpl extends TcpDiscoveryImpl {
             // Use security-unsafe getter.
             Map<String, Object> attrs = new HashMap<>(node.getAttributes());
 
-            attrs.put(IgniteNodeAttributes.ATTR_SECURITY_CREDENTIALS,
-                spi.marsh.marshal(attrs.get(IgniteNodeAttributes.ATTR_SECURITY_CREDENTIALS)));
+            attrs.put(
+                IgniteNodeAttributes.ATTR_SECURITY_CREDENTIALS,
+                marshal(attrs.get(IgniteNodeAttributes.ATTR_SECURITY_CREDENTIALS))
+            );
 
             node.setAttributes(attrs);
         }
@@ -1262,7 +1266,7 @@ class ServerImpl extends TcpDiscoveryImpl {
             if (credBytes == null)
                 return null;
 
-            return spi.marsh.unmarshal(credBytes, null);
+            return MarshallerUtils.unmarshal(spi.ignite().name(), spi.marsh, credBytes, null);
         }
         catch (IgniteCheckedException e) {
             throw new IgniteSpiException("Failed to unmarshal node security credentials: " + node.id(), e);
@@ -2356,7 +2360,7 @@ class ServerImpl extends TcpDiscoveryImpl {
                 for (ClientMessageWorker clientMsgWorker : clientMsgWorkers.values()) {
                     if (msgBytes == null) {
                         try {
-                            msgBytes = spi.marsh.marshal(msg);
+                            msgBytes = marshal(msg);
                         }
                         catch (IgniteCheckedException e) {
                             U.error(log, "Failed to marshal message: " + msg, e);
@@ -2375,7 +2379,7 @@ class ServerImpl extends TcpDiscoveryImpl {
 
                         if (clientMsgWorker.clientNodeId.equals(node.id())) {
                             try {
-                                msg0 = spi.marsh.unmarshal(msgBytes,
+                                msg0 = MarshallerUtils.unmarshal(spi.ignite().name(), spi.marsh, msgBytes,
                                     U.resolveClassLoader(spi.ignite().configuration()));
 
                                 prepareNodeAddedMessage(msg0, clientMsgWorker.clientNodeId, null, null, null);
@@ -3134,7 +3138,7 @@ class ServerImpl extends TcpDiscoveryImpl {
                             // Stick in authentication subject to node (use security-safe attributes for copy).
                             Map<String, Object> attrs = new HashMap<>(node.getAttributes());
 
-                            attrs.put(IgniteNodeAttributes.ATTR_SECURITY_SUBJECT, spi.marsh.marshal(subj));
+                            attrs.put(IgniteNodeAttributes.ATTR_SECURITY_SUBJECT, marshal(subj));
 
                             node.setAttributes(attrs);
                         }
@@ -3785,9 +3789,11 @@ class ServerImpl extends TcpDiscoveryImpl {
                         else {
                             SecurityContext subj = spi.nodeAuth.authenticateNode(node, cred);
 
-                            SecurityContext coordSubj = spi.marsh.unmarshal(
+                            final IgniteConfiguration cfg = spi.ignite().configuration();
+
+                            SecurityContext coordSubj = MarshallerUtils.unmarshal(cfg.getGridName(), spi.marsh,
                                 node.<byte[]>attribute(IgniteNodeAttributes.ATTR_SECURITY_SUBJECT),
-                                U.resolveClassLoader(spi.ignite().configuration()));
+                                U.resolveClassLoader(cfg));
 
                             if (!permissionsEqual(coordSubj.subject().permissions(), subj.subject().permissions())) {
                                 // Node has not pass authentication.
@@ -4838,7 +4844,8 @@ class ServerImpl extends TcpDiscoveryImpl {
                     DiscoverySpiCustomMessage msgObj = null;
 
                     try {
-                        msgObj = msg.message(spi.marsh, U.resolveClassLoader(spi.ignite().configuration()));
+                        msgObj = msg.message(spi.marsh, U.resolveClassLoader(spi.ignite().configuration()),
+                                spi.ignite().name());
                     }
                     catch (Throwable e) {
                         U.error(log, "Failed to unmarshal discovery custom message.", e);
@@ -4849,8 +4856,8 @@ class ServerImpl extends TcpDiscoveryImpl {
 
                         if (nextMsg != null) {
                             try {
-                                TcpDiscoveryCustomEventMessage ackMsg = new TcpDiscoveryCustomEventMessage(
-                                    getLocalNodeId(), nextMsg, spi.marsh.marshal(nextMsg));
+                                TcpDiscoveryCustomEventMessage ackMsg =
+                                    new TcpDiscoveryCustomEventMessage(getLocalNodeId(), nextMsg, marshal(nextMsg));
 
                                 ackMsg.topologyVersion(msg.topologyVersion());
 
@@ -4981,8 +4988,10 @@ class ServerImpl extends TcpDiscoveryImpl {
 
                 if (node != null) {
                     try {
+                        final IgniteConfiguration cfg = spi.ignite().configuration();
+
                         DiscoverySpiCustomMessage msgObj = msg.message(spi.marsh,
-                            U.resolveClassLoader(spi.ignite().configuration()));
+                            U.resolveClassLoader(cfg), cfg.getGridName());
 
                         lsnr.onDiscovery(DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT,
                             msg.topologyVersion(),
@@ -4992,7 +5001,7 @@ class ServerImpl extends TcpDiscoveryImpl {
                             msgObj);
 
                         if (msgObj.isMutable())
-                            msg.message(msgObj, spi.marsh.marshal(msgObj));
+                            msg.message(msgObj, marshal(msgObj));
                     }
                     catch (Throwable e) {
                         U.error(log, "Failed to unmarshal discovery custom message.", e);
@@ -5428,8 +5437,7 @@ class ServerImpl extends TcpDiscoveryImpl {
 
                 while (!isInterrupted()) {
                     try {
-                        TcpDiscoveryAbstractMessage msg = spi.marsh.unmarshal(in,
-                            U.resolveClassLoader(spi.ignite().configuration()));
+                        TcpDiscoveryAbstractMessage msg = unmarshal(in);
 
                         msg.senderNodeId(nodeId);
 
@@ -5919,7 +5927,7 @@ class ServerImpl extends TcpDiscoveryImpl {
                 byte[] msgBytes = msgT.get2();
 
                 if (msgBytes == null)
-                    msgBytes = spi.marsh.marshal(msg);
+                    msgBytes = marshal(msg);
 
                 if (msg instanceof TcpDiscoveryClientAckResponse) {
                     if (clientVer == null) {

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryImpl.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryImpl.java b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryImpl.java
index 30b83e5..d049314 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryImpl.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoveryImpl.java
@@ -17,6 +17,7 @@
 
 package org.apache.ignite.spi.discovery.tcp;
 
+import java.io.InputStream;
 import java.net.InetSocketAddress;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
@@ -26,12 +27,15 @@ import java.util.Date;
 import java.util.List;
 import java.util.UUID;
 import java.util.concurrent.ConcurrentLinkedDeque;
+
+import org.apache.ignite.IgniteCheckedException;
 import org.apache.ignite.IgniteException;
 import org.apache.ignite.IgniteLogger;
 import org.apache.ignite.cluster.ClusterNode;
 import org.apache.ignite.internal.IgniteInterruptedCheckedException;
 import org.apache.ignite.internal.util.typedef.internal.LT;
 import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.spi.IgniteSpiContext;
 import org.apache.ignite.spi.IgniteSpiException;
 import org.apache.ignite.spi.IgniteSpiThread;
@@ -326,4 +330,27 @@ abstract class TcpDiscoveryImpl {
 
         return res;
     }
+
+    /**
+     * Marshal object.
+     *
+     * @param obj Object.
+     * @return Result.
+     * @throws IgniteCheckedException If failed.
+     */
+    protected byte[] marshal(Object obj) throws IgniteCheckedException {
+        return MarshallerUtils.marshal(spi.ignite().name(), spi.marsh, obj);
+    }
+
+    /**
+     * Unmarshal object.
+     *
+     * @param in Input stream.
+     * @return Result.
+     * @throws IgniteCheckedException If failed.
+     */
+    protected <T> T unmarshal(InputStream in) throws IgniteCheckedException {
+        return MarshallerUtils.unmarshal(spi.ignite().configuration().getGridName(), spi.marsh, in,
+            U.resolveClassLoader(spi.ignite().configuration()));
+    }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpi.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpi.java b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpi.java
index 308830e..1fb5482 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpi.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySpi.java
@@ -64,6 +64,7 @@ import org.apache.ignite.lang.IgniteInClosure;
 import org.apache.ignite.lang.IgniteProductVersion;
 import org.apache.ignite.lang.IgniteUuid;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.resources.IgniteInstanceResource;
 import org.apache.ignite.resources.LoggerResource;
@@ -1377,7 +1378,7 @@ public class TcpDiscoverySpi extends IgniteSpiAdapter implements DiscoverySpi, T
         IgniteCheckedException err = null;
 
         try {
-            marsh.marshal(msg, out);
+            MarshallerUtils.marshal(ignite.name(), marsh, msg, out);
         }
         catch (IgniteCheckedException e) {
             err = e;
@@ -1461,10 +1462,8 @@ public class TcpDiscoverySpi extends IgniteSpiAdapter implements DiscoverySpi, T
         try {
             sock.setSoTimeout((int)timeout);
 
-            T res = marsh.unmarshal(in == null ? sock.getInputStream() : in,
-                U.resolveClassLoader(ignite.configuration()));
-
-            return res;
+            return MarshallerUtils.unmarshal(ignite.configuration().getGridName(), marsh,
+                in == null ? sock.getInputStream() : in, U.resolveClassLoader(ignite.configuration()));
         }
         catch (IOException | IgniteCheckedException e) {
             if (X.hasCause(e, SocketTimeoutException.class))
@@ -1679,7 +1678,7 @@ public class TcpDiscoverySpi extends IgniteSpiAdapter implements DiscoverySpi, T
 
         for (Map.Entry<Integer, Serializable> entry : data.entrySet()) {
             try {
-                byte[] bytes = marsh.marshal(entry.getValue());
+                byte[] bytes = MarshallerUtils.marshal(ignite.name(), marsh, entry.getValue());
 
                 data0.put(entry.getKey(), bytes);
             }
@@ -1709,7 +1708,8 @@ public class TcpDiscoverySpi extends IgniteSpiAdapter implements DiscoverySpi, T
 
         for (Map.Entry<Integer, byte[]> entry : data.entrySet()) {
             try {
-                Serializable compData = marsh.unmarshal(entry.getValue(), clsLdr);
+                Serializable compData = MarshallerUtils.unmarshal(ignite.name(), marsh, entry.getValue(), clsLdr
+                );
 
                 data0.put(entry.getKey(), compData);
             }

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ipfinder/multicast/TcpDiscoveryMulticastIpFinder.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ipfinder/multicast/TcpDiscoveryMulticastIpFinder.java b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ipfinder/multicast/TcpDiscoveryMulticastIpFinder.java
index 8b29efd..ba19ade 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ipfinder/multicast/TcpDiscoveryMulticastIpFinder.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ipfinder/multicast/TcpDiscoveryMulticastIpFinder.java
@@ -40,6 +40,7 @@ import org.apache.ignite.internal.util.typedef.internal.LT;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.resources.LoggerResource;
 import org.apache.ignite.spi.IgniteSpiConfiguration;
@@ -593,7 +594,7 @@ public class TcpDiscoveryMulticastIpFinder extends TcpDiscoveryVmIpFinder {
                             AddressResponse addrRes;
 
                             try {
-                                addrRes = new AddressResponse(data);
+                                addrRes = new AddressResponse(data, getGridName());
                             }
                             catch (IgniteCheckedException e) {
                                 LT.warn(log, e, "Failed to deserialize multicast response.");
@@ -640,6 +641,15 @@ public class TcpDiscoveryMulticastIpFinder extends TcpDiscoveryVmIpFinder {
         }
     }
 
+    /**
+     * get Ignite configuration if possible.
+     *
+     * @return Ignite config or {@code null}.
+     */
+    @Nullable private String getGridName() {
+        return ignite == null ? null : ignite.name();
+    }
+
     /** {@inheritDoc} */
     @Override public void close() {
         if (addrSnds != null) {
@@ -688,14 +698,16 @@ public class TcpDiscoveryMulticastIpFinder extends TcpDiscoveryVmIpFinder {
          * @param addrs Addresses discovery SPI binds to.
          * @throws IgniteCheckedException If marshalling failed.
          */
-        private AddressResponse(Collection<InetSocketAddress> addrs) throws IgniteCheckedException {
+        private AddressResponse(Collection<InetSocketAddress> addrs, final String gridName) throws IgniteCheckedException {
             this.addrs = addrs;
 
-            byte[] addrsData = marsh.marshal(addrs);
+            byte[] addrsData = MarshallerUtils.marshal(gridName, marsh, addrs);
+
             data = new byte[U.IGNITE_HEADER.length + addrsData.length];
 
             if (data.length > MAX_DATA_LENGTH)
-                throw new IgniteCheckedException("Too long data packet [size=" + data.length + ", max=" + MAX_DATA_LENGTH + "]");
+                throw new IgniteCheckedException("Too long data packet [size=" + data.length +
+                    ", max=" + MAX_DATA_LENGTH + "]");
 
             System.arraycopy(U.IGNITE_HEADER, 0, data, 0, U.IGNITE_HEADER.length);
             System.arraycopy(addrsData, 0, data, 4, addrsData.length);
@@ -703,14 +715,16 @@ public class TcpDiscoveryMulticastIpFinder extends TcpDiscoveryVmIpFinder {
 
         /**
          * @param data Message data.
+         * @param gridName Grid name.
          * @throws IgniteCheckedException If unmarshalling failed.
          */
-        private AddressResponse(byte[] data) throws IgniteCheckedException {
+        private AddressResponse(byte[] data, final String gridName) throws IgniteCheckedException {
             assert U.bytesEqual(U.IGNITE_HEADER, 0, data, 0, U.IGNITE_HEADER.length);
 
             this.data = data;
 
-            addrs = marsh.unmarshal(Arrays.copyOfRange(data, U.IGNITE_HEADER.length, data.length), null);
+            addrs = MarshallerUtils.unmarshal(gridName, marsh,
+                    Arrays.copyOfRange(data, U.IGNITE_HEADER.length, data.length), null);
         }
 
         /**
@@ -829,7 +843,7 @@ public class TcpDiscoveryMulticastIpFinder extends TcpDiscoveryVmIpFinder {
             AddressResponse res;
 
             try {
-                res = new AddressResponse(addrs);
+                res = new AddressResponse(addrs, gridName);
             }
             catch (IgniteCheckedException e) {
                 U.error(log, "Failed to prepare multicast message.", e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/messages/TcpDiscoveryCustomEventMessage.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/messages/TcpDiscoveryCustomEventMessage.java b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/messages/TcpDiscoveryCustomEventMessage.java
index ca5dd56..897a4ed 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/messages/TcpDiscoveryCustomEventMessage.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/messages/TcpDiscoveryCustomEventMessage.java
@@ -18,9 +18,11 @@
 package org.apache.ignite.spi.discovery.tcp.messages;
 
 import java.util.UUID;
+
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.spi.discovery.DiscoverySpiCustomMessage;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -70,20 +72,26 @@ public class TcpDiscoveryCustomEventMessage extends TcpDiscoveryAbstractMessage
     }
 
     /**
-     * @return Deserialized message,
+     * @param marsh Marshaller.
+     * @param gridName Grid name.
+     * @return Deserialized message.
      * @throws java.lang.Throwable if unmarshal failed.
      */
-    @Nullable public DiscoverySpiCustomMessage message(@NotNull Marshaller marsh) throws Throwable {
-        return message(marsh, null);
+    @Nullable public DiscoverySpiCustomMessage message(@NotNull Marshaller marsh, String gridName) throws Throwable {
+        return message(marsh, null, gridName);
     }
 
     /**
-     * @return Deserialized message,
+     * @param marsh Marshaller.
+     * @param ldr Class loader.
+     * @param gridName Grid name.
+     * @return Deserialized message.
      * @throws java.lang.Throwable if unmarshal failed.
      */
-    @Nullable public DiscoverySpiCustomMessage message(@NotNull Marshaller marsh, ClassLoader ldr) throws Throwable {
+    @Nullable public DiscoverySpiCustomMessage message(@NotNull Marshaller marsh, ClassLoader ldr,
+        final String gridName) throws Throwable {
         if (msg == null) {
-            msg = marsh.unmarshal(msgBytes, ldr);
+            msg = MarshallerUtils.unmarshal(gridName, marsh, msgBytes, ldr);
 
             assert msg != null;
         }
@@ -104,4 +112,4 @@ public class TcpDiscoveryCustomEventMessage extends TcpDiscoveryAbstractMessage
     @Override public String toString() {
         return S.toString(TcpDiscoveryCustomEventMessage.class, this, "super", super.toString());
     }
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/spi/swapspace/file/FileSwapSpaceSpi.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/spi/swapspace/file/FileSwapSpaceSpi.java b/modules/core/src/main/java/org/apache/ignite/spi/swapspace/file/FileSwapSpaceSpi.java
index df35ed3..052a422 100644
--- a/modules/core/src/main/java/org/apache/ignite/spi/swapspace/file/FileSwapSpaceSpi.java
+++ b/modules/core/src/main/java/org/apache/ignite/spi/swapspace/file/FileSwapSpaceSpi.java
@@ -57,6 +57,7 @@ import org.apache.ignite.internal.util.typedef.internal.S;
 import org.apache.ignite.internal.util.typedef.internal.U;
 import org.apache.ignite.lang.IgniteBiInClosure;
 import org.apache.ignite.lang.IgniteInClosure;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.resources.LoggerResource;
 import org.apache.ignite.spi.IgniteSpiAdapter;
 import org.apache.ignite.spi.IgniteSpiCloseableIterator;
@@ -594,7 +595,7 @@ public class FileSwapSpaceSpi extends IgniteSpiAdapter implements SwapSpaceSpi,
 
         if (keyBytes == null) {
             try {
-                keyBytes = ignite.configuration().getMarshaller().marshal(key.key());
+                keyBytes = MarshallerUtils.marshal(ignite.name(), ignite.configuration().getMarshaller(), key.key());
             }
             catch (IgniteCheckedException e) {
                 throw new IgniteSpiException("Failed to marshal key: " + key.key(), e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/stream/socket/SocketMessageConverter.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/stream/socket/SocketMessageConverter.java b/modules/core/src/main/java/org/apache/ignite/stream/socket/SocketMessageConverter.java
index 03e82e3..9e2ca67 100644
--- a/modules/core/src/main/java/org/apache/ignite/stream/socket/SocketMessageConverter.java
+++ b/modules/core/src/main/java/org/apache/ignite/stream/socket/SocketMessageConverter.java
@@ -25,7 +25,8 @@ public interface SocketMessageConverter<T> {
      * Converter message represented by array of bytes to object.
      *
      * @param msg Message.
+     * @param gridName Grid name.
      * @return Converted object.
      */
-    public T convert(byte[] msg);
+    public T convert(byte[] msg, String gridName);
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/main/java/org/apache/ignite/stream/socket/SocketStreamer.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/stream/socket/SocketStreamer.java b/modules/core/src/main/java/org/apache/ignite/stream/socket/SocketStreamer.java
index 066a5fd..818ae6a 100644
--- a/modules/core/src/main/java/org/apache/ignite/stream/socket/SocketStreamer.java
+++ b/modules/core/src/main/java/org/apache/ignite/stream/socket/SocketStreamer.java
@@ -35,6 +35,7 @@ import org.apache.ignite.internal.util.nio.GridNioServerListenerAdapter;
 import org.apache.ignite.internal.util.nio.GridNioSession;
 import org.apache.ignite.internal.util.typedef.F;
 import org.apache.ignite.internal.util.typedef.internal.A;
+import org.apache.ignite.marshaller.MarshallerUtils;
 import org.apache.ignite.marshaller.jdk.JdkMarshaller;
 import org.apache.ignite.stream.StreamAdapter;
 import org.apache.ignite.stream.StreamTupleExtractor;
@@ -163,7 +164,7 @@ public class SocketStreamer<T, K, V> extends StreamAdapter<T, K, V> {
             }
 
             @Override public void onMessage(GridNioSession ses, byte[] msg) {
-                addMessage(converter.convert(msg));
+                addMessage(converter.convert(msg, ses.gridName()));
             }
         };
 
@@ -218,9 +219,9 @@ public class SocketStreamer<T, K, V> extends StreamAdapter<T, K, V> {
         private static final JdkMarshaller MARSH = new JdkMarshaller();
 
         /** {@inheritDoc} */
-        @Override public T convert(byte[] msg) {
+        @Override public T convert(byte[] msg, final String gridName) {
             try {
-                return MARSH.unmarshal(msg, null);
+                return MarshallerUtils.unmarshal(gridName, MARSH, msg, null);
             }
             catch (IgniteCheckedException e) {
                 throw new IgniteException(e);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridLocalIgniteSerializationTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridLocalIgniteSerializationTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridLocalIgniteSerializationTest.java
new file mode 100644
index 0000000..8531f92
--- /dev/null
+++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridLocalIgniteSerializationTest.java
@@ -0,0 +1,373 @@
+/*
+ * 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;
+
+import org.apache.ignite.Ignite;
+import org.apache.ignite.IgniteCache;
+import org.apache.ignite.Ignition;
+import org.apache.ignite.binary.BinaryObjectException;
+import org.apache.ignite.binary.BinaryReader;
+import org.apache.ignite.binary.BinaryWriter;
+import org.apache.ignite.binary.Binarylizable;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.binary.BinaryMarshaller;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.util.concurrent.Callable;
+
+/**
+ * Test for local Ignite instance processing during serialization/deserialization.
+ */
+public class GridLocalIgniteSerializationTest extends GridCommonAbstractTest {
+    /** */
+    private static final String CACHE_NAME = "cache_name";
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(final String gridName) throws Exception {
+        final IgniteConfiguration cfg = super.getConfiguration(gridName);
+
+        if (gridName != null && gridName.startsWith("binary"))
+            cfg.setMarshaller(new BinaryMarshaller());
+
+        return cfg;
+    }
+
+    /**
+     * Test that calling {@link Ignition#localIgnite()}
+     * is safe for binary marshaller.
+     *
+     * @throws Exception If failed.
+     */
+    public void testPutGetSimple() throws Exception {
+        testPutGet(new SimpleTestObject("one"), null);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPutGetSerializable() throws Exception {
+        testPutGet(new SerializableTestObject("test"), null);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPutGetExternalizable() throws Exception {
+        testPutGet(new ExternalizableTestObject("test"), null);
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    public void testPutGetBinarylizable() throws Exception {
+        testPutGet(new BinarylizableTestObject("test"), "binaryIgnite");
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
+    private void testPutGet(final TestObject obj, final String gridName) throws Exception {
+        // Run async to emulate user thread.
+        GridTestUtils.runAsync(new Callable<Object>() {
+            @Override public Object call() throws Exception {
+                try (final Ignite ignite = startGrid(gridName)) {
+                    final IgniteCache<Integer, TestObject> cache = ignite.getOrCreateCache(CACHE_NAME);
+
+                    assertNull(obj.ignite());
+
+                    cache.put(1, obj);
+
+                    assertNotNull(obj.ignite());
+
+                    final TestObject loadedObj = cache.get(1);
+
+                    assertNotNull(loadedObj.ignite());
+
+                    assertEquals(obj, loadedObj);
+                }
+
+                return null;
+            }
+        }).get();
+    }
+
+    /**
+     *
+     */
+    private interface TestObject {
+        /**
+         * @return Ignite instance.
+         */
+        Ignite ignite();
+    }
+
+    /**
+     * Test object.
+     */
+    private static class SimpleTestObject implements TestObject {
+        /** */
+        private final String val;
+
+        /** */
+        private transient Ignite ignite;
+
+        /** */
+        private SimpleTestObject(final String val) {
+            this.val = val;
+        }
+
+        /**
+         * @return Object.
+         */
+        @SuppressWarnings("unused")
+        private Object readResolve() {
+            ignite = Ignition.localIgnite();
+
+            return this;
+        }
+
+        /**
+         * @return Object.
+         */
+        @SuppressWarnings("unused")
+        private Object writeReplace() {
+            ignite = Ignition.localIgnite();
+
+            return this;
+        }
+
+        /** */
+        @Override public boolean equals(final Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+
+            final SimpleTestObject simpleTestObj = (SimpleTestObject) o;
+
+            return val != null ? val.equals(simpleTestObj.val) : simpleTestObj.val == null;
+
+        }
+
+        /** */
+        @Override public int hashCode() {
+            return val != null ? val.hashCode() : 0;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Ignite ignite() {
+            return ignite;
+        }
+    }
+
+    /**
+     *
+     */
+    private static class SerializableTestObject implements Serializable, TestObject {
+        /** */
+        private static final long serialVersionUID = 0L;
+
+        /** */
+        private String val;
+
+        /** */
+        private transient Ignite ignite;
+
+        /**
+         *
+         */
+        public SerializableTestObject() {
+        }
+
+        /**
+         * @param val Value
+         */
+        public SerializableTestObject(final String val) {
+            this.val = val;
+        }
+
+        /**
+         * @param out Object output.
+         * @throws IOException If fail.
+         */
+        private void writeObject(ObjectOutputStream out) throws IOException {
+            U.writeString(out, val);
+
+            ignite = Ignition.localIgnite();
+        }
+
+        /**
+         * @param in Object input.
+         * @throws IOException If fail.
+         */
+        private void readObject(ObjectInputStream in) throws IOException {
+            val = U.readString(in);
+
+            ignite = Ignition.localIgnite();
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(final Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+
+            final SerializableTestObject that = (SerializableTestObject) o;
+
+            return val != null ? val.equals(that.val) : that.val == null;
+
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return val != null ? val.hashCode() : 0;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Ignite ignite() {
+            return ignite;
+        }
+    }
+
+    /**
+     *
+     */
+    private static class ExternalizableTestObject implements Externalizable, TestObject {
+        /** */
+        private static final long serialVersionUID = 0L;
+
+        /** */
+        private String val;
+
+        /** */
+        private transient Ignite ignite;
+
+        /**
+         *
+         */
+        public ExternalizableTestObject() {
+        }
+
+        /**
+         * @param val Value.
+         */
+        public ExternalizableTestObject(final String val) {
+            this.val = val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void writeExternal(final ObjectOutput out) throws IOException {
+            U.writeString(out, val);
+
+            ignite = Ignition.localIgnite();
+        }
+
+        /** {@inheritDoc} */
+        @Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
+            val = U.readString(in);
+
+            ignite = Ignition.localIgnite();
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(final Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+
+            final ExternalizableTestObject that = (ExternalizableTestObject) o;
+
+            return val != null ? val.equals(that.val) : that.val == null;
+
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return val != null ? val.hashCode() : 0;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Ignite ignite() {
+            return ignite;
+        }
+    }
+
+    /**
+     *
+     */
+    private static class BinarylizableTestObject implements Binarylizable, TestObject {
+        /** */
+        private String val;
+
+        /** */
+        private transient Ignite ignite;
+
+        /**
+         *
+         */
+        public BinarylizableTestObject() {
+        }
+
+        /**
+         * @param val Value.
+         */
+        public BinarylizableTestObject(final String val) {
+            this.val = val;
+        }
+
+        /** {@inheritDoc} */
+        @Override public void writeBinary(final BinaryWriter writer) throws BinaryObjectException {
+            writer.rawWriter().writeString(val);
+
+            ignite = Ignition.localIgnite();
+        }
+
+        /** {@inheritDoc} */
+        @Override public void readBinary(final BinaryReader reader) throws BinaryObjectException {
+            val = reader.rawReader().readString();
+
+            ignite = Ignition.localIgnite();
+        }
+
+        /** {@inheritDoc} */
+        @Override public boolean equals(final Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+
+            final BinarylizableTestObject that = (BinarylizableTestObject) o;
+
+            return val != null ? val.equals(that.val) : that.val == null;
+
+        }
+
+        /** {@inheritDoc} */
+        @Override public int hashCode() {
+            return val != null ? val.hashCode() : 0;
+        }
+
+        /** {@inheritDoc} */
+        @Override public Ignite ignite() {
+            return ignite;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/test/java/org/apache/ignite/internal/util/nio/impl/GridNioFilterChainSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/util/nio/impl/GridNioFilterChainSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/util/nio/impl/GridNioFilterChainSelfTest.java
index 201fd27..61d93c1 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/util/nio/impl/GridNioFilterChainSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/util/nio/impl/GridNioFilterChainSelfTest.java
@@ -377,5 +377,10 @@ public class GridNioFilterChainSelfTest extends GridCommonAbstractTest {
         @Nullable @Override public GridNioRecoveryDescriptor recoveryDescriptor() {
             return null;
         }
+
+        /** {@inheritDoc} */
+        @Override public String gridName() {
+            return null;
+        }
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySelfTest.java b/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySelfTest.java
index 32d9072..7014608 100644
--- a/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/spi/discovery/tcp/TcpDiscoverySelfTest.java
@@ -1964,7 +1964,7 @@ public class TcpDiscoverySelfTest extends GridCommonAbstractTest {
                 if (msg instanceof TcpDiscoveryCustomEventMessage) {
                     try {
                         DiscoveryCustomMessage custMsg = GridTestUtils.getFieldValue(
-                            ((TcpDiscoveryCustomEventMessage)msg).message(marsh), "delegate");
+                            ((TcpDiscoveryCustomEventMessage)msg).message(marsh, null), "delegate");
 
                         if (custMsg instanceof StartRoutineAckDiscoveryMessage) {
                             log.info("Skip message send and stop node: " + msg);

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/test/java/org/apache/ignite/stream/socket/SocketStreamerSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/stream/socket/SocketStreamerSelfTest.java b/modules/core/src/test/java/org/apache/ignite/stream/socket/SocketStreamerSelfTest.java
index 1056990..a59ebea 100644
--- a/modules/core/src/test/java/org/apache/ignite/stream/socket/SocketStreamerSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/stream/socket/SocketStreamerSelfTest.java
@@ -169,7 +169,7 @@ public class SocketStreamerSelfTest extends GridCommonAbstractTest {
      */
     public void testSizeBasedCustomConverter() throws Exception {
         SocketMessageConverter<Message> converter = new SocketMessageConverter<Message>() {
-            @Override public Message convert(byte[] msg) {
+            @Override public Message convert(byte[] msg, String gridName) {
                 int i = (msg[0] & 0xFF) << 24;
                 i |= (msg[1] & 0xFF) << 16;
                 i |= (msg[2] & 0xFF) << 8;
@@ -233,7 +233,7 @@ public class SocketStreamerSelfTest extends GridCommonAbstractTest {
      */
     public void testDelimiterBasedCustomConverter() throws Exception {
         SocketMessageConverter<Message> converter = new SocketMessageConverter<Message>() {
-            @Override public Message convert(byte[] msg) {
+            @Override public Message convert(byte[] msg, String gridName) {
                 int i = (msg[0] & 0xFF) << 24;
                 i |= (msg[1] & 0xFF) << 16;
                 i |= (msg[2] & 0xFF) << 8;

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBasicTestSuite.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBasicTestSuite.java b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBasicTestSuite.java
index 98a876f..e613c31 100644
--- a/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBasicTestSuite.java
+++ b/modules/core/src/test/java/org/apache/ignite/testsuites/IgniteBasicTestSuite.java
@@ -34,6 +34,7 @@ import org.apache.ignite.internal.GridStartStopSelfTest;
 import org.apache.ignite.internal.GridStopWithCancelSelfTest;
 import org.apache.ignite.internal.IgniteSlowClientDetectionSelfTest;
 import org.apache.ignite.internal.processors.affinity.GridAffinityProcessorRendezvousSelfTest;
+import org.apache.ignite.internal.processors.cache.GridLocalIgniteSerializationTest;
 import org.apache.ignite.internal.processors.cache.GridProjectionForCachesOnDaemonNodeSelfTest;
 import org.apache.ignite.internal.processors.cache.IgniteDaemonNodeMarshallerCacheTest;
 import org.apache.ignite.internal.processors.cache.IgniteMarshallerCacheConcurrentReadWriteTest;
@@ -117,6 +118,7 @@ public class IgniteBasicTestSuite extends TestSuite {
         suite.addTestSuite(IgniteSlowClientDetectionSelfTest.class);
         GridTestUtils.addTestIfNeeded(suite, IgniteDaemonNodeMarshallerCacheTest.class, ignoredTests);
         suite.addTestSuite(IgniteMarshallerCacheConcurrentReadWriteTest.class);
+        suite.addTestSuite(GridLocalIgniteSerializationTest.class);
 
         suite.addTestSuite(IgniteExceptionInNioWorkerSelfTest.class);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopExternalCommunication.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopExternalCommunication.java b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopExternalCommunication.java
index 1d59a95..4203069 100644
--- a/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopExternalCommunication.java
+++ b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopExternalCommunication.java
@@ -1179,6 +1179,7 @@ public class HadoopExternalCommunication {
                 endpoint,
                 accepted,
                 srvLsnr,
+                gridName,
                 filters());
         }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopIpcToNioAdapter.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopIpcToNioAdapter.java b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopIpcToNioAdapter.java
index a8de999..3d68cbc 100644
--- a/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopIpcToNioAdapter.java
+++ b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopIpcToNioAdapter.java
@@ -62,14 +62,15 @@ public class HadoopIpcToNioAdapter<T> {
      * @param log Log.
      * @param endp Endpoint.
      * @param lsnr Listener.
+     * @param gridname Ignite config.
      * @param filters Filters.
      */
     public HadoopIpcToNioAdapter(IgniteLogger log, IpcEndpoint endp, boolean accepted,
-        GridNioServerListener<T> lsnr, GridNioFilter... filters) {
+        GridNioServerListener<T> lsnr, String gridname, GridNioFilter... filters) {
         this.endp = endp;
 
         chain = new GridNioFilterChain<>(log, lsnr, new HeadFilter(), filters);
-        ses = new GridNioSessionImpl(chain, null, null, accepted);
+        ses = new GridNioSessionImpl(chain, null, null, accepted, gridname);
 
         writeBuf = ByteBuffer.allocate(8 << 10);
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/e5f3abd2/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopMarshallerFilter.java
----------------------------------------------------------------------
diff --git a/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopMarshallerFilter.java b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopMarshallerFilter.java
index 3f79469..2c5c122 100644
--- a/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopMarshallerFilter.java
+++ b/modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/taskexecutor/external/communication/HadoopMarshallerFilter.java
@@ -23,6 +23,7 @@ import org.apache.ignite.internal.util.nio.GridNioFilterAdapter;
 import org.apache.ignite.internal.util.nio.GridNioFuture;
 import org.apache.ignite.internal.util.nio.GridNioSession;
 import org.apache.ignite.marshaller.Marshaller;
+import org.apache.ignite.marshaller.MarshallerUtils;
 
 /**
  * Serialization filter.
@@ -59,14 +60,15 @@ public class HadoopMarshallerFilter extends GridNioFilterAdapter {
     @Override public GridNioFuture<?> onSessionWrite(GridNioSession ses, Object msg) throws IgniteCheckedException {
         assert msg instanceof HadoopMessage : "Invalid message type: " + msg;
 
-        return proceedSessionWrite(ses, marshaller.marshal(msg));
+        return proceedSessionWrite(ses, MarshallerUtils.marshal(ses.gridName(), marshaller, msg));
     }
 
+    /** {@inheritDoc} */
     @Override public void onMessageReceived(GridNioSession ses, Object msg) throws IgniteCheckedException {
         assert msg instanceof byte[];
 
         // Always unmarshal with system classloader.
-        proceedMessageReceived(ses, marshaller.unmarshal((byte[])msg, null));
+        proceedMessageReceived(ses, MarshallerUtils.unmarshal(ses.gridName(), marshaller, (byte[])msg, null));
     }
 
     /** {@inheritDoc} */


[44/50] [abbrv] ignite git commit: Cherry-picked latest Visor fixes for UI and compatibility.

Posted by vo...@apache.org.
Cherry-picked latest Visor fixes for UI and compatibility.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 2b1c82cceee3f522f7d3ce50e8d74d0c9df066a0
Parents: 7cf26d9
Author: Alexey Kuznetsov <ak...@apache.org>
Authored: Fri Jul 29 17:54:35 2016 +0700
Committer: Alexey Kuznetsov <ak...@apache.org>
Committed: Fri Jul 29 17:54:35 2016 +0700

----------------------------------------------------------------------
 .../internal/visor/cache/VisorCacheV4.java      |  2 +-
 .../visor/node/VisorNodeDataCollectorJob.java   | 29 ++++++++++++++++----
 2 files changed, 25 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/2b1c82cc/modules/core/src/main/java/org/apache/ignite/internal/visor/cache/VisorCacheV4.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/visor/cache/VisorCacheV4.java b/modules/core/src/main/java/org/apache/ignite/internal/visor/cache/VisorCacheV4.java
index 81dbacb..a5f66be 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/visor/cache/VisorCacheV4.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/visor/cache/VisorCacheV4.java
@@ -86,7 +86,7 @@ public class VisorCacheV4 extends VisorCacheV2 {
 
     /** {@inheritDoc} */
     @Override public VisorCache history() {
-        return initHistory(new VisorCacheV3());
+        return initHistory(new VisorCacheV4());
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/2b1c82cc/modules/core/src/main/java/org/apache/ignite/internal/visor/node/VisorNodeDataCollectorJob.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/visor/node/VisorNodeDataCollectorJob.java b/modules/core/src/main/java/org/apache/ignite/internal/visor/node/VisorNodeDataCollectorJob.java
index 9a9b1cd..611dcde 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/visor/node/VisorNodeDataCollectorJob.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/visor/node/VisorNodeDataCollectorJob.java
@@ -21,8 +21,9 @@ import java.util.Collection;
 import java.util.concurrent.ConcurrentMap;
 import org.apache.ignite.IgniteFileSystem;
 import org.apache.ignite.cluster.ClusterNode;
+import org.apache.ignite.configuration.FileSystemConfiguration;
 import org.apache.ignite.configuration.IgniteConfiguration;
-import org.apache.ignite.internal.processors.cache.GridCacheProcessor;
+import org.apache.ignite.internal.managers.discovery.GridDiscoveryManager;
 import org.apache.ignite.internal.processors.igfs.IgfsProcessorAdapter;
 import org.apache.ignite.internal.util.ipc.IpcServerEndpoint;
 import org.apache.ignite.internal.util.typedef.internal.S;
@@ -56,7 +57,7 @@ public class VisorNodeDataCollectorJob extends VisorJob<VisorNodeDataCollectorTa
     private static final IgniteProductVersion VER_1_4_1 = IgniteProductVersion.fromString("1.4.1");
 
     /** */
-    private static final IgniteProductVersion VER_1_5_9 = IgniteProductVersion.fromString("1.5.9");
+    private static final IgniteProductVersion VER_1_5_10 = IgniteProductVersion.fromString("1.5.10");
 
     /** */
     private static final IgniteProductVersion VER_1_5_26 = IgniteProductVersion.fromString("1.5.26");
@@ -146,7 +147,7 @@ public class VisorNodeDataCollectorJob extends VisorJob<VisorNodeDataCollectorTa
         if (compatibleWith(VER_1_4_1))
             return new VisorCache();
 
-        if (compatibleWith(VER_1_5_9))
+        if (compatibleWith(VER_1_5_10))
             return new VisorCacheV2();
 
         if (compatibleWith(VER_1_5_26))
@@ -156,6 +157,18 @@ public class VisorNodeDataCollectorJob extends VisorJob<VisorNodeDataCollectorTa
     }
 
     /**
+     * @param cacheName Cache name to check.
+     * @return {@code true} if cache on local node is not a data cache or near cache disabled.
+     */
+    private boolean proxyCache(String cacheName) {
+        GridDiscoveryManager discovery = ignite.context().discovery();
+
+        ClusterNode locNode = ignite.localNode();
+
+        return !(discovery.cacheAffinityNode(locNode, cacheName) || discovery.cacheNearNode(locNode, cacheName));
+    }
+
+    /**
      * Collect caches.
      *
      * @param res Job result.
@@ -165,9 +178,10 @@ public class VisorNodeDataCollectorJob extends VisorJob<VisorNodeDataCollectorTa
         try {
             IgniteConfiguration cfg = ignite.configuration();
 
-            GridCacheProcessor cacheProc = ignite.context().cache();
+            for (String cacheName : ignite.context().cache().cacheNames()) {
+                if (proxyCache(cacheName))
+                    continue;
 
-            for (String cacheName : cacheProc.cacheNames()) {
                 if (arg.systemCaches() || !(isSystemCache(cacheName) || isIgfsCache(cfg, cacheName))) {
                     long start0 = U.currentTimeMillis();
 
@@ -205,6 +219,11 @@ public class VisorNodeDataCollectorJob extends VisorJob<VisorNodeDataCollectorTa
             for (IgniteFileSystem igfs : igfsProc.igfss()) {
                 long start0 = U.currentTimeMillis();
 
+                FileSystemConfiguration igfsCfg = igfs.configuration();
+
+                if (proxyCache(igfsCfg.getDataCacheName()) || proxyCache(igfsCfg.getMetaCacheName()))
+                    continue;
+
                 try {
                     Collection<IpcServerEndpoint> endPoints = igfsProc.endpoints(igfs.name());
 


[32/50] [abbrv] ignite git commit: IGNITE-3455: Entry placed on C++ side is not found on Java side

Posted by vo...@apache.org.
IGNITE-3455: Entry placed on C++ side is not found on Java side


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 84e83c96127a06f9d6b2ccc68d23db8f6dc089b1
Parents: 4897315
Author: Denis Magda <dm...@gridgain.com>
Authored: Mon Jul 18 15:21:46 2016 +0300
Committer: Denis Magda <dm...@gridgain.com>
Committed: Mon Jul 18 15:21:46 2016 +0300

----------------------------------------------------------------------
 .../ignite/internal/binary/BinaryContext.java   |  6 ++-
 .../binary/BinaryMarshallerSelfTest.java        | 41 ++++++++++++++++++++
 2 files changed, 46 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/84e83c96/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryContext.java
----------------------------------------------------------------------
diff --git a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryContext.java b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryContext.java
index 27e9440..d78c126 100644
--- a/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryContext.java
+++ b/modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryContext.java
@@ -1127,13 +1127,17 @@ public class BinaryContext {
                 mapper,
                 serializer,
                 true,
-                false
+                true
             );
 
             fieldsMeta = desc.fieldsMeta();
             schemas = desc.schema() != null ? Collections.singleton(desc.schema()) : null;
 
             descByCls.put(cls, desc);
+
+            // Registering in order to support the interoperability between Java, C++ and .Net.
+            // https://issues.apache.org/jira/browse/IGNITE-3455
+            predefinedTypes.put(id, desc);
         }
 
         metaHnd.addMeta(id, new BinaryMetadata(id, typeName, fieldsMeta, affKeyFieldName, schemas, isEnum).wrap(this));

http://git-wip-us.apache.org/repos/asf/ignite/blob/84e83c96/modules/core/src/test/java/org/apache/ignite/internal/binary/BinaryMarshallerSelfTest.java
----------------------------------------------------------------------
diff --git a/modules/core/src/test/java/org/apache/ignite/internal/binary/BinaryMarshallerSelfTest.java b/modules/core/src/test/java/org/apache/ignite/internal/binary/BinaryMarshallerSelfTest.java
index a504650..b3058de 100644
--- a/modules/core/src/test/java/org/apache/ignite/internal/binary/BinaryMarshallerSelfTest.java
+++ b/modules/core/src/test/java/org/apache/ignite/internal/binary/BinaryMarshallerSelfTest.java
@@ -1798,6 +1798,47 @@ public class BinaryMarshallerSelfTest extends GridCommonAbstractTest {
     /**
      * @throws Exception If failed.
      */
+    public void testCustomTypeRegistration() throws Exception {
+        BinaryTypeConfiguration customType = new BinaryTypeConfiguration(Value.class.getName());
+
+        BinaryMarshaller marsh = binaryMarshaller(Arrays.asList(customType));
+
+        BinaryContext ctx = binaryContext(marsh);
+
+        int typeId = ctx.typeId(Value.class.getName());
+
+        BinaryClassDescriptor descriptor = ctx.descriptorForTypeId(true, typeId, null, false);
+
+        assertEquals(Value.class, descriptor.describedClass());
+        assertEquals(true, descriptor.registered());
+        assertEquals(true, descriptor.userType());
+
+        // Custom explicit types must be registered in 'predefinedTypes' in order not to break the interoperability.
+        Field field = ctx.getClass().getDeclaredField("predefinedTypes");
+
+        field.setAccessible(true);
+
+        Map<Integer, BinaryClassDescriptor> map = (Map<Integer, BinaryClassDescriptor>)field.get(ctx);
+
+        assertTrue(map.size() > 0);
+
+        assertNotNull(map.get(typeId));
+
+        // Custom explicit types must NOT be registered in 'predefinedTypeNames'.
+        field = ctx.getClass().getDeclaredField("predefinedTypeNames");
+
+        field.setAccessible(true);
+
+        Map<String, Integer> map2 = (Map<String, Integer>)field.get(ctx);
+
+        assertTrue(map2.size() > 0);
+
+        assertNull(map2.get(ctx.userTypeName(Value.class.getName())));
+    }
+
+    /**
+     * @throws Exception If failed.
+     */
     public void testFieldIdMapping() throws Exception {
         BinaryTypeConfiguration customType1 = new BinaryTypeConfiguration(Value.class.getName());
 


[29/50] [abbrv] ignite git commit: IGNITE-3446 Visor CMD: improve usability for batch mode.

Posted by vo...@apache.org.
IGNITE-3446 Visor CMD: improve usability for batch mode.


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

Branch: refs/heads/ignite-1.5.31-1
Commit: 4897315b33a59e8566ffd026e99445279f27c53a
Parents: 6389400
Author: Andrey Novikov <an...@apache.org>
Authored: Fri Jul 15 16:54:21 2016 +0700
Committer: Andrey Novikov <an...@apache.org>
Committed: Fri Jul 15 16:54:21 2016 +0700

----------------------------------------------------------------------
 .../ignite/visor/commands/VisorConsole.scala    |   5 +-
 .../commands/alert/VisorAlertCommand.scala      |   2 +-
 .../commands/cache/VisorCacheCommand.scala      |  40 ++--
 .../commands/cache/VisorCacheStopCommand.scala  |   2 +-
 .../config/VisorConfigurationCommand.scala      |  23 ++-
 .../commands/events/VisorEventsCommand.scala    |  29 +--
 .../visor/commands/gc/VisorGcCommand.scala      |  11 +-
 .../visor/commands/kill/VisorKillCommand.scala  | 184 ++++++++++++++-----
 .../visor/commands/node/VisorNodeCommand.scala  |  13 +-
 .../visor/commands/vvm/VisorVvmCommand.scala    |  11 +-
 .../scala/org/apache/ignite/visor/visor.scala   |  76 +++++---
 11 files changed, 276 insertions(+), 120 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/4897315b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/VisorConsole.scala
----------------------------------------------------------------------
diff --git a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/VisorConsole.scala b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/VisorConsole.scala
index 6d91b05..b4d78b5 100644
--- a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/VisorConsole.scala
+++ b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/VisorConsole.scala
@@ -146,7 +146,10 @@ class VisorConsole {
         batchCommand.foreach(commands => batchStream = Some(commands.replaceAll(";", "\n")))
 
         val inputStream = batchStream match {
-            case Some(cmd) => new ByteArrayInputStream((cmd + "\nquit\n").getBytes("UTF-8"))
+            case Some(cmd) =>
+                visor.batchMode = true
+
+                new ByteArrayInputStream((cmd + "\nquit\n").getBytes("UTF-8"))
             case None => new FileInputStream(FileDescriptor.in)
         }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/4897315b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/alert/VisorAlertCommand.scala
----------------------------------------------------------------------
diff --git a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/alert/VisorAlertCommand.scala b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/alert/VisorAlertCommand.scala
index db60443..401a3f2 100644
--- a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/alert/VisorAlertCommand.scala
+++ b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/alert/VisorAlertCommand.scala
@@ -751,7 +751,7 @@ private case class VisorSentAlert(
     assert(spec != null)
 
     def idVar: String = {
-        val v = mfind(id)
+        val v = mfindHead(id)
 
         if (v.isDefined) id + "(@" + v.get._1 + ")" else id
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/4897315b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheCommand.scala
----------------------------------------------------------------------
diff --git a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheCommand.scala b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheCommand.scala
index b4ed6b8..a9f9137 100644
--- a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheCommand.scala
+++ b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheCommand.scala
@@ -73,12 +73,15 @@ import scala.language.{implicitConversions, reflectiveCalls}
  *
  * ====Arguments====
  * {{{
- *     -id=<node-id>
- *         Full ID of the node to get cache statistics from.
- *         Either '-id8' or '-id' can be specified.
- *         If neither is specified statistics will be gathered from all nodes.
  *     -id8=<node-id>
  *         ID8 of the node to get cache statistics from.
+ *         Note that either '-id8' or '-id' should be specified.
+ *         You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.
+ *         To specify oldest node on the same host as visor use variable '@nl'.
+ *         To specify oldest node on other hosts that are not running visor use variable '@nr'.
+ *         If neither is specified statistics will be gathered from all nodes.
+ *     -id=<node-id>
+ *         Full ID of the node to get cache statistics from.
  *         Either '-id8' or '-id' can be specified.
  *         If neither is specified statistics will be gathered from all nodes.
  *     -c=<cache-name>
@@ -278,7 +281,7 @@ class VisorCacheCommand {
                             else if (hasArgFlag("swap", argLst))
                                 VisorCacheSwapCommand().swap(argLst, node)
                             else if (hasArgFlag("stop", argLst))
-                                VisorCacheStopCommand().scan(argLst, node)
+                                VisorCacheStopCommand().stop(argLst, node)
                         }
                         else {
                             if (hasArgFlag("clear", argLst))
@@ -311,7 +314,12 @@ class VisorCacheCommand {
                 return
             }
 
-            println("Time of the snapshot: " + formatDateTime(System.currentTimeMillis))
+            node match {
+                case Some(n) =>
+                    println("ID8=" + nid8(n) + ", time of the snapshot: " + formatDateTime(System.currentTimeMillis))
+                case None =>
+                    println("Time of the snapshot: " + formatDateTime(System.currentTimeMillis))
+            }
 
             val sumT = VisorTextTable()
 
@@ -459,12 +467,12 @@ class VisorCacheCommand {
      */
     private def mkCacheName(@Nullable s: String): String = {
         if (s == null) {
-            val v = mfind(DFLT_CACHE_KEY)
+            val v = mfindHead(DFLT_CACHE_KEY)
 
             DFLT_CACHE_NAME + (if (v.isDefined) "(@" + v.get._1 + ')' else "")
         }
         else {
-            val v = mfind(s)
+            val v = mfindHead(s)
 
             s + (if (v.isDefined) "(@" + v.get._1 + ')' else "")
         }
@@ -649,7 +657,7 @@ class VisorCacheCommand {
 
         sumT.render()
 
-        val a = ask("\nChoose cache number ('c' to cancel) [c]: ", "c")
+        val a = ask("\nChoose cache number ('c' to cancel) [c]: ", "0")
 
         if (a.toLowerCase == "c")
             None
@@ -703,17 +711,19 @@ object VisorCacheCommand {
             "cache -stop -c=<cache-name>"
     ),
         args = Seq(
+            "-id8=<node-id>" -> Seq(
+                "ID8 of the node to get cache statistics from.",
+                "Note that either '-id8' or '-id' should be specified.",
+                "You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.",
+                "To specify oldest node on the same host as visor use variable '@nl'.",
+                "To specify oldest node on other hosts that are not running visor use variable '@nr'.",
+                "If neither is specified statistics will be gathered from all nodes."
+            ),
             "-id=<node-id>" -> Seq(
                 "Full ID of the node to get cache statistics from.",
                 "Either '-id8' or '-id' can be specified.",
                 "If neither is specified statistics will be gathered from all nodes."
             ),
-            "-id8=<node-id>" -> Seq(
-                "ID8 of the node to get cache statistics from.",
-                "Either '-id8' or '-id' can be specified.",
-                "If neither is specified statistics will be gathered from all nodes.",
-                "Note you can also use '@n0' ... '@nn' variables as shortcut to <node-id>."
-            ),
             "-c=<cache-name>" -> Seq(
                 "Name of the cache.",
                 "Note you can also use '@c0' ... '@cn' variables as shortcut to <cache-name>."

http://git-wip-us.apache.org/repos/asf/ignite/blob/4897315b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheStopCommand.scala
----------------------------------------------------------------------
diff --git a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheStopCommand.scala b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheStopCommand.scala
index bf81f73..1b55505 100644
--- a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheStopCommand.scala
+++ b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/cache/VisorCacheStopCommand.scala
@@ -76,7 +76,7 @@ class VisorCacheStopCommand {
      *
      * @param argLst Command arguments.
      */
-    def scan(argLst: ArgList, node: Option[ClusterNode]) {
+    def stop(argLst: ArgList, node: Option[ClusterNode]) {
         val cacheArg = argValue("c", argLst)
 
         val cacheName = cacheArg match {

http://git-wip-us.apache.org/repos/asf/ignite/blob/4897315b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/config/VisorConfigurationCommand.scala
----------------------------------------------------------------------
diff --git a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/config/VisorConfigurationCommand.scala b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/config/VisorConfigurationCommand.scala
index 3f0f52f..1b8bbd5 100644
--- a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/config/VisorConfigurationCommand.scala
+++ b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/config/VisorConfigurationCommand.scala
@@ -54,12 +54,16 @@ import scala.language.implicitConversions
  *
  * ====Arguments====
  * {{{
+ *     -id8=<node-id8>
+ *         Node ID8.
+ *         Note that either '-id8' or '-id' should be specified.
+ *         You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.
+ *         To specify oldest node on the same host as visor use variable '@nl'.
+ *         To specify oldest node on other hosts that are not running visor use variable '@nr'.
+ *         If neither is specified - command starts in interactive mode.
  *     -id=<node-id>
  *         Full node ID. Either '-id8' or '-id' can be specified.
  *         If neither is specified - command starts in interactive mode.
- *     -id8=<node-id8>
- *         Node ID8. Either '-id8' or '-id' can be specified.
- *         If neither is specified - command starts in interactive mode.
  * }}}
  *
  * ====Examples====
@@ -388,14 +392,17 @@ object VisorConfigurationCommand {
             s"${cmd.name} {-id=<node-id>|id8=<node-id8>}"
         ),
         args = List(
+            "-id8=<node-id8>" -> List(
+                "Node ID8.",
+                "Note that either '-id8' or '-id' should be specified.",
+                "You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.",
+                "To specify oldest node on the same host as visor use variable '@nl'.",
+                "To specify oldest node on other hosts that are not running visor use variable '@nr'.",
+                "If neither is specified - command starts in interactive mode."
+            ),
             "-id=<node-id>" -> List(
                 "Full node ID. Either '-id8' or '-id' can be specified.",
                 "If neither is specified - command starts in interactive mode."
-            ),
-            "-id8=<node-id8>" -> List(
-                "Node ID8. Either '-id8' or '-id' can be specified.",
-                "If neither is specified - command starts in interactive mode.",
-                "Note you can also use '@n0' ... '@nn' variables as shortcut to <node-id>."
             )
         ),
         examples = List(

http://git-wip-us.apache.org/repos/asf/ignite/blob/4897315b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/events/VisorEventsCommand.scala
----------------------------------------------------------------------
diff --git a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/events/VisorEventsCommand.scala b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/events/VisorEventsCommand.scala
index f7ea625..e3e73c7 100644
--- a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/events/VisorEventsCommand.scala
+++ b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/events/VisorEventsCommand.scala
@@ -65,12 +65,15 @@ import scala.language.implicitConversions
  *
  * ====Arguments====
  * {{{
- *     -id=<node-id>
- *         Full node ID.
- *         Either '-id' or '-id8' can be specified.
- *         If called without the arguments - starts in interactive mode.
  *     -id8
  *         Node ID8.
+ *         Note that either '-id8' or '-id' should be specified.
+ *         You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.
+ *         To specify oldest node on the same host as visor use variable '@nl'.
+ *         To specify oldest node on other hosts that are not running visor use variable '@nr'.
+ *         If called without the arguments - starts in interactive mode.
+ *     -id=<node-id>
+ *         Full node ID.
  *         Either '-id' or '-id8' can be specified.
  *         If called without the arguments - starts in interactive mode.
  *     -e=<ch,de,di,jo,ta,ca,cr,sw>
@@ -146,7 +149,7 @@ class VisorEventsCommand extends VisorConsoleCommand {
      */
     @throws[IllegalArgumentException]("In case unknown event mnemonic.")
     protected def typeFilter(typeArg: Option[String]) = {
-        typeArg.map(_.split(",").map(typeIds).flatten).orNull
+        typeArg.map(_.split(",").flatMap(typeIds)).orNull
     }
 
     /**
@@ -229,6 +232,8 @@ class VisorEventsCommand extends VisorConsoleCommand {
                             return
                     }
 
+                    println("ID8=" + nid8(node))
+
                     if (evts == null || evts.isEmpty) {
                         println("No events found.")
 
@@ -402,17 +407,19 @@ object VisorEventsCommand {
             "    {-t=<num>s|m|h|d} {-s=e|t} {-r} {-c=<n>}"
         ),
         args = List(
+            "-id8=<node-id8>" -> List(
+                "Node ID8.",
+                "Note that either '-id8' or '-id' should be specified.",
+                "You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.",
+                "To specify oldest node on the same host as visor use variable '@nl'.",
+                "To specify oldest node on other hosts that are not running visor use variable '@nr'.",
+                "If called without the arguments - starts in interactive mode."
+            ),
             "-id=<node-id>" -> List(
                 "Full node ID.",
                 "Either '-id' or '-id8' can be specified.",
                 "If called without the arguments - starts in interactive mode."
             ),
-            "-id8=<node-id8>" -> List(
-                "Node ID8.",
-                "Note that either '-id8' or '-id' can be specified and " +
-                    "you can also use '@n0' ... '@nn' variables as shortcut to <node-id8>.",
-                "If called without the arguments - starts in interactive mode."
-            ),
             "-e=<ch,de,di,jo,ta,ca,cr,sw>" -> List(
                 "Comma separated list of event types that should be queried:",
                 "   ch Checkpoint events.",

http://git-wip-us.apache.org/repos/asf/ignite/blob/4897315b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/gc/VisorGcCommand.scala
----------------------------------------------------------------------
diff --git a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/gc/VisorGcCommand.scala b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/gc/VisorGcCommand.scala
index a9bf39f..990fd00 100644
--- a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/gc/VisorGcCommand.scala
+++ b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/gc/VisorGcCommand.scala
@@ -52,7 +52,10 @@ import scala.language.{implicitConversions, reflectiveCalls}
  * {{{
  *     -id8=<node-id8>
  *         ID8 of the node.
- *         Note that either '-id8' or '-id' can be specified.
+ *         Note that either '-id8' or '-id' should be specified.
+ *         You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.
+ *         To specify oldest node on the same host as visor use variable '@nl'.
+ *         To specify oldest node on other hosts that are not running visor use variable '@nr'.
  *     -id=<node-id>
  *         ID of the node.
  *         Note that either '-id8' or '-id' can be specified.
@@ -159,8 +162,10 @@ object VisorGcCommand {
         args = List(
             "-id8=<node-id8>" -> List(
                 "ID8 of the node.",
-                "Note that either '-id8' or '-id' can be specified and " +
-                    "you can also use '@n0' ... '@nn' variables as shortcut to <node-id8>."
+                "Note that either '-id8' or '-id' should be specified.",
+                "You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.",
+                "To specify oldest node on the same host as visor use variable '@nl'.",
+                "To specify oldest node on other hosts that are not running visor use variable '@nr'."
             ),
             "-id=<node-id>" -> List(
                 "ID of the node.",

http://git-wip-us.apache.org/repos/asf/ignite/blob/4897315b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/kill/VisorKillCommand.scala
----------------------------------------------------------------------
diff --git a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/kill/VisorKillCommand.scala b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/kill/VisorKillCommand.scala
index dffd5f1..c705e21 100644
--- a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/kill/VisorKillCommand.scala
+++ b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/kill/VisorKillCommand.scala
@@ -46,7 +46,7 @@ import scala.util.control.Breaks._
  * {{{
  *     kill
  *     kill "-in|-ih"
- *     kill "{-r|-k} {-id8=<node-id8>|-id=<node-id>}"
+ *     kill "{-r|-k} {-sc} {-al|-ar|-id8=<node-id8>|-id=<node-id>}"
  * }}}
  *
  * ====Arguments====
@@ -61,17 +61,28 @@ import scala.util.control.Breaks._
  *         Run command in interactive mode with ability to
  *         choose a host where to kill or restart nodes.
  *         Note that either '-in' or '-ih' can be specified.
+ *     -al
+ *         Kill or restart all nodes on this host.
+ *         Note that either '-al' or '-ar' can be specified.
+ *     -ar
+ *         Kill or restart all nodes on other hosts.
+ *         Note that either '-al', '-ar' can be specified.
+ *     -sc
+ *         Skip kill or restart of client nodes for group nodes command.
  *     -r
  *         Restart node mode.
  *         Note that either '-r' or '-k' can be specified.
- *         If no parameters provided - command starts in interactive mode.
+ *         If no other parameters provided - command executes on all nodes.
  *     -k
  *         Kill (stop) node mode.
  *         Note that either '-r' or '-k' can be specified.
- *         If no parameters provided - command starts in interactive mode.
+ *         If no other parameters provided - command executes on all nodes.
  *     -id8=<node-id8>
  *         ID8 of the node to kill or restart.
- *         Note that either '-id8' or '-id' can be specified.
+ *         Note that either '-id8' or '-id' should be specified.
+ *         You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.
+ *         To specify oldest node on the same host as visor use variable '@nl'.
+ *         To specify oldest node on other hosts that are not running visor use variable '@nr'.
  *         If no parameters provided - command starts in interactive mode.
  *     -id=<node-id>
  *         ID of the node to kill or restart.
@@ -85,6 +96,16 @@ import scala.util.control.Breaks._
  *         Starts command in interactive mode.
  *     kill "-id8=12345678 -r"
  *         Restart node with '12345678' ID8.
+ *     kill -id8=@n0 -r" ->
+ *         Restart specified node with id8 taken from 'n0' memory variable.
+ *     kill -id8=@nl -r" ->
+ *         Restart oldest local node with id8 taken from 'nl' memory variable.
+ *     kill -id8=@nl -k" ->
+ *         Kill (stop) oldest remote node with id8 taken from 'nr' memory variable.
+ *     kill -r -ar" ->
+ *         Restart all remote nodes.
+ *     kill -k -sc -al" ->
+ *         Kill (stop) all local server nodes.
  *     kill "-k"
  *         Kill (stop) all nodes.
  * }}}
@@ -114,8 +135,12 @@ class VisorKillCommand extends VisorConsoleCommand {
             val iNodes = hasArgFlag("in", argLst)
             val iHosts = hasArgFlag("ih", argLst)
 
+            val skipClient = hasArgFlag("sc", argLst)
+
             if (iNodes && iHosts)
                 scold("Only one of '-in' or '-ih' can be specified.").^^
+            else if ((iNodes || iHosts) && skipClient)
+                scold("Skip client flag is not allowed in interactive mode.").^^
             else if (iNodes)
                 interactiveNodes().^^
             else if (iHosts)
@@ -126,52 +151,94 @@ class VisorKillCommand extends VisorConsoleCommand {
             val restart = hasArgFlag("r", argLst)
             val kill = hasArgFlag("k", argLst)
 
-            var node: ClusterNode = null
+            val allLocal = hasArgFlag("al", argLst)
+            val allRemote = hasArgFlag("ar", argLst)
 
             if (kill && restart)
                 scold("Only one of '-k' or '-r' can be specified.")
             else if (!kill && !restart)
                 scold("Missing '-k' or '-r' option in command: " + args)
-            else if (id8.isDefined && id.isDefined)
-                scold("Only one of -id8 or -id is allowed.")
+            else if (Seq(allLocal, allRemote, id8.isDefined, id.isDefined).count((v) => v) > 1)
+                scold("Only one of -al, -ar, -id8 or -id is allowed.")
+            else if ((id8.isDefined || id.isDefined) && skipClient)
+                scold("Skip client flag is allowed only for group command.")
             else {
-                if (id8.isDefined) {
+                val localGroup = ignite.cluster.forHost(ignite.localNode)
+
+                var nodes = if (id8.isDefined) {
                     val ns = nodeById8(id8.get)
 
                     if (ns.isEmpty)
                         scold("Unknown 'id8' value: " + id8.get).^^
-                    else if (ns.size != 1) {
+
+                    if (ns.size != 1)
                         scold("'id8' resolves to more than one node (use full 'id' instead) : " + args).^^
-                    }
-                    else
-                        node = ns.head
+
+                    ns.toSeq
                 }
-                else if (id.isDefined)
-                    try {
-                        node = ignite.cluster.node(java.util.UUID.fromString(id.get))
+                else if (id.isDefined) {
+                    var nid: UUID = null
 
-                        if (node == null)
-                            scold("'id' does not match any node : " + args).^^
+                    try {
+                        nid = UUID.fromString(id.get)
                     }
                     catch {
                         case e: IllegalArgumentException => scold("Invalid node 'id' in args: " + args).^^
                     }
 
-                if (node == null && (id.isDefined || id8.isDefined))
-                    scold("Node with given ID cannot be found.").^^
+                    val nodes = ignite.cluster.forNodeId(nid).nodes()
+
+                    if (nodes.isEmpty)
+                        scold("'id' does not match any node : " + args).^^
+
+                    nodes.toSeq
+                } else if (allLocal) {
+                    if (skipClient)
+                        localGroup.forServers().nodes().toSeq
+                    else
+                        localGroup.nodes().toSeq
+                }
+                else if (allRemote) {
+                    val remoteGroup = ignite.cluster.forOthers(localGroup)
+
+                    if (skipClient)
+                        remoteGroup.forServers().nodes().toSeq
+                    else
+                        remoteGroup.nodes().toSeq
+                }
+                else {
+                    if (skipClient)
+                        ignite.cluster.forServers().nodes().toSeq
+                    else
+                        ignite.cluster.nodes().toSeq
+                }
+
+                if (nodes.isEmpty) {
+                    if (id.isDefined || id8.isDefined)
+                        scold("Node with given ID cannot be found.").^^
+                    else if (allLocal)
+                        scold("Local nodes cannot be found.").^^
+                    else if (allRemote)
+                        scold("Remote nodes cannot be found.").^^
+                }
+
+                if (restart) {
+                    val excludeNodes = nodes.filter(_.attribute[String](ATTR_RESTART_ENABLED) == "false")
+
+                    nodes = nodes.filter(_.attribute[String](ATTR_RESTART_ENABLED) == "true")
 
-                try
                     // In case of the restart - check that target node supports it.
-                    if (restart && node != null && node.attribute[String](ATTR_RESTART_ENABLED) != "true")
-                        scold("Node doesn't support restart: " + nid8(node)).^^
-                catch {
-                    case e: IgniteException => scold("Failed to restart the node. " + e.getMessage).^^
+                    if (excludeNodes.nonEmpty)
+                        scold("Node(s) doesn't support restart: " + excludeNodes.map(nid8).mkString("[", ", ", "]")).^^
+
+                    if (nodes.isEmpty)
+                        break
                 }
 
                 val op = if (restart) "restart" else "kill"
 
                 try
-                    killOrRestart(if (node == null) ignite.cluster.nodes().map(_.id()) else Collections.singleton(node.id()), restart)
+                    killOrRestart(nodes.map(_.id()), restart)
                 catch {
                     case _: IgniteException => scold("Failed to " + op + " due to system error.").^^
                 }
@@ -205,29 +272,31 @@ class VisorKillCommand extends VisorConsoleCommand {
 
         val op = if (restart) "restart" else "kill"
 
-        if (nodes.size == ignite.cluster.nodes().size())
-            ask("Are you sure you want to " + op + " ALL nodes? (y/n) [n]: ", "n") match {
-                case "y" | "Y" =>  ask("You are about to " + op + " ALL nodes. " +
-                    "Are you 100% sure? (y/n) [n]: ", "n") match {
+        if (!batchMode) {
+            if (nodes.size == ignite.cluster.nodes().size())
+                ask("Are you sure you want to " + op + " ALL nodes? (y/n) [n]: ", "n") match {
+                    case "y" | "Y" => ask("You are about to " + op + " ALL nodes. " +
+                        "Are you 100% sure? (y/n) [n]: ", "n") match {
                         case "y" | "Y" => ()
                         case "n" | "N" => break()
                         case x => nl(); warn("Invalid answer: " + x); break()
                     }
-                case "n" | "N" => break()
-                case x => nl(); warn("Invalid answer: " + x); break()
-            }
-        else if (nodes.size > 1)
-            ask("Are you sure you want to " + op + " several nodes? (y/n) [n]: ", "n") match {
-                case "y" | "Y" => ()
-                case "n" | "N" => break()
-                case x => nl(); warn("Invalid answer: " + x); break()
-            }
-        else
-            ask("Are you sure you want to " + op + " this node? (y/n) [n]: ", "n") match {
-                case "y" | "Y" => ()
-                case "n" | "N" => break()
-                case x => nl(); warn("Invalid answer: " + x); break()
-            }
+                    case "n" | "N" => break()
+                    case x => nl(); warn("Invalid answer: " + x); break()
+                }
+            else if (nodes.size > 1)
+                ask("Are you sure you want to " + op + " several nodes? (y/n) [n]: ", "n") match {
+                    case "y" | "Y" => ()
+                    case "n" | "N" => break()
+                    case x => nl(); warn("Invalid answer: " + x); break()
+                }
+            else
+                ask("Are you sure you want to " + op + " " + nid8(nodes.head) + " node? (y/n) [n]: ", "n") match {
+                    case "y" | "Y" => ()
+                    case "n" | "N" => break()
+                    case x => nl(); warn("Invalid answer: " + x); break()
+                }
+        }
 
         if (restart)
             ignite.cluster.restartNodes(nodes)
@@ -278,7 +347,7 @@ object VisorKillCommand {
         spec = List(
             cmd.name,
             s"${cmd.name} -in|-ih",
-            s"${cmd.name} {-r|-k} {-id8=<node-id8>|-id=<node-id>}"
+            s"${cmd.name} {-r|-k} {-sc} {-al|-ar|-id8=<node-id8>|-id=<node-id>}"
         ),
         args = List(
             "-in" -> List(
@@ -293,6 +362,17 @@ object VisorKillCommand {
                 "choose a host where to kill or restart nodes.",
                 "Note that either '-in' or '-ih' can be specified."
             ),
+            "-al" -> List(
+                "Kill (stop) all local nodes.",
+                "Note that either '-al' or '-ar' can be specified."
+            ),
+            "-ar" -> List(
+                "Kill (stop) all remote nodes.",
+                "Note that either '-al' or '-ar' can be specified."
+            ),
+            "-sc" -> List(
+                "Skip kill or restart of client nodes for group nodes command."
+            ),
             "-r" -> List(
                 "Restart node mode.",
                 "Note that either '-r' or '-k' can be specified.",
@@ -305,8 +385,10 @@ object VisorKillCommand {
             ),
             "-id8=<node-id8>" -> List(
                 "ID8 of the node to kill or restart.",
-                "Note that either '-id8' or '-id' can be specified and " +
-                    "you can also use '@n0' ... '@nn' variables as shortcut to <node-id8>.",
+                "Note that either '-id8' or '-id' should be specified.",
+                "You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.",
+                "To specify oldest node on the same host as visor use variable '@nl'.",
+                "To specify oldest node on other hosts that are not running visor use variable '@nr'.",
                 "If no parameters provided - command starts in interactive mode."
             ),
             "-id=<node-id>" -> List(
@@ -322,6 +404,14 @@ object VisorKillCommand {
                 "Restart node with id8.",
             s"${cmd.name} -id8=@n0 -r" ->
                 "Restart specified node with id8 taken from 'n0' memory variable.",
+            s"${cmd.name} -id8=@nl -r" ->
+                "Restart oldest local node with id8 taken from 'nl' memory variable.",
+            s"${cmd.name} -id8=@nl -k" ->
+                "Kill (stop) oldest remote node with id8 taken from 'nr' memory variable.",
+            s"${cmd.name} -r -ar" ->
+                "Restart all remote nodes.",
+            s"${cmd.name} -k -sc -al" ->
+                "Kill (stop) all local server nodes.",
             s"${cmd.name} -k" ->
                 "Kill (stop) all nodes."
         ),

http://git-wip-us.apache.org/repos/asf/ignite/blob/4897315b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/node/VisorNodeCommand.scala
----------------------------------------------------------------------
diff --git a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/node/VisorNodeCommand.scala b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/node/VisorNodeCommand.scala
index 9ba0129..899e495 100644
--- a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/node/VisorNodeCommand.scala
+++ b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/node/VisorNodeCommand.scala
@@ -57,7 +57,11 @@ import scala.util.control.Breaks._
  * ====Arguments====
  * {{{
  *     -id8=<node-id8>
- *         ID8 of node. Either '-id8' or '-id' can be specified.
+ *         ID8 of node.
+ *         Note that either '-id8' or '-id' should be specified.
+ *         You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.
+ *         To specify oldest node on the same host as visor use variable '@nl'.
+ *         To specify oldest node on other hosts that are not running visor use variable '@nr'.
  *         If neither specified - command starts in interactive mode.
  *     -id=<node-id>
  *         Full ID of node. Either '-id8' or '-id' can  be specified.
@@ -295,8 +299,11 @@ object VisorNodeCommand {
         ),
         args = List(
             "-id8=<node-id8>" -> List(
-                "Note that either '-id8' or '-id' can be specified and " +
-                    "you can also use '@n0' ... '@nn' variables as shortcut to <node-id8>.",
+                "ID8 of node.",
+                "Note that either '-id8' or '-id' should be specified.",
+                "You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.",
+                "To specify oldest node on the same host as visor use variable '@nl'.",
+                "To specify oldest node on other hosts that are not running visor use variable '@nr'.",
                 "If neither specified - command starts in interactive mode."
             ),
             "-id=<node-id>" -> List(

http://git-wip-us.apache.org/repos/asf/ignite/blob/4897315b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/vvm/VisorVvmCommand.scala
----------------------------------------------------------------------
diff --git a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/vvm/VisorVvmCommand.scala b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/vvm/VisorVvmCommand.scala
index ff5cf82..e935256 100644
--- a/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/vvm/VisorVvmCommand.scala
+++ b/modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/vvm/VisorVvmCommand.scala
@@ -60,7 +60,10 @@ import scala.util.control.Breaks._
  *         If not specified, PATH and JAVA_HOME will be searched.
  *     -id8=<node-id8>
  *         ID8 of node.
- *         Either '-id8' or '-id' can be specified.
+ *         Note that either '-id8' or '-id' should be specified.
+ *         You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.
+ *         To specify oldest node on the same host as visor use variable '@nl'.
+ *         To specify oldest node on other hosts that are not running visor use variable '@nr'.
  *     -id=<node-id>
  *         Full ID of node.
  *         Either '-id8' or '-id' can be specified.
@@ -260,8 +263,10 @@ object VisorVvmCommand {
             ),
             "-id8=<node-id8>" -> List(
                 "ID8 of node.",
-                "Note that either '-id8' or '-id' can be specified and " +
-                    "you can also use '@n0' ... '@nn' variables as shortcut to <node-id8>."
+                "Note that either '-id8' or '-id' should be specified.",
+                "You can also use '@n0' ... '@nn' variables as a shortcut for <node-id8>.",
+                "To specify oldest node on the same host as visor use variable '@nl'.",
+                "To specify oldest node on other hosts that are not running visor use variable '@nr'."
             ),
             "-id=<node-id>" -> List(
                 "Full ID of node.",

http://git-wip-us.apache.org/repos/asf/ignite/blob/4897315b/modules/visor-console/src/main/scala/org/apache/ignite/visor/visor.scala
----------------------------------------------------------------------
diff --git a/modules/visor-console/src/main/scala/org/apache/ignite/visor/visor.scala b/modules/visor-console/src/main/scala/org/apache/ignite/visor/visor.scala
index 7f7d1f9..1e8b634 100644
--- a/modules/visor-console/src/main/scala/org/apache/ignite/visor/visor.scala
+++ b/modules/visor-console/src/main/scala/org/apache/ignite/visor/visor.scala
@@ -234,6 +234,8 @@ object visor extends VisorTag {
 
     private var reader: ConsoleReader = null
 
+    var batchMode: Boolean = false
+
     def reader(reader: ConsoleReader) {
         assert(reader != null)
 
@@ -661,12 +663,18 @@ object visor extends VisorTag {
     }
 
     /**
-     * Finds variable by its value.
+     * Finds variables by its value.
      *
      * @param v Value to find by.
      */
-    def mfind(@Nullable v: String): Option[(String, String)] =
-        mem find(t => t._2 == v)
+    def mfind(@Nullable v: String) = mem.filter(t => t._2 == v).toSeq
+
+    /**
+      * Finds variable by its value.
+      *
+      * @param v Value to find by.
+      */
+    def mfindHead(@Nullable v: String) = mfind(v).filterNot(entry => Seq("nl", "nr").contains(entry._1)).headOption
 
     /**
      * Sets Visor console memory variable. Note that this method '''does not'''
@@ -872,7 +880,7 @@ object visor extends VisorTag {
                 case _ => Left("'id8' resolves to more than one node (use full 'id' instead): " + id8.get)
             }
         }
-        else if (id.isDefined)
+        else if (id.isDefined) {
             try {
                 val node = Option(ignite.cluster.node(java.util.UUID.fromString(id.get)))
 
@@ -884,6 +892,7 @@ object visor extends VisorTag {
             catch {
                 case e: IllegalArgumentException => Left("Invalid node 'id': " + id.get)
             }
+        }
         else
             Right(None)
     }
@@ -1522,15 +1531,27 @@ object visor extends VisorTag {
                 setVarIfAbsent(ip.get, "h")
         })
 
+        val onHost = ignite.cluster.forHost(ignite.localNode())
+
+        Option(onHost.forServers().forOldest().node()).foreach(n => msetOpt("nl", nid8(n)))
+        Option(ignite.cluster.forOthers(onHost).forServers.forOldest().node()).foreach(n => msetOpt("nr", nid8(n)))
+
         nodeJoinLsnr = new IgnitePredicate[Event]() {
             override def apply(e: Event): Boolean = {
                 e match {
                     case de: DiscoveryEvent =>
-                        setVarIfAbsent(nid8(de.eventNode()), "n")
+                        val n = nid8(de.eventNode())
+
+                        setVarIfAbsent(n, "n")
 
                         val node = ignite.cluster.node(de.eventNode().id())
 
                         if (node != null) {
+                            val alias = if (U.sameMacs(ignite.localNode(), node)) "nl" else "nr"
+
+                            if (mgetOpt(alias).isEmpty)
+                                msetOpt(alias, n)
+
                             val ip = sortAddresses(node.addresses).headOption
 
                             if (ip.isDefined)
@@ -1551,29 +1572,25 @@ object visor extends VisorTag {
 
         ignite.events().localListen(nodeJoinLsnr, EVT_NODE_JOINED)
 
-        nodeLeftLsnr = new IgnitePredicate[Event]() {
-            override def apply(e: Event): Boolean = {
-                e match {
-                    case (de: DiscoveryEvent) =>
-                        val nv = mfind(nid8(de.eventNode()))
+        val mclear = (node: ClusterNode) => {
+            mfind(nid8(node)).foreach(nv => mem.remove(nv._1))
 
-                        if (nv.isDefined)
-                            mem.remove(nv.get._1)
+            val onHost = ignite.cluster.forHost(ignite.localNode())
 
-                        val ip = sortAddresses(de.eventNode().addresses).headOption
+            if (mgetOpt("nl").isEmpty)
+                Option(onHost.forServers().forOldest().node()).foreach(n => msetOpt("nl", nid8(n)))
 
-                        if (ip.isDefined) {
-                            val last = !ignite.cluster.nodes().exists(n =>
-                                n.addresses.size > 0 && sortAddresses(n.addresses).head == ip.get
-                            )
+            if (mgetOpt("nr").isEmpty)
+                Option(ignite.cluster.forOthers(onHost).forServers.forOldest().node()).foreach(n => msetOpt("nr", nid8(n)))
 
-                            if (last) {
-                                val hv = mfind(ip.get)
+            if (onHost.nodes().isEmpty)
+                sortAddresses(node.addresses).headOption.foreach((ip) => mfind(ip).foreach(hv => mem.remove(hv._1)))
+        }
 
-                                if (hv.isDefined)
-                                    mem.remove(hv.get._1)
-                            }
-                        }
+        nodeLeftLsnr = new IgnitePredicate[Event]() {
+            override def apply(e: Event): Boolean = {
+                e match {
+                    case (de: DiscoveryEvent) => mclear(de.eventNode())
                 }
 
                 true
@@ -1594,6 +1611,8 @@ object visor extends VisorTag {
 
                             close()
                         }
+                        else
+                            mclear(de.eventNode())
                 }
 
                 true
@@ -1658,7 +1677,7 @@ object visor extends VisorTag {
             val n = ignite.cluster.node(id)
 
             val id8 = nid8(id)
-            val v = mfind(id8)
+            val v = mfindHead(id8)
 
             id8 +
                 (if (v.isDefined) "(@" + v.get._1 + ")" else "") +
@@ -1678,7 +1697,7 @@ object visor extends VisorTag {
         assert(isCon)
 
         val id8 = nid8(id)
-        val v = mfind(id8)
+        val v = mfindHead(id8)
 
         id8 + (if (v.isDefined) "(@" + v.get._1 + ")" else "")
     }
@@ -1846,7 +1865,7 @@ object visor extends VisorTag {
 
             t.render()
 
-            val a = ask("\nChoose node number ('c' to cancel) [c]: ", "c")
+            val a = ask("\nChoose node number ('c' to cancel) [0]: ", "0")
 
             if (a.toLowerCase == "c")
                 None
@@ -1929,7 +1948,7 @@ object visor extends VisorTag {
 
             t.render()
 
-            val a = ask("\nChoose host number ('c' to cancel) [c]: ", "c")
+            val a = ask("\nChoose host number ('c' to cancel) [0]: ", "0")
 
             if (a.toLowerCase == "c")
                 None
@@ -2000,6 +2019,9 @@ object visor extends VisorTag {
         assert(prompt != null)
         assert(dflt != null)
 
+        if (batchMode)
+            return dflt
+
         readLineOpt(prompt, if (passwd) Some('*') else None) match {
             case None => dflt
             case Some(s) if s.length == 0 => dflt


[34/50] [abbrv] ignite git commit: GG-11293: .NET: Backported affinity functions feature to 7.5.30.

Posted by vo...@apache.org.
http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityFunctionContext.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityFunctionContext.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityFunctionContext.cs
new file mode 100644
index 0000000..6067af4
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityFunctionContext.cs
@@ -0,0 +1,120 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Cache.Affinity
+{
+    using System.Collections.Generic;
+    using System.Diagnostics;
+    using Apache.Ignite.Core.Binary;
+    using Apache.Ignite.Core.Cluster;
+    using Apache.Ignite.Core.Events;
+    using Apache.Ignite.Core.Impl;
+
+    /// <summary>
+    /// Affinity function context.
+    /// </summary>
+    public class AffinityFunctionContext
+    {
+        /** */
+        private readonly List<List<IClusterNode>> _previousAssignment;
+
+        /** */
+        private readonly int _backups;
+
+        /** */
+        private readonly ICollection<IClusterNode> _currentTopologySnapshot;
+
+        /** */
+        private readonly AffinityTopologyVersion _currentTopologyVersion;
+
+        /** */
+        private readonly DiscoveryEvent _discoveryEvent;
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="AffinityFunctionContext"/> class.
+        /// </summary>
+        /// <param name="reader">The reader.</param>
+        internal AffinityFunctionContext(IBinaryRawReader reader)
+        {
+            Debug.Assert(reader != null);
+
+            _currentTopologySnapshot = IgniteUtils.ReadNodes(reader);
+            _backups = reader.ReadInt();
+            _currentTopologyVersion = new AffinityTopologyVersion(reader.ReadLong(), reader.ReadInt());
+            _discoveryEvent = EventReader.Read<DiscoveryEvent>(reader);
+
+            // Prev assignment
+            var cnt = reader.ReadInt();
+
+            if (cnt > 0)
+            {
+                _previousAssignment = new List<List<IClusterNode>>(cnt);
+
+                for (var i = 0; i < cnt; i++)
+                    _previousAssignment.Add(IgniteUtils.ReadNodes(reader));
+            }
+        }
+
+        /// <summary>
+        /// Gets the affinity assignment for given partition on previous topology version.
+        /// First node in returned list is a primary node, other nodes are backups.
+        /// </summary>
+        /// <param name="partition">The partition to get previous assignment for.</param>
+        /// <returns>
+        /// List of nodes assigned to a given partition on previous topology version or <code>null</code>
+        /// if this information is not available.
+        /// </returns>
+        public ICollection<IClusterNode> GetPreviousAssignment(int partition)
+        {
+            return _previousAssignment == null ? null : _previousAssignment[partition];
+        }
+
+        /// <summary>
+        /// Gets number of backups for new assignment.
+        /// </summary>
+        public int Backups
+        {
+            get { return _backups; }
+        }
+
+        /// <summary>
+        /// Gets the current topology snapshot. Snapshot will contain only nodes on which the particular
+        /// cache is configured. List of passed nodes is guaranteed to be sorted in a same order
+        /// on all nodes on which partition assignment is performed.
+        /// </summary>
+        public ICollection<IClusterNode> CurrentTopologySnapshot
+        {
+            get { return _currentTopologySnapshot; }
+        }
+
+        /// <summary>
+        /// Gets the current topology version.
+        /// </summary>
+        public AffinityTopologyVersion CurrentTopologyVersion
+        {
+            get { return _currentTopologyVersion; }
+        }
+
+        /// <summary>
+        /// Gets the discovery event that caused the topology change.
+        /// </summary>
+        public DiscoveryEvent DiscoveryEvent
+        {
+            get { return _discoveryEvent; }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityTopologyVersion.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityTopologyVersion.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityTopologyVersion.cs
new file mode 100644
index 0000000..9bfdfb4
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/AffinityTopologyVersion.cs
@@ -0,0 +1,138 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Cache.Affinity
+{
+    using System;
+    using Apache.Ignite.Core.Cluster;
+
+    /// <summary>
+    /// Affinity topology version.
+    /// </summary>
+    public struct AffinityTopologyVersion : IEquatable<AffinityTopologyVersion>
+    {
+        /** */
+        private readonly long _version;
+
+        /** */
+        private readonly int _minorVersion;
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="AffinityTopologyVersion"/> struct.
+        /// </summary>
+        /// <param name="version">The version.</param>
+        /// <param name="minorVersion">The minor version.</param>
+        public AffinityTopologyVersion(long version, int minorVersion)
+        {
+            _version = version;
+            _minorVersion = minorVersion;
+        }
+
+        /// <summary>
+        /// Gets the major version, same as <see cref="ICluster.TopologyVersion"/>.
+        /// </summary>
+        public long Version
+        {
+            get { return _version; }
+        }
+
+        /// <summary>
+        /// Gets the minor version, which is increased when new caches start.
+        /// </summary>
+        public int MinorVersion
+        {
+            get { return _minorVersion; }
+        }
+
+        /// <summary>
+        /// Indicates whether the current object is equal to another object of the same type.
+        /// </summary>
+        /// <param name="other">An object to compare with this object.</param>
+        /// <returns>
+        /// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.
+        /// </returns>
+        public bool Equals(AffinityTopologyVersion other)
+        {
+            return _version == other._version && _minorVersion == other._minorVersion;
+        }
+
+        /// <summary>
+        /// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
+        /// </summary>
+        /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
+        /// <returns>
+        /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, 
+        /// <c>false</c>.
+        /// </returns>
+        public override bool Equals(object obj)
+        {
+            if (ReferenceEquals(null, obj)) return false;
+            return obj is AffinityTopologyVersion && Equals((AffinityTopologyVersion) obj);
+        }
+
+        /// <summary>
+        /// Returns a hash code for this instance.
+        /// </summary>
+        /// <returns>
+        /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. 
+        /// </returns>
+        public override int GetHashCode()
+        {
+            unchecked
+            {
+                return (_version.GetHashCode()*397) ^ _minorVersion;
+            }
+        }
+
+        /// <summary>
+        /// Implements the operator ==.
+        /// </summary>
+        /// <param name="left">The left.</param>
+        /// <param name="right">The right.</param>
+        /// <returns>
+        /// The result of the operator.
+        /// </returns>
+        public static bool operator ==(AffinityTopologyVersion left, AffinityTopologyVersion right)
+        {
+            return left.Equals(right);
+        }
+
+        /// <summary>
+        /// Implements the operator !=.
+        /// </summary>
+        /// <param name="left">The left.</param>
+        /// <param name="right">The right.</param>
+        /// <returns>
+        /// The result of the operator.
+        /// </returns>
+        public static bool operator !=(AffinityTopologyVersion left, AffinityTopologyVersion right)
+        {
+            return !left.Equals(right);
+        }
+
+        /// <summary>
+        /// Returns a <see cref="string" /> that represents this instance.
+        /// </summary>
+        /// <returns>
+        /// A <see cref="string" /> that represents this instance.
+        /// </returns>
+        public override string ToString()
+        {
+            return string.Format("AffinityTopologyVersion [Version={0}, MinorVersion={1}]", _version, _minorVersion);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/FairAffinityFunction.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/FairAffinityFunction.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/FairAffinityFunction.cs
new file mode 100644
index 0000000..4a3885f
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Fair/FairAffinityFunction.cs
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Cache.Affinity.Fair
+{
+    using System;
+
+    /// <summary>
+    /// Fair affinity function which tries to ensure that all nodes get equal number of partitions with 
+    /// minimum amount of reassignments between existing nodes.
+    /// </summary>
+    [Serializable]
+    public class FairAffinityFunction : AffinityFunctionBase
+    {
+        // No-op.
+        // Actual implementation is in Java, see AffinityFunctionSerializer.Write method.
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/IAffinityFunction.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/IAffinityFunction.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/IAffinityFunction.cs
new file mode 100644
index 0000000..b6c190c
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/IAffinityFunction.cs
@@ -0,0 +1,82 @@
+\ufeff/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Cache.Affinity
+{
+    using System;
+    using System.Collections.Generic;
+    using Apache.Ignite.Core.Cache.Affinity.Fair;
+    using Apache.Ignite.Core.Cache.Affinity.Rendezvous;
+    using Apache.Ignite.Core.Cluster;
+
+    /// <summary>
+    /// Represents a function that maps cache keys to cluster nodes.
+    /// <para />
+    /// Predefined implementations: 
+    /// <see cref="RendezvousAffinityFunction"/>, <see cref="FairAffinityFunction"/>.
+    /// </summary>
+    public interface IAffinityFunction
+    {
+        /// <summary>
+        /// Gets the total number of partitions.
+        /// <para />
+        /// All caches should always provide correct partition count which should be the same on all 
+        /// participating nodes. Note that partitions should always be numbered from 0 inclusively 
+        /// to N exclusively without any gaps.
+        /// </summary>
+        int Partitions { get; }
+
+        /// <summary>
+        /// Gets partition number for a given key starting from 0. Partitioned caches
+        /// should make sure that keys are about evenly distributed across all partitions
+        /// from 0 to <see cref="Partitions"/> for best performance.
+        /// <para />
+        /// Note that for fully replicated caches it is possible to segment key sets among different
+        /// grid node groups. In that case each node group should return a unique partition
+        /// number. However, unlike partitioned cache, mappings of keys to nodes in
+        /// replicated caches are constant and a node cannot migrate from one partition
+        /// to another.
+        /// </summary>
+        /// <param name="key">Key to get partition for.</param>
+        /// <returns>Partition number for a given key.</returns>
+        int GetPartition(object key);
+
+        /// <summary>
+        /// Removes node from affinity. This method is called when it is safe to remove 
+        /// disconnected node from affinity mapping.
+        /// </summary>
+        /// <param name="nodeId">The node identifier.</param>
+        void RemoveNode(Guid nodeId);
+
+        /// <summary>
+        /// Gets affinity nodes for a partition. In case of replicated cache, all returned
+        /// nodes are updated in the same manner. In case of partitioned cache, the returned
+        /// list should contain only the primary and back up nodes with primary node being
+        /// always first.
+        /// <pare />
+        /// Note that partitioned affinity must obey the following contract: given that node
+        /// <code>N</code> is primary for some key <code>K</code>, if any other node(s) leave
+        /// grid and no node joins grid, node <code>N</code> will remain primary for key <code>K</code>.
+        /// </summary>
+        /// <param name="context">The affinity function context.</param>
+        /// <returns>
+        /// A collection of partitions, where each partition is a collection of nodes,
+        /// where first node is a primary node, and other nodes are backup nodes.
+        /// </returns>
+        IEnumerable<IEnumerable<IClusterNode>> AssignPartitions(AffinityFunctionContext context);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/RendezvousAffinityFunction.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/RendezvousAffinityFunction.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/RendezvousAffinityFunction.cs
new file mode 100644
index 0000000..98ec364
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Cache/Affinity/Rendezvous/RendezvousAffinityFunction.cs
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Cache.Affinity.Rendezvous
+{
+    using System;
+
+    /// <summary>
+    /// Affinity function for partitioned cache based on Highest Random Weight algorithm.
+    /// </summary>
+    [Serializable]
+    public class RendezvousAffinityFunction : AffinityFunctionBase
+    {
+        // No-op.
+        // Actual implementation is in Java, see AffinityFunctionSerializer.Write method.
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Events/EventReader.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Events/EventReader.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Events/EventReader.cs
index cb1c715..ee1c837 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Events/EventReader.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Events/EventReader.cs
@@ -32,16 +32,14 @@ namespace Apache.Ignite.Core.Events
         /// <param name="reader">Reader.</param>
         /// <returns>Deserialized event.</returns>
         /// <exception cref="System.InvalidCastException">Incompatible event type.</exception>
-        public static T Read<T>(IBinaryReader reader) where T : IEvent
+        public static T Read<T>(IBinaryRawReader reader) where T : IEvent
         {
-            var r = reader.GetRawReader();
-
-            var clsId = r.ReadInt();
+            var clsId = reader.ReadInt();
 
             if (clsId == -1)
                 return default(T);
 
-            return (T) CreateInstance(clsId, r);
+            return (T) CreateInstance(clsId, reader);
         }
 
         /// <summary>

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Ignition.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Ignition.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Ignition.cs
index 7a3fafc..f6fab5d 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Ignition.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Ignition.cs
@@ -26,10 +26,12 @@ namespace Apache.Ignite.Core
     using System.Runtime;
     using System.Threading;
     using Apache.Ignite.Core.Binary;
+    using Apache.Ignite.Core.Cache.Affinity;
     using Apache.Ignite.Core.Common;
     using Apache.Ignite.Core.Impl;
     using Apache.Ignite.Core.Impl.Binary;
     using Apache.Ignite.Core.Impl.Binary.IO;
+    using Apache.Ignite.Core.Impl.Cache.Affinity;
     using Apache.Ignite.Core.Impl.Common;
     using Apache.Ignite.Core.Impl.Handle;
     using Apache.Ignite.Core.Impl.Memory;
@@ -233,6 +235,8 @@ namespace Apache.Ignite.Core
                 PrepareConfiguration(reader);
 
                 PrepareLifecycleBeans(reader, outStream, handleRegistry);
+
+                PrepareAffinityFunctions(reader, outStream);
             }
             catch (Exception e)
             {
@@ -282,7 +286,7 @@ namespace Apache.Ignite.Core
             int cnt = reader.ReadInt();
 
             for (int i = 0; i < cnt; i++)
-                beans.Add(new LifecycleBeanHolder(CreateLifecycleBean(reader)));
+                beans.Add(new LifecycleBeanHolder(CreateObject<ILifecycleBean>(reader)));
 
             // 2. Append beans definied in local configuration.
             ICollection<ILifecycleBean> nativeBeans = _startup.Configuration.LifecycleBeans;
@@ -306,21 +310,33 @@ namespace Apache.Ignite.Core
         }
 
         /// <summary>
-        /// Create lifecycle bean.
+        /// Prepares the affinity functions.
         /// </summary>
-        /// <param name="reader">Reader.</param>
-        /// <returns>Lifecycle bean.</returns>
-        private static ILifecycleBean CreateLifecycleBean(BinaryReader reader)
+        private static void PrepareAffinityFunctions(BinaryReader reader, PlatformMemoryStream outStream)
         {
-            // 1. Instantiate.
-            var bean = IgniteUtils.CreateInstance<ILifecycleBean>(reader.ReadString());
+            var cnt = reader.ReadInt();
+
+            var writer = reader.Marshaller.StartMarshal(outStream);
 
-            // 2. Set properties.
-            var props = reader.ReadDictionaryAsGeneric<string, object>();
+            for (var i = 0; i < cnt; i++)
+            {
+                var objHolder = new ObjectInfoHolder(reader);
+                AffinityFunctionSerializer.Write(writer, objHolder.CreateInstance<IAffinityFunction>(), objHolder);
+            }
+        }
+
+        /// <summary>
+        /// Creates an object and sets the properties.
+        /// </summary>
+        /// <param name="reader">Reader.</param>
+        /// <returns>Resulting object.</returns>
+        private static T CreateObject<T>(IBinaryRawReader reader)
+        {
+            var res =  IgniteUtils.CreateInstance<T>(reader.ReadString());
 
-            IgniteUtils.SetProperties(bean, props);
+            IgniteUtils.SetProperties(res, reader.ReadDictionaryAsGeneric<string, object>());
 
-            return bean;
+            return res;
         }
 
         /// <summary>

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/BinaryReaderExtensions.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/BinaryReaderExtensions.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/BinaryReaderExtensions.cs
index c3dcc3a..a5446ac 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/BinaryReaderExtensions.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/BinaryReaderExtensions.cs
@@ -19,6 +19,7 @@ namespace Apache.Ignite.Core.Impl.Binary
 {
     using System.Collections.Generic;
     using Apache.Ignite.Core.Binary;
+    using Apache.Ignite.Core.Impl.Common;
 
     /// <summary>
     /// Reader extensions.
@@ -48,5 +49,18 @@ namespace Apache.Ignite.Core.Impl.Binary
         {
             return (Dictionary<TKey, TValue>) reader.ReadDictionary(size => new Dictionary<TKey, TValue>(size));
         }
+
+        /// <summary>
+        /// Reads the object either as a normal object or as a [typeName+props] wrapper.
+        /// </summary>
+        public static T ReadObjectEx<T>(this IBinaryRawReader reader)
+        {
+            var obj = reader.ReadObject<object>();
+
+            if (obj == null)
+                return default(T);
+
+            return obj is T ? (T)obj : ((ObjectInfoHolder)obj).CreateInstance<T>();
+        }
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/Marshaller.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/Marshaller.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/Marshaller.cs
index 81fc195..a63e8f4 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/Marshaller.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Binary/Marshaller.cs
@@ -506,12 +506,15 @@ namespace Apache.Ignite.Core.Impl.Binary
         /// <summary>
         /// Adds a predefined system type.
         /// </summary>
-        private void AddSystemType<T>(byte typeId, Func<BinaryReader, T> ctor) where T : IBinaryWriteAware
+        private void AddSystemType<T>(int typeId, Func<BinaryReader, T> ctor) where T : IBinaryWriteAware
         {
             var type = typeof(T);
 
             var serializer = new BinarySystemTypeSerializer<T>(ctor);
 
+            if (typeId == 0)
+                typeId = BinaryUtils.TypeId(type.Name, null, null);
+
             AddType(type, typeId, BinaryUtils.GetTypeName(type), false, false, null, null, serializer, null, false);
         }
 
@@ -536,6 +539,7 @@ namespace Apache.Ignite.Core.Impl.Binary
             AddSystemType(BinaryUtils.TypeMessageListenerHolder, w => new MessageListenerHolder(w));
             AddSystemType(BinaryUtils.TypeStreamReceiverHolder, w => new StreamReceiverHolder(w));
             AddSystemType(BinaryUtils.TypePlatformJavaObjectFactoryProxy, w => new PlatformJavaObjectFactoryProxy());
+            AddSystemType(0, w => new ObjectInfoHolder(w));
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/Affinity/AffinityFunctionSerializer.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/Affinity/AffinityFunctionSerializer.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/Affinity/AffinityFunctionSerializer.cs
new file mode 100644
index 0000000..888445a
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/Affinity/AffinityFunctionSerializer.cs
@@ -0,0 +1,277 @@
+\ufeff/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Cache.Affinity
+{
+    using System;
+    using System.Collections.Generic;
+    using System.Diagnostics;
+    using System.IO;
+    using System.Linq;
+    using Apache.Ignite.Core.Binary;
+    using Apache.Ignite.Core.Cache.Affinity;
+    using Apache.Ignite.Core.Cache.Affinity.Fair;
+    using Apache.Ignite.Core.Cache.Affinity.Rendezvous;
+    using Apache.Ignite.Core.Cluster;
+    using Apache.Ignite.Core.Common;
+    using Apache.Ignite.Core.Impl.Binary;
+    using Apache.Ignite.Core.Impl.Binary.IO;
+    using Apache.Ignite.Core.Impl.Memory;
+
+    /// <summary>
+    /// Affinity function read/write methods.
+    /// </summary>
+    internal static class AffinityFunctionSerializer
+    {
+        /** */
+        private const byte TypeCodeNull = 0;
+
+        /** */
+        private const byte TypeCodeFair = 1;
+
+        /** */
+        private const byte TypeCodeRendezvous = 2;
+
+        /** */
+        private const byte TypeCodeUser = 3;
+
+        /// <summary>
+        /// Writes the instance.
+        /// </summary>
+        internal static void Write(IBinaryRawWriter writer, IAffinityFunction fun, object userFuncOverride = null)
+        {
+            Debug.Assert(writer != null);
+
+            if (fun == null)
+            {
+                writer.WriteByte(TypeCodeNull);
+                return;
+            }
+
+            // 1) Type code
+            // 2) Partitions
+            // 3) ExcludeNeighbors
+            // 4) Override flags
+            // 5) User object
+
+            var p = fun as AffinityFunctionBase;
+
+            if (p != null)
+            {
+                writer.WriteByte(p is FairAffinityFunction ? TypeCodeFair : TypeCodeRendezvous);
+                writer.WriteInt(p.Partitions);
+                writer.WriteBoolean(p.ExcludeNeighbors);
+
+                var overrideFlags = GetOverrideFlags(p.GetType());
+                writer.WriteByte((byte) overrideFlags);
+
+                // Do not write user func if there is nothing overridden
+                WriteUserFunc(writer, overrideFlags != UserOverrides.None ? fun : null, userFuncOverride);
+            }
+            else
+            {
+                writer.WriteByte(TypeCodeUser);
+                writer.WriteInt(fun.Partitions);
+                writer.WriteBoolean(false); // Exclude neighbors
+                writer.WriteByte((byte) UserOverrides.All);
+                WriteUserFunc(writer, fun, userFuncOverride);
+            }
+        }
+
+        /// <summary>
+        /// Reads the instance.
+        /// </summary>
+        internal static IAffinityFunction Read(IBinaryRawReader reader)
+        {
+            Debug.Assert(reader != null);
+
+            var typeCode = reader.ReadByte();
+
+            if (typeCode == TypeCodeNull)
+                return null;
+
+            var partitions = reader.ReadInt();
+            var exclNeighbors = reader.ReadBoolean();
+            var overrideFlags = (UserOverrides)reader.ReadByte();
+            var userFunc = reader.ReadObjectEx<IAffinityFunction>();
+
+            if (userFunc != null)
+            {
+                Debug.Assert(overrideFlags != UserOverrides.None);
+
+                var fair = userFunc as FairAffinityFunction;
+                if (fair != null)
+                {
+                    fair.Partitions = partitions;
+                    fair.ExcludeNeighbors = exclNeighbors;
+                }
+
+                var rendezvous = userFunc as RendezvousAffinityFunction;
+                if (rendezvous != null)
+                {
+                    rendezvous.Partitions = partitions;
+                    rendezvous.ExcludeNeighbors = exclNeighbors;
+                }
+
+                return userFunc;
+            }
+
+            Debug.Assert(overrideFlags == UserOverrides.None);
+            AffinityFunctionBase fun;
+
+            switch (typeCode)
+            {
+                case TypeCodeFair:
+                    fun = new FairAffinityFunction();
+                    break;
+                case TypeCodeRendezvous:
+                    fun = new RendezvousAffinityFunction();
+                    break;
+                default:
+                    throw new InvalidOperationException("Invalid AffinityFunction type code: " + typeCode);
+            }
+
+            fun.Partitions = partitions;
+            fun.ExcludeNeighbors = exclNeighbors;
+
+            return fun;
+        }
+
+
+        /// <summary>
+        /// Writes the partitions assignment to a stream.
+        /// </summary>
+        /// <param name="parts">The parts.</param>
+        /// <param name="stream">The stream.</param>
+        /// <param name="marsh">The marshaller.</param>
+        internal static void WritePartitions(IEnumerable<IEnumerable<IClusterNode>> parts,
+            PlatformMemoryStream stream, Marshaller marsh)
+        {
+            Debug.Assert(parts != null);
+            Debug.Assert(stream != null);
+            Debug.Assert(marsh != null);
+
+            IBinaryRawWriter writer = marsh.StartMarshal(stream);
+
+            var partCnt = 0;
+            writer.WriteInt(partCnt); // reserve size
+
+            foreach (var part in parts)
+            {
+                if (part == null)
+                    throw new IgniteException("IAffinityFunction.AssignPartitions() returned invalid partition: null");
+
+                partCnt++;
+
+                var nodeCnt = 0;
+                var cntPos = stream.Position;
+                writer.WriteInt(nodeCnt); // reserve size
+
+                foreach (var node in part)
+                {
+                    nodeCnt++;
+                    writer.WriteGuid(node.Id);
+                }
+
+                var endPos = stream.Position;
+                stream.Seek(cntPos, SeekOrigin.Begin);
+                stream.WriteInt(nodeCnt);
+                stream.Seek(endPos, SeekOrigin.Begin);
+            }
+
+            stream.SynchronizeOutput();
+            stream.Seek(0, SeekOrigin.Begin);
+            writer.WriteInt(partCnt);
+        }
+
+        /// <summary>
+        /// Reads the partitions assignment from a stream.
+        /// </summary>
+        /// <param name="stream">The stream.</param>
+        /// <param name="marsh">The marshaller.</param>
+        /// <returns>Partitions assignment.</returns>
+        internal static IEnumerable<IEnumerable<IClusterNode>> ReadPartitions(IBinaryStream stream, Marshaller marsh)
+        {
+            Debug.Assert(stream != null);
+            Debug.Assert(marsh != null);
+
+            IBinaryRawReader reader = marsh.StartUnmarshal(stream);
+
+            var partCnt = reader.ReadInt();
+
+            var res = new List<IEnumerable<IClusterNode>>(partCnt);
+
+            for (var i = 0; i < partCnt; i++)
+                res.Add(IgniteUtils.ReadNodes(reader));
+
+            return res;
+        }
+
+        /// <summary>
+        /// Gets the override flags.
+        /// </summary>
+        private static UserOverrides GetOverrideFlags(Type funcType)
+        {
+            var res = UserOverrides.None;
+
+            var methods = new[] {UserOverrides.GetPartition, UserOverrides.AssignPartitions, UserOverrides.RemoveNode};
+
+            var map = funcType.GetInterfaceMap(typeof(IAffinityFunction));
+
+            foreach (var method in methods)
+            {
+                // Find whether user type overrides IAffinityFunction method from AffinityFunctionBase.
+                var methodName = method.ToString();
+
+                if (map.TargetMethods.Single(x => x.Name == methodName).DeclaringType != typeof(AffinityFunctionBase))
+                    res |= method;
+            }
+
+            return res;
+        }
+
+        /// <summary>
+        /// Writes the user function.
+        /// </summary>
+        private static void WriteUserFunc(IBinaryRawWriter writer, IAffinityFunction func, object funcOverride)
+        {
+            if (funcOverride != null)
+            {
+                writer.WriteObject(funcOverride);
+                return;
+            }
+
+            if (func != null && !func.GetType().IsSerializable)
+                throw new IgniteException("AffinityFunction should be serializable.");
+
+            writer.WriteObject(func);
+        }
+
+        /// <summary>
+        /// Overridden function flags.
+        /// </summary>
+        [Flags]
+        private enum UserOverrides : byte
+        {
+            None = 0,
+            GetPartition = 1,
+            RemoveNode = 1 << 1,
+            AssignPartitions = 1 << 2,
+            All = GetPartition | RemoveNode | AssignPartitions
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/Affinity/PlatformAffinityFunction.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/Affinity/PlatformAffinityFunction.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/Affinity/PlatformAffinityFunction.cs
new file mode 100644
index 0000000..d335804
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Cache/Affinity/PlatformAffinityFunction.cs
@@ -0,0 +1,74 @@
+\ufeff/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Cache.Affinity
+{
+    using System;
+    using System.Collections.Generic;
+    using Apache.Ignite.Core.Cache.Affinity;
+    using Apache.Ignite.Core.Cluster;
+    using Apache.Ignite.Core.Impl.Binary;
+    using Apache.Ignite.Core.Impl.Unmanaged;
+
+    /// <summary>
+    /// Affinity function that delegates to Java.
+    /// </summary>
+    internal class PlatformAffinityFunction : PlatformTarget, IAffinityFunction
+    {
+        /** Opcodes. */
+        private enum  Op
+        {
+            Partition = 1,
+            RemoveNode = 2,
+            AssignPartitions = 3
+        }
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="PlatformAffinityFunction"/> class.
+        /// </summary>
+        /// <param name="target">Target.</param>
+        /// <param name="marsh">Marshaller.</param>
+        public PlatformAffinityFunction(IUnmanagedTarget target, Marshaller marsh) : base(target, marsh)
+        {
+            // No-op.
+        }
+
+        /** <inheritdoc /> */
+        public int Partitions
+        {
+            get { throw new NotSupportedException("PlatformAffinityFunction.Partitions is not supported."); }
+        }
+
+        /** <inheritdoc /> */
+        public int GetPartition(object key)
+        {
+            return (int) DoOutOp((int) Op.Partition, w => w.WriteObject(key));
+        }
+
+        /** <inheritdoc /> */
+        public void RemoveNode(Guid nodeId)
+        {
+            DoOutOp((int) Op.RemoveNode, w => w.WriteGuid(nodeId));
+        }
+
+        /** <inheritdoc /> */
+        public IEnumerable<IEnumerable<IClusterNode>> AssignPartitions(AffinityFunctionContext context)
+        {
+            return DoInOp((int) Op.AssignPartitions, s => AffinityFunctionSerializer.ReadPartitions(s, Marshaller));
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Common/ObjectInfoHolder.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Common/ObjectInfoHolder.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Common/ObjectInfoHolder.cs
new file mode 100644
index 0000000..407fe0c
--- /dev/null
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Common/ObjectInfoHolder.cs
@@ -0,0 +1,86 @@
+\ufeff/*
+ * 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.
+ */
+
+namespace Apache.Ignite.Core.Impl.Common
+{
+    using System.Collections.Generic;
+    using System.Diagnostics;
+    using Apache.Ignite.Core.Binary;
+    using Apache.Ignite.Core.Impl.Binary;
+
+    /// <summary>
+    /// Holds the information to instantiate an object and set its properties.
+    /// Typically used for .NET objects defined in Spring XML.
+    /// </summary>
+    internal class ObjectInfoHolder : IBinaryWriteAware
+    {
+        /** Type name. */
+        private readonly string _typeName;
+
+        /** Properties. */
+        private readonly Dictionary<string, object> _properties;
+
+        /// <summary>
+        /// Initializes a new instance of the <see cref="ObjectInfoHolder"/> class.
+        /// </summary>
+        /// <param name="reader">The reader.</param>
+        public ObjectInfoHolder(IBinaryRawReader reader)
+        {
+            Debug.Assert(reader != null);
+
+            _typeName = reader.ReadString();
+            _properties = reader.ReadDictionaryAsGeneric<string, object>();
+
+            Debug.Assert(!string.IsNullOrEmpty(_typeName));
+        }
+
+        /// <summary>
+        /// Gets the name of the type.
+        /// </summary>
+        public string TypeName
+        {
+            get { return _typeName; }
+        }
+
+        /// <summary>
+        /// Gets the properties.
+        /// </summary>
+        public Dictionary<string, object> Properties
+        {
+            get { return _properties; }
+        }
+
+        /// <summary>
+        /// Creates an instance according to type name and properties.
+        /// </summary>
+        public T CreateInstance<T>()
+        {
+            return IgniteUtils.CreateInstance<T>(TypeName, Properties);
+        }
+
+        /** <inheritdoc /> */
+        public void WriteBinary(IBinaryWriter writer)
+        {
+            Debug.Assert(writer != null);
+
+            var w = writer.GetRawWriter();
+
+            w.WriteString(_typeName);
+            w.WriteDictionary(_properties);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Impl/IgniteUtils.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/IgniteUtils.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/IgniteUtils.cs
index 7929a5d..5d0d989 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/IgniteUtils.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/IgniteUtils.cs
@@ -128,8 +128,9 @@ namespace Apache.Ignite.Core.Impl
         /// Create new instance of specified class.
         /// </summary>
         /// <param name="typeName">Class name</param>
+        /// <param name="props">Properties to set.</param>
         /// <returns>New Instance.</returns>
-        public static T CreateInstance<T>(string typeName)
+        public static T CreateInstance<T>(string typeName, IEnumerable<KeyValuePair<string, object>> props = null)
         {
             IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName");
 
@@ -138,7 +139,12 @@ namespace Apache.Ignite.Core.Impl
             if (type == null)
                 throw new IgniteException("Failed to create class instance [className=" + typeName + ']');
 
-            return (T) Activator.CreateInstance(type);
+            var res = (T)Activator.CreateInstance(type);
+
+            if (props != null)
+                SetProperties(res, props);
+
+            return res;
         }
 
         /// <summary>

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbackHandlers.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbackHandlers.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbackHandlers.cs
index 8147e9d..dd16d03 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbackHandlers.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbackHandlers.cs
@@ -95,5 +95,11 @@ namespace Apache.Ignite.Core.Impl.Unmanaged
 
         internal void* extensionCbInLongOutLong;
         internal void* extensionCbInLongLongOutLong;
+
+        internal void* affinityFunctionInit;
+        internal void* affinityFunctionPartition;
+        internal void* affinityFunctionAssignPartitions;
+        internal void* affinityFunctionRemoveNode;
+        internal void* affinityFunctionDestroy;
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/5f57cc8d/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbacks.cs
----------------------------------------------------------------------
diff --git a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbacks.cs b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbacks.cs
index e554cfc..f4b3db9 100644
--- a/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbacks.cs
+++ b/modules/platforms/dotnet/Apache.Ignite.Core/Impl/Unmanaged/UnmanagedCallbacks.cs
@@ -21,14 +21,16 @@ namespace Apache.Ignite.Core.Impl.Unmanaged
     using System.Collections.Generic;
     using System.Diagnostics;
     using System.Diagnostics.CodeAnalysis;
+    using System.IO;
     using System.Runtime.InteropServices;
     using System.Threading;
-
+    using Apache.Ignite.Core.Cache.Affinity;
     using Apache.Ignite.Core.Cluster;
     using Apache.Ignite.Core.Common;
     using Apache.Ignite.Core.Impl.Binary;
     using Apache.Ignite.Core.Impl.Binary.IO;
     using Apache.Ignite.Core.Impl.Cache;
+    using Apache.Ignite.Core.Impl.Cache.Affinity;
     using Apache.Ignite.Core.Impl.Cache.Query.Continuous;
     using Apache.Ignite.Core.Impl.Cache.Store;
     using Apache.Ignite.Core.Impl.Common;
@@ -161,6 +163,12 @@ namespace Apache.Ignite.Core.Impl.Unmanaged
         private delegate long ExtensionCallbackInLongOutLongDelegate(void* target, int typ, long arg1);
         private delegate long ExtensionCallbackInLongLongOutLongDelegate(void* target, int typ, long arg1, long arg2);
 
+        private delegate long AffinityFunctionInitDelegate(void* target, long memPtr, void* baseFunc);
+        private delegate int AffinityFunctionPartitionDelegate(void* target, long ptr, long memPtr);
+        private delegate void AffinityFunctionAssignPartitionsDelegate(void* target, long ptr, long inMemPtr, long outMemPtr);
+        private delegate void AffinityFunctionRemoveNodeDelegate(void* target, long ptr, long memPtr);
+        private delegate void AffinityFunctionDestroyDelegate(void* target, long ptr);
+
         /// <summary>
         /// constructor.
         /// </summary>
@@ -240,7 +248,13 @@ namespace Apache.Ignite.Core.Impl.Unmanaged
                 error = CreateFunctionPointer((ErrorCallbackDelegate)Error),
                 
                 extensionCbInLongOutLong = CreateFunctionPointer((ExtensionCallbackInLongOutLongDelegate)ExtensionCallbackInLongOutLong),
-                extensionCbInLongLongOutLong = CreateFunctionPointer((ExtensionCallbackInLongLongOutLongDelegate)ExtensionCallbackInLongLongOutLong)
+                extensionCbInLongLongOutLong = CreateFunctionPointer((ExtensionCallbackInLongLongOutLongDelegate)ExtensionCallbackInLongLongOutLong),
+                
+                affinityFunctionInit = CreateFunctionPointer((AffinityFunctionInitDelegate)AffinityFunctionInit),
+                affinityFunctionPartition = CreateFunctionPointer((AffinityFunctionPartitionDelegate)AffinityFunctionPartition),
+                affinityFunctionAssignPartitions = CreateFunctionPointer((AffinityFunctionAssignPartitionsDelegate)AffinityFunctionAssignPartitions),
+                affinityFunctionRemoveNode = CreateFunctionPointer((AffinityFunctionRemoveNodeDelegate)AffinityFunctionRemoveNode),
+                affinityFunctionDestroy = CreateFunctionPointer((AffinityFunctionDestroyDelegate)AffinityFunctionDestroy)
             };
 
             _cbsPtr = Marshal.AllocHGlobal(UU.HandlersSize());
@@ -1057,7 +1071,120 @@ namespace Apache.Ignite.Core.Impl.Unmanaged
         }
 
         #endregion
-        
+
+        #region AffinityFunction
+
+        private long AffinityFunctionInit(void* target, long memPtr, void* baseFunc)
+        {
+            return SafeCall(() =>
+            {
+                using (var stream = IgniteManager.Memory.Get(memPtr).GetStream())
+                {
+                    var reader = _ignite.Marshaller.StartUnmarshal(stream);
+
+                    var func = reader.ReadObjectEx<IAffinityFunction>();
+
+                    ResourceProcessor.Inject(func, _ignite);
+
+                    var affBase = func as AffinityFunctionBase;
+
+                    if (affBase != null)
+                        affBase.SetBaseFunction(new PlatformAffinityFunction(
+                            _ignite.InteropProcessor.ChangeTarget(baseFunc), _ignite.Marshaller));
+
+                    return _handleRegistry.Allocate(func);
+                }
+            });
+        }
+
+        private int AffinityFunctionPartition(void* target, long ptr, long memPtr)
+        {
+            return SafeCall(() =>
+            {
+                using (var stream = IgniteManager.Memory.Get(memPtr).GetStream())
+                {
+                    var key = _ignite.Marshaller.Unmarshal<object>(stream);
+
+                    return _handleRegistry.Get<IAffinityFunction>(ptr, true).GetPartition(key);
+                }
+            });
+        }
+
+        private void AffinityFunctionAssignPartitions(void* target, long ptr, long inMemPtr, long outMemPtr)
+        {
+            SafeCall(() =>
+            {
+                using (var inStream = IgniteManager.Memory.Get(inMemPtr).GetStream())
+                {
+                    var ctx = new AffinityFunctionContext(_ignite.Marshaller.StartUnmarshal(inStream));
+                    var func = _handleRegistry.Get<IAffinityFunction>(ptr, true);
+                    var parts = func.AssignPartitions(ctx);
+
+                    if (parts == null)
+                        throw new IgniteException(func.GetType() + ".AssignPartitions() returned invalid result: null");
+
+                    using (var outStream = IgniteManager.Memory.Get(outMemPtr).GetStream())
+                    {
+                        var writer = _ignite.Marshaller.StartMarshal(outStream);
+
+                        var partCnt = 0;
+                        writer.WriteInt(partCnt);  // reserve size
+
+                        foreach (var part in parts)
+                        {
+                            if (part == null)
+                                throw new IgniteException(func.GetType() +
+                                                          ".AssignPartitions() returned invalid partition: null");
+
+                            partCnt++;
+
+                            var nodeCnt = 0;
+                            var cntPos = outStream.Position;
+                            writer.WriteInt(nodeCnt);  // reserve size
+
+                            foreach (var node in part)
+                            {
+                                nodeCnt++;
+                                writer.WriteGuid(node.Id);
+                            }
+
+                            var endPos = outStream.Position;
+                            outStream.Seek(cntPos, SeekOrigin.Begin);
+                            outStream.WriteInt(nodeCnt);
+                            outStream.Seek(endPos, SeekOrigin.Begin);
+                        }
+
+                        outStream.SynchronizeOutput();
+                        outStream.Seek(0, SeekOrigin.Begin);
+                        writer.WriteInt(partCnt);
+                    }
+                }
+            });
+        }
+
+        private void AffinityFunctionRemoveNode(void* target, long ptr, long memPtr)
+        {
+            SafeCall(() =>
+            {
+                using (var stream = IgniteManager.Memory.Get(memPtr).GetStream())
+                {
+                    var nodeId = _ignite.Marshaller.Unmarshal<Guid>(stream);
+
+                    _handleRegistry.Get<IAffinityFunction>(ptr, true).RemoveNode(nodeId);
+                }
+            });
+        }
+
+        private void AffinityFunctionDestroy(void* target, long ptr)
+        {
+            SafeCall(() =>
+            {
+                _handleRegistry.Release(ptr);
+            });
+        }
+
+        #endregion
+
         #region HELPERS
 
         [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]