/*
 * Licensed to ElasticSearch and Shay Banon under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. ElasticSearch 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.elasticsearch.test.integration.cluster.allocation;

import gnu.trove.map.hash.TObjectIntHashMap;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.integration.AbstractNodesTests;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

/**
 */
@Test
public class AwarenessAllocationTests extends AbstractNodesTests {

    private final ESLogger logger = Loggers.getLogger(AwarenessAllocationTests.class);

    @AfterMethod
    public void cleanAndCloseNodes() throws Exception {
        closeAllNodes();
    }

    @Test
    public void testSimpleAwareness() throws Exception {
        Settings commonSettings = ImmutableSettings.settingsBuilder()
                .put("cluster.routing.schedule", "10ms")
                .put("cluster.routing.allocation.awareness.attributes", "rack_id")
                .build();


        logger.info("--> starting 2 nodes on the same rack");
        startNode("node1", ImmutableSettings.settingsBuilder().put(commonSettings).put("node.rack_id", "rack_1"));
        startNode("node2", ImmutableSettings.settingsBuilder().put(commonSettings).put("node.rack_id", "rack_1"));

        client("node1").admin().indices().prepareCreate("test1").execute().actionGet();
        client("node1").admin().indices().prepareCreate("test2").execute().actionGet();

        ClusterHealthResponse health = client("node1").admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet();
        assertThat(health.isTimedOut(), equalTo(false));

        logger.info("--> starting 1 node on a different rack");
        startNode("node3", ImmutableSettings.settingsBuilder().put(commonSettings).put("node.rack_id", "rack_2"));

        Thread.sleep(500);

        health = client("node1").admin().cluster().prepareHealth().setWaitForGreenStatus().setWaitForNodes("3").setWaitForRelocatingShards(0).execute().actionGet();
        assertThat(health.isTimedOut(), equalTo(false));

        ClusterState clusterState = client("node1").admin().cluster().prepareState().execute().actionGet().getState();
        //System.out.println(clusterState.routingTable().prettyPrint());
        // verify that we have 10 shards on node3
        TObjectIntHashMap<String> counts = new TObjectIntHashMap<String>();
        for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
            for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
                for (ShardRouting shardRouting : indexShardRoutingTable) {
                    counts.adjustOrPutValue(clusterState.nodes().get(shardRouting.currentNodeId()).name(), 1, 1);
                }
            }
        }
        assertThat(counts.get("node3"), equalTo(10));
    }
}

@@ -3083,24 +3083,200 @@
 rack_2%22));%0A%0A
+        long start = System.currentTimeMillis();%0A        TObjectIntHashMap%3CString%3E counts;%0A        // On slow machines the initial relocation might be delayed%0A        do %7B%0A    
         Thre
@@ -3288,15 +3288,76 @@
 eep(
-5
+1
 00);%0A
-%0A
+            logger.info(%22--%3E waiting for no relocation%22);%0A    
     
@@ -3517,32 +3517,36 @@
 nGet();%0A        
+    
 assertThat(healt
@@ -3571,32 +3571,91 @@
 ualTo(false));%0A%0A
+            logger.info(%22--%3E checking current state%22);%0A    
         ClusterS
@@ -3765,16 +3765,20 @@
         
+ 
+   
 //System
@@ -3842,16 +3842,20 @@
         
+    
 // verif
@@ -3900,33 +3900,11 @@
     
-TObjectIntHashMap%3CString%3E
+   
  cou
@@ -3938,24 +3938,28 @@
 %3CString%3E();%0A
+    
         for 
@@ -4032,32 +4032,36 @@
 ) %7B%0A            
+   
+ 
 for (IndexShardR
@@ -4130,24 +4130,28 @@
             
+    
 for (ShardRo
@@ -4213,24 +4213,28 @@
             
+   
+ 
 counts.adjus
@@ -4323,34 +4323,40 @@
                 
-%7D%0A
+    %7D%0A  
             %7D%0A  
@@ -4343,32 +4343,34 @@
 %7D%0A              
+  
 %7D%0A        %7D%0A    
@@ -4355,33 +4355,130 @@
       %7D%0A        
-%7D
+    %7D%0A        %7D while (counts.get(%22node3%22) != 10 && (System.currentTimeMillis() - start) %3C 10000);
 %0A        assertT

Improve stability of testSimpleAwareness test