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.Date;
import org.apache.helix.HelixConstants.ChangeType;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.NotificationContext;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.participant.CustomCodeCallbackHandler;
import org.apache.helix.participant.HelixCustomCodeRunner;
import org.apache.helix.tools.ClusterStateVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;

public class TestHelixCustomCodeRunner extends ZkTestBase {
  private static Logger LOG = LoggerFactory.getLogger(TestHelixCustomCodeRunner.class);

  private final String _clusterName = "CLUSTER_" + getShortClassName();
  private final MockCallback _callback = new MockCallback();

  class MockCallback implements CustomCodeCallbackHandler {
    boolean _isCallbackInvoked;

    @Override
    public void onCallback(NotificationContext context) {
      _isCallbackInvoked = true;
      // System.out.println(type + ": TestCallback invoked on " + manager.getInstanceName());
    }

  }

  private void registerCustomCodeRunner(HelixManager manager) {
    try {
      // delay the start of the 1st participant
      // so there will be a leadership transfer from localhost_12919 to 12918
      if (manager.getInstanceName().equals("localhost_12918")) {
        Thread.sleep(2000);
      }

      HelixCustomCodeRunner customCodeRunner = new HelixCustomCodeRunner(manager, ZK_ADDR);
      customCodeRunner.invoke(_callback).on(ChangeType.LIVE_INSTANCE)
          .usingLeaderStandbyModel("TestParticLeader").start();
    } catch (Exception e) {
      LOG.error("Exception do pre-connect job", e);
    }
  }

  @Test
  public void testCustomCodeRunner() throws Exception {
    System.out.println("START " + _clusterName + " at " + new Date(System.currentTimeMillis()));

    int nodeNb = 5;
    int startPort = 12918;
    TestHelper.setupCluster(_clusterName, ZK_ADDR, startPort, "localhost", // participant name
                                                                           // prefix
        "TestDB", // resource name prefix
        1, // resourceNb
        5, // partitionNb
        nodeNb, // nodesNb
        nodeNb, // replica
        "MasterSlave", true);

    ClusterControllerManager controller =
        new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
    controller.syncStart();

    MockParticipantManager[] participants = new MockParticipantManager[5];
    for (int i = 0; i < nodeNb; i++) {
      String instanceName = "localhost_" + (startPort + i);

      participants[i] = new MockParticipantManager(ZK_ADDR, _clusterName, instanceName);

      registerCustomCodeRunner(participants[i]);
      participants[i].syncStart();
    }
    boolean result = ClusterStateVerifier.verifyByPolling(
        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName));
    Assert.assertTrue(result);

    Thread.sleep(1000); // wait for the INIT type callback to finish
    Assert.assertTrue(_callback._isCallbackInvoked);
    _callback._isCallbackInvoked = false;

    // add a new live instance
    HelixDataAccessor accessor =
        new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<>(_gZkClient));
    Builder keyBuilder = accessor.keyBuilder();

    LiveInstance newLiveIns = new LiveInstance("newLiveInstance");
    newLiveIns.setHelixVersion("0.6.0");
    newLiveIns.setSessionId("randomSessionId");
    accessor.setProperty(keyBuilder.liveInstance("newLiveInstance"), newLiveIns);

    Thread.sleep(1000); // wait for the CALLBACK type callback to finish
    Assert.assertTrue(_callback._isCallbackInvoked);

    // clean up
    controller.syncStop();
    for (int i = 0; i < nodeNb; i++) {
      participants[i].syncStop();
    }
    accessor.removeProperty(keyBuilder.liveInstance("newLiveInstance"));
    TestHelper.dropCluster(_clusterName, _gZkClient);

    System.out.println("END " + _clusterName + " at " + new Date(System.currentTimeMillis()));
  }
}

@@ -864,16 +864,17 @@
 l.Date;%0A
+%0A
 import o
@@ -920,51 +920,8 @@
 pe;%0A
-import org.apache.helix.HelixDataAccessor;%0A
 impo
@@ -1003,53 +1003,8 @@
 xt;%0A
-import org.apache.helix.PropertyKey.Builder;%0A
 impo
@@ -1140,32 +1140,32 @@
 trollerManager;%0A
+
 import org.apach
@@ -1220,163 +1220,8 @@
 er;%0A
-import org.apache.helix.manager.zk.ZKHelixDataAccessor;%0Aimport org.apache.helix.manager.zk.ZkBaseDataAccessor;%0Aimport org.apache.helix.model.LiveInstance;%0A
 impo
@@ -4163,399 +4163,202 @@
 ance
-%0A    HelixDataAccessor accessor =%0A        new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor%3C%3E(_gZkClient));%0A    Builder keyBuilder = accessor.keyBuilder();%0A%0A    LiveInstance newLiveIns = new LiveInstance(%22newLiveInstance%22);%0A    newLiveIns.setHelixVersion(%220.6.0%22);%0A    newLiveIns.setSessionId(%22randomSessionId%22);%0A    accessor.setProperty(keyBuilder.liveInstance(%22newLiveInstance%22)
+ and its instance config.%0A    // instance name: localhost_1000%0A    int%5B%5D newLiveInstance = new int%5B%5D%7B1000%7D;%0A    setupInstances(_clusterName, newLiveInstance);%0A    setupLiveInstances(_clusterName
 , ne
@@ -4365,16 +4365,21 @@
 wLiveIns
+tance
 );%0A%0A    
@@ -4631,96 +4631,53 @@
     
-accessor.removeProperty(keyBuilder.liveInstance(%22newLiveInstance%22));%0A    TestHelper.drop
+deleteLiveInstances(_clusterName);%0A    delete
 Clus
@@ -4696,20 +4696,8 @@
 Name
-, _gZkClient
 );%0A%0A

Fix NullPointerException for testCustomCodeRunner. (#581)