package org.apache.helix.integration;

/*
 * 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.
 */

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.helix.TestHelper;
import org.apache.helix.ZNRecord;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.integration.common.ZkIntegrationTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.apache.helix.tools.ClusterStateVerifier.MasterNbInExtViewVerifier;
import org.apache.zookeeper.data.Stat;
import org.testng.Assert;
import org.testng.annotations.Test;

public class TestExternalViewUpdates extends ZkIntegrationTestBase {
  @Test
  public void testExternalViewUpdates() throws Exception {
    System.out.println("START testExternalViewUpdates at " + new Date(System.currentTimeMillis()));

    String clusterName = getShortClassName();
    MockParticipantManager[] participants = new MockParticipantManager[5];
    int resourceNb = 10;
    TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
        "localhost", // participant name prefix
        "TestDB", // resource name prefix
        resourceNb, // resources
        1, // partitions per resource
        5, // number of nodes
        1, // replicas
        "MasterSlave", true); // do rebalance

    // start participants
    for (int i = 0; i < 5; i++) {
      String instanceName = "localhost_" + (12918 + i);

      participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
      participants[i].syncStart();
    }

    // start controller after participants to trigger rebalance immediate after the controller is ready
    ClusterControllerManager controller =
        new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
    controller.syncStart();

    boolean result =
        ClusterStateVerifier
            .verifyByZkCallback(new MasterNbInExtViewVerifier(ZK_ADDR, clusterName));
    Assert.assertTrue(result);

    result =
        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
            clusterName));
    Assert.assertTrue(result);

    // need to verify that each ExternalView's version number is 2
    Builder keyBuilder = new Builder(clusterName);
    ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
    String parentPath = keyBuilder.externalViews().getPath();
    List<String> childNames = accessor.getChildNames(parentPath, 0);

    List<String> paths = new ArrayList<String>();
    for (String name : childNames) {
      paths.add(parentPath + "/" + name);
    }

    // Stat[] stats = accessor.getStats(paths);
    for (String path : paths) {
      Stat stat = accessor.getStat(path, 0);
      Assert.assertTrue(stat.getVersion() <= 2, "ExternalView should be updated at most 2 times");
    }

    // clean up
    controller.syncStop();
    for (int i = 0; i < 5; i++) {
      participants[i].syncStop();
    }
    System.out.println("END testExternalViewUpdates at " + new Date(System.currentTimeMillis()));
  }
}

@@ -915,16 +915,102 @@
 l.List;%0A
+import org.apache.helix.BaseDataAccessor;%0Aimport org.apache.helix.PropertyKey.Builder;
 %0Aimport 
@@ -1076,53 +1076,8 @@
 rd;%0A
-import org.apache.helix.PropertyKey.Builder;%0A
 impo
@@ -1923,24 +1923,148 @@
 lassName();%0A
+    int numResource = 10;%0A    int numPartition = 1;%0A    int numReplica = 1;%0A    int numNode = 5;%0A    int startPort = 12918;%0A
     MockPart
@@ -2126,35 +2126,16 @@
 ger%5B
-5%5D;%0A    int resourceNb = 10
+numNode%5D
 ;%0A  
@@ -2182,21 +2182,25 @@
 K_ADDR, 
-12918
+startPort
 , // par
@@ -2315,18 +2315,19 @@
     
-r
+numR
 esource
-Nb
 , //
@@ -2341,25 +2341,36 @@
 ces%0A        
-1
+numPartition
 , // partiti
@@ -2394,17 +2394,23 @@
         
-5
+numNode
 , // num
@@ -2430,17 +2430,26 @@
         
-1
+numReplica
 , // rep
@@ -2543,33 +2543,39 @@
 (int i = 0; i %3C 
-5
+numNode
 ; i++) %7B%0A      S
@@ -2611,21 +2611,25 @@
 st_%22 + (
-12918
+startPort
  + i);%0A%0A
@@ -2831,16 +2831,25 @@
 mmediate
+ly%0A    //
  after t
@@ -3359,67 +3359,190 @@
  // 
-need to verify that each ExternalView's version number is 2
+10 Resources, 1 partition, 1 replica, so there are at most 10 ZK writes for EV (assume)%0A    // worst case that no event is batched in controller. Therefore, EV version should be %3C 10
 %0A   
@@ -3593,18 +3593,16 @@
 e);%0A    
-Zk
 BaseData
@@ -3953,50 +3953,59 @@
     
-// Stat%5B%5D stats = accessor.getStats(paths)
+int maxEV = numResource * numPartition * numReplica
 ;%0A  
@@ -4128,10 +4128,24 @@
  %3C= 
-2,
+maxEV,%0A         
  %22Ex
@@ -4181,17 +4181,29 @@
 at most 
-2
+%22 + maxEV + %22
  times%22)

fix breaking TestExternalViewUpdates