index
int64 0
0
| repo_id
stringlengths 9
205
| file_path
stringlengths 31
246
| content
stringlengths 1
12.2M
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestCarryOverBadCurState.java
|
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.PropertyPathBuilder;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.apache.helix.tools.ClusterStateVerifier.MasterNbInExtViewVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestCarryOverBadCurState extends ZkTestBase {
@Test
public void testCarryOverBadCurState() throws Exception {
System.out.println("START testCarryOverBadCurState at " + new Date(System.currentTimeMillis()));
String clusterName = getShortClassName();
MockParticipantManager[] participants = new MockParticipantManager[5];
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
10, // partitions per resource
5, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
// add a bad current state
ZNRecord badCurState = new ZNRecord("TestDB0");
String path = PropertyPathBuilder.instanceCurrentState(clusterName, "localhost_12918", "session_0", "TestDB0");
_gZkClient.createPersistent(path, true);
_gZkClient.writeData(path, badCurState);
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
// 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();
}
boolean result =
ClusterStateVerifier
.verifyByZkCallback(new MasterNbInExtViewVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// clean up
controller.syncStop();
for (int i = 0; i < 5; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END testCarryOverBadCurState at " + new Date(System.currentTimeMillis()));
}
}
| 9,500 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestClusterStartsup.java
|
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.HelixException;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.PropertyPathBuilder;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestClusterStartsup extends ZkStandAloneCMTestBase {
void setupCluster() throws HelixException {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, 20, STATE_MODEL);
for (int i = 0; i < NODE_NR; i++) {
String storageNodeName = "localhost_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
}
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, 3);
}
@Override
@BeforeClass()
public void beforeClass() throws Exception {
}
@Test()
public void testParticipantStartUp() throws Exception {
setupCluster();
String controllerMsgPath = PropertyPathBuilder.controllerMessage(CLUSTER_NAME);
_gZkClient.deleteRecursively(controllerMsgPath);
HelixManager manager = null;
try {
manager =
HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "localhost_" + (START_PORT + 1),
InstanceType.PARTICIPANT, ZK_ADDR);
manager.connect();
Assert.fail("Should fail on connect() since cluster structure is not set up");
} catch (HelixException e) {
// OK
}
if (manager != null) {
AssertJUnit.assertFalse(manager.isConnected());
}
try {
manager =
HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "localhost_" + (START_PORT + 3),
InstanceType.PARTICIPANT, ZK_ADDR);
manager.connect();
Assert.fail("Should fail on connect() since cluster structure is not set up");
} catch (HelixException e) {
// OK
}
if (manager != null) {
AssertJUnit.assertFalse(manager.isConnected());
}
setupCluster();
String stateModelPath = PropertyPathBuilder.stateModelDef(CLUSTER_NAME);
_gZkClient.deleteRecursively(stateModelPath);
try {
manager =
HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "localhost_" + (START_PORT + 1),
InstanceType.PARTICIPANT, ZK_ADDR);
manager.connect();
Assert.fail("Should fail on connect() since cluster structure is not set up");
} catch (HelixException e) {
// OK
}
if (manager != null) {
AssertJUnit.assertFalse(manager.isConnected());
}
setupCluster();
String instanceStatusUpdatePath =
PropertyPathBuilder.instanceStatusUpdate(CLUSTER_NAME, "localhost_" + (START_PORT + 1));
_gZkClient.deleteRecursively(instanceStatusUpdatePath);
try {
manager =
HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "localhost_" + (START_PORT + 1),
InstanceType.PARTICIPANT, ZK_ADDR);
manager.connect();
Assert.fail("Should fail on connect() since cluster structure is not set up");
} catch (HelixException e) {
// OK
}
if (manager != null) {
AssertJUnit.assertFalse(manager.isConnected());
}
if (manager != null) {
manager.disconnect();
}
}
}
| 9,501 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestFailOverPerf1kp.java
|
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.ExternalCommand;
import org.apache.helix.ScriptTestHelper;
import org.apache.helix.TestHelper;
import org.testng.Assert;
public class TestFailOverPerf1kp {
// TODO: renable this test. disable it because the script is not running properly on apache
// jenkins
// @Test
public void testFailOverPerf1kp() throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String testName = className + "_" + methodName;
System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis()));
ExternalCommand cmd = ScriptTestHelper.runCommandLineTest("helix_random_kill_local_startzk.sh");
String output = cmd.getStringOutput("UTF8");
int i = getStateTransitionLatency(0, output);
int j = output.indexOf("ms", i);
long latency = Long.parseLong(output.substring(i, j));
System.out.println("startup latency: " + latency);
i = getStateTransitionLatency(i, output);
j = output.indexOf("ms", i);
latency = Long.parseLong(output.substring(i, j));
System.out.println("failover latency: " + latency);
Assert.assertTrue(latency < 800, "failover latency for 1k partition test should < 800ms");
System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis()));
}
int getStateTransitionLatency(int start, String output) {
final String pattern = "state transition latency: ";
int i = output.indexOf(pattern, start) + pattern.length();
// String latencyStr = output.substring(i, j);
// System.out.println(latencyStr);
return i;
}
}
| 9,502 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestBatchMessageHandling.java
|
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.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixException;
import org.apache.helix.NotificationContext;
import org.apache.helix.TestHelper;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.mock.participant.MockMSStateModel;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.Message;
import org.apache.helix.model.builder.FullAutoModeISBuilder;
import org.apache.helix.participant.statemachine.StateModel;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestBatchMessageHandling extends ZkStandAloneCMTestBase {
@Test
public void testSubMessageFailed() throws Exception {
TestOnlineOfflineStateModel._numOfSuccessBeforeFailure.set(6);
// Let one instance handle all the batch messages.
_participants[0].getStateMachineEngine().registerStateModelFactory("OnlineOffline",
new TestOnlineOfflineStateModelFactory(), "TestFactory");
for (int i = 1; i < _participants.length; i++) {
_participants[i].syncStop();
}
HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
// Check that the Participants really stopped
boolean result = TestHelper.verify(() -> {
List<String> liveInstances =
dataAccessor.getChildNames(dataAccessor.keyBuilder().liveInstances());
for (int i = 1; i < _participants.length; i++) {
if (_participants[i].isConnected()
|| liveInstances.contains(_participants[i].getInstanceName())) {
return false;
}
}
return true;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
// Add 1 db with batch message enabled. Each db has 10 partitions.
// So it will have 1 batch message and 10 sub messages.
String dbName = "TestDBSubMessageFail";
IdealState idealState = new FullAutoModeISBuilder(dbName).setStateModel("OnlineOffline")
.setStateModelFactoryName("TestFactory").setNumPartitions(10).setNumReplica(1).build();
idealState.setBatchMessageMode(true);
_gSetupTool.getClusterManagementTool().addResource(CLUSTER_NAME, dbName, idealState);
// Check that IdealState has really been added
result = TestHelper.verify(
() -> dataAccessor.getPropertyStat(dataAccessor.keyBuilder().idealStates(dbName)) != null,
TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
for (int i = 0; i < 5; i++) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
if (!idealState.equals(is)) {
Thread.sleep(1000L);
}
}
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, 1);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
Thread.sleep(2000L);
result = TestHelper.verify(() -> {
int numOfOnlines = 0;
int numOfErrors = 0;
ExternalView externalView =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, dbName);
for (String partition : externalView.getPartitionSet()) {
if (externalView.getStateMap(partition).values().contains("ONLINE")) {
numOfOnlines++;
}
if (externalView.getStateMap(partition).values().contains("ERROR")) {
numOfErrors++;
}
}
if (numOfErrors == 4 && numOfOnlines == 6) {
return true;
}
return false;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
}
public static class TestOnlineOfflineStateModelFactory
extends StateModelFactory<TestOnlineOfflineStateModel> {
@Override
public TestOnlineOfflineStateModel createNewStateModel(String resourceName,
String stateUnitKey) {
return new TestOnlineOfflineStateModel();
}
}
public static class TestOnlineOfflineStateModel extends StateModel {
private static Logger LOG = LoggerFactory.getLogger(MockMSStateModel.class);
static AtomicInteger _numOfSuccessBeforeFailure = new AtomicInteger();
public void onBecomeOnlineFromOffline(Message message, NotificationContext context) {
if (_numOfSuccessBeforeFailure.getAndDecrement() > 0) {
LOG.info("State transition from Offline to Online");
return;
}
throw new HelixException("Number of Success reached");
}
public void onBecomeOfflineFromOnline(Message message, NotificationContext context) {
LOG.info("State transition from Online to Offline");
}
public void onBecomeDroppedFromOffline(Message message, NotificationContext context) {
LOG.info("State transition from Offline to Dropped");
}
}
}
| 9,503 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestSwapInstance.java
|
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 org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.model.IdealState;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestSwapInstance extends ZkStandAloneCMTestBase {
@Test
public void testSwapInstance() throws Exception {
HelixManager manager = _controller;
HelixDataAccessor dataAccessor = manager.getHelixDataAccessor();
// Create semi auto resource
_gSetupTool.addResourceToCluster(CLUSTER_NAME, "db-semi", 64, STATE_MODEL,
IdealState.RebalanceMode.SEMI_AUTO.name());
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "db-semi", _replica);
// Create customized resource
_gSetupTool.addResourceToCluster(CLUSTER_NAME, "db-customized", 64, STATE_MODEL,
IdealState.RebalanceMode.CUSTOMIZED.name());
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "db-customized", _replica);
// Create full-auto resource
_gSetupTool.addResourceToCluster(CLUSTER_NAME, "db-fa", 64, STATE_MODEL,
IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName());
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "db-fa", _replica);
// Wait for cluster converge
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// Get ideal states before swap
IdealState semiIS = dataAccessor.getProperty(dataAccessor.keyBuilder().idealStates("db-semi"));
IdealState customizedIS =
dataAccessor.getProperty(dataAccessor.keyBuilder().idealStates("db-customized"));
IdealState faIs =
dataAccessor.getProperty(dataAccessor.keyBuilder().idealStates("db-fa"));
String oldInstanceName = String.format("%s_%s", PARTICIPANT_PREFIX, START_PORT);
String newInstanceName = String.format("%s_%s", PARTICIPANT_PREFIX, 66666);
try {
_gSetupTool.swapInstance(CLUSTER_NAME, oldInstanceName, newInstanceName);
Assert.fail("Cannot swap as new instance is not added to cluster yet");
} catch (Exception e) {
// OK - new instance not added to cluster yet
}
// Add new instance to cluster
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, newInstanceName);
try {
_gSetupTool.swapInstance(CLUSTER_NAME, oldInstanceName, newInstanceName);
Assert.fail("Cannot swap as old instance is still alive");
} catch (Exception e) {
// OK - old instance still alive
}
// Stop old instance
_participants[0].syncStop();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
try {
_gSetupTool.swapInstance(CLUSTER_NAME, oldInstanceName, newInstanceName);
Assert.fail("Cannot swap as old instance is still enabled");
} catch (Exception e) {
// OK - old instance still alive
}
// disable old instance
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, oldInstanceName, false);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// We can swap now
_gSetupTool.swapInstance(CLUSTER_NAME, oldInstanceName, newInstanceName);
// verify cluster
Assert.assertTrue(_clusterVerifier.verifyByPolling());
verifySwapInstance(dataAccessor, "db-semi", semiIS, oldInstanceName, newInstanceName, false);
verifySwapInstance(dataAccessor, "db-customized", customizedIS, oldInstanceName, newInstanceName,
false);
verifySwapInstance(dataAccessor, "db-fa", faIs, oldInstanceName, newInstanceName, true);
// Verify idempotency
_gSetupTool.swapInstance(CLUSTER_NAME, oldInstanceName, newInstanceName);
verifySwapInstance(dataAccessor, "db-semi", semiIS, oldInstanceName, newInstanceName, false);
verifySwapInstance(dataAccessor, "db-customized", customizedIS, oldInstanceName, newInstanceName,
false);
verifySwapInstance(dataAccessor, "db-fa", faIs, oldInstanceName, newInstanceName, true);
}
private void verifySwapInstance(HelixDataAccessor dataAccessor, String resourceName,
IdealState oldIs, String oldInstance, String newInstance, boolean isFullAuto) {
IdealState newIs = dataAccessor.getProperty(dataAccessor.keyBuilder().idealStates(resourceName));
if (isFullAuto) {
// Full auto resource should not contain new instance as it's not live yet
for (String key : newIs.getRecord().getMapFields().keySet()) {
Assert.assertFalse(newIs.getRecord().getMapField(key).keySet().contains(newInstance));
}
for (String key : newIs.getRecord().getListFields().keySet()) {
Assert.assertFalse(newIs.getRecord().getListField(key).contains(newInstance));
}
} else {
verifyIdealStateWithSwappedInstance(oldIs, newIs, oldInstance, newInstance);
}
}
private void verifyIdealStateWithSwappedInstance(IdealState oldIs, IdealState newIs,
String oldInstance, String newInstance) {
// Verify map fields
for (String key : oldIs.getRecord().getMapFields().keySet()) {
for (String host : oldIs.getRecord().getMapField(key).keySet()) {
if (host.equals(oldInstance)) {
Assert.assertTrue(oldIs.getRecord().getMapField(key).get(oldInstance)
.equals(newIs.getRecord().getMapField(key).get(newInstance)));
} else {
Assert.assertTrue(oldIs.getRecord().getMapField(key).get(host)
.equals(newIs.getRecord().getMapField(key).get(host)));
}
}
}
// verify list fields
for (String key : oldIs.getRecord().getListFields().keySet()) {
Assert.assertEquals(oldIs.getRecord().getListField(key).size(), newIs.getRecord()
.getListField(key).size());
for (int i = 0; i < oldIs.getRecord().getListField(key).size(); i++) {
String host = oldIs.getRecord().getListField(key).get(i);
String newHost = newIs.getRecord().getListField(key).get(i);
if (host.equals(oldInstance)) {
Assert.assertTrue(newHost.equals(newInstance));
} else {
Assert.assertTrue(host.equals(newHost));
}
}
}
}
}
| 9,504 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestMessagePartitionStateMismatch.java
|
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.Map;
import java.util.Random;
import java.util.UUID;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.Message;
import org.apache.helix.model.Message.MessageState;
import org.apache.helix.model.Message.MessageType;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestMessagePartitionStateMismatch extends ZkStandAloneCMTestBase {
@Test
public void testStateMismatch() throws InterruptedException {
// String controllerName = CONTROLLER_PREFIX + "_0";
HelixManager manager = _controller; // _startCMResultMap.get(controllerName)._manager;
HelixDataAccessor accessor = manager.getHelixDataAccessor();
Builder kb = accessor.keyBuilder();
ExternalView ev = accessor.getProperty(kb.externalView(TEST_DB));
Map<String, LiveInstance> liveinstanceMap =
accessor.getChildValuesMap(accessor.keyBuilder().liveInstances(), true);
for (String instanceName : liveinstanceMap.keySet()) {
String sessionid = liveinstanceMap.get(instanceName).getEphemeralOwner();
for (String partition : ev.getPartitionSet()) {
if (ev.getStateMap(partition).containsKey(instanceName)) {
String uuid = UUID.randomUUID().toString();
Message message = new Message(MessageType.STATE_TRANSITION, uuid);
boolean rand = new Random().nextInt(10) > 5;
if (ev.getStateMap(partition).get(instanceName).equals("MASTER")) {
message.setSrcName(manager.getInstanceName());
message.setTgtName(instanceName);
message.setMsgState(MessageState.NEW);
message.setPartitionName(partition);
message.setResourceName(TEST_DB);
message.setFromState(rand ? "SLAVE" : "OFFLINE");
message.setToState(rand ? "MASTER" : "SLAVE");
message.setTgtSessionId(sessionid);
message.setSrcSessionId(manager.getSessionId());
message.setStateModelDef("MasterSlave");
message.setStateModelFactoryName("DEFAULT");
} else if (ev.getStateMap(partition).get(instanceName).equals("SLAVE")) {
message.setSrcName(manager.getInstanceName());
message.setTgtName(instanceName);
message.setMsgState(MessageState.NEW);
message.setPartitionName(partition);
message.setResourceName(TEST_DB);
message.setFromState(rand ? "MASTER" : "OFFLINE");
message.setToState(rand ? "SLAVE" : "SLAVE");
message.setTgtSessionId(sessionid);
message.setSrcSessionId(manager.getSessionId());
message.setStateModelDef("MasterSlave");
message.setStateModelFactoryName("DEFAULT");
}
accessor.setProperty(accessor.keyBuilder().message(instanceName, message.getMsgId()),
message);
}
}
}
Thread.sleep(3000);
ExternalView ev2 = accessor.getProperty(kb.externalView(TEST_DB));
Assert.assertTrue(ev.equals(ev2));
}
}
| 9,505 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestPersistAssignmentStage.java
|
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.List;
import java.util.Map;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
import org.apache.helix.controller.stages.AttributeName;
import org.apache.helix.controller.stages.BestPossibleStateOutput;
import org.apache.helix.controller.stages.ClusterEvent;
import org.apache.helix.controller.stages.ClusterEventType;
import org.apache.helix.controller.stages.PersistAssignmentStage;
import org.apache.helix.controller.stages.ReadClusterDataStage;
import org.apache.helix.controller.stages.ResourceComputationStage;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.Partition;
import org.apache.helix.tools.DefaultIdealStateCalculator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestPersistAssignmentStage extends ZkStandAloneCMTestBase {
ClusterEvent event = new ClusterEvent(ClusterEventType.Unknown);
/**
* Case where we have one resource in IdealState
* @throws Exception
*/
@Test
public void testSimple() throws Exception {
int nodes = 2;
List<String> instances = new ArrayList<>();
for (int i = 0; i < nodes; i++) {
instances.add("localhost_" + i);
}
int partitions = 10;
int replicas = 1;
String resourceName = "testResource";
event.addAttribute(AttributeName.ControllerDataProvider.name(),
new ResourceControllerDataProvider());
ZNRecord record =
DefaultIdealStateCalculator.calculateIdealState(instances, partitions, replicas, resourceName, "ONLINE",
"OFFLINE");
IdealState idealState = new IdealState(record);
idealState.setStateModelDefRef("OnlineOffline");
// Read and load current state into event
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
accessor.setProperty(keyBuilder.idealStates(resourceName), idealState);
runStage(_manager, event, new ReadClusterDataStage());
runStage(_manager, event, new ResourceComputationStage());
// Ensure persist best possible assignment is true
ClusterConfig clusterConfig = new ClusterConfig(CLUSTER_NAME);
clusterConfig.setPersistBestPossibleAssignment(true);
ResourceControllerDataProvider cache =
event.getAttribute(AttributeName.ControllerDataProvider.name());
cache.setClusterConfig(clusterConfig);
// 1. Change best possible state (simulate a new rebalancer run)
BestPossibleStateOutput bestPossibleStateOutput = new BestPossibleStateOutput();
for (String partition : idealState.getPartitionSet()) {
bestPossibleStateOutput.setState(resourceName, new Partition(partition), "localhost_3", "OFFLINE");
}
// 2. At the same time, set DelayRebalanceEnabled = true (simulate a Admin operation at the same time)
idealState.setDelayRebalanceEnabled(true);
accessor.setProperty(keyBuilder.idealStates(resourceName), idealState);
// Persist new assignment
PersistAssignmentStage stage = new PersistAssignmentStage();
event.addAttribute(AttributeName.BEST_POSSIBLE_STATE.name(), bestPossibleStateOutput);
runStage(_manager, event, stage);
IdealState newIdealState = accessor.getProperty(keyBuilder.idealStates(resourceName));
// 1. New assignment should be set
Assert.assertEquals(newIdealState.getPartitionSet().size(), idealState.getPartitionSet().size());
for (String partition : idealState.getPartitionSet()) {
Map<String, String> assignment = newIdealState.getInstanceStateMap(partition);
Assert.assertNotNull(assignment);
Assert.assertEquals(assignment.size(),1);
Assert.assertTrue(assignment.containsKey("localhost_3") && assignment.get("localhost_3").equals("OFFLINE"));
}
// 2. Admin config should be set
Assert.assertTrue(newIdealState.isDelayRebalanceEnabled());
}
}
| 9,506 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestBatchEnableInstances.java
|
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.Arrays;
import java.util.Collections;
import java.util.Map;
import org.apache.helix.HelixException;
import org.apache.helix.integration.task.TaskTestBase;
import org.apache.helix.integration.task.WorkflowGenerator;
import org.apache.helix.model.ExternalView;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestBatchEnableInstances extends TaskTestBase {
@BeforeClass
public void beforeClass() throws Exception {
_numDbs = 1;
_numReplicas = 3;
_numNodes = 5;
_numPartitions = 4;
super.beforeClass();
}
@Test(expectedExceptions = HelixException.class, expectedExceptionsMessageRegExp = "Batch.*is not supported")
public void testBatchModeNotSupported() {
// ensure batch enable/disable is not supported and shouldn't be used yet
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, Collections.emptyList(), true);
}
@Test(enabled = false)
public void testOldEnableDisable() throws InterruptedException {
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
_participants[0].getInstanceName(), false);
Assert.assertTrue(_clusterVerifier.verify());
ExternalView externalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
Assert.assertEquals(externalView.getRecord().getMapFields().size(), _numPartitions);
for (Map<String, String> stateMap : externalView.getRecord().getMapFields().values()) {
Assert.assertTrue(!stateMap.keySet().contains(_participants[0].getInstanceName()));
}
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
_participants[0].getInstanceName(), true);
}
@Test(enabled = false)
public void testBatchEnableDisable() throws InterruptedException {
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
Arrays.asList(_participants[0].getInstanceName(), _participants[1].getInstanceName()),
false);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
ExternalView externalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
Assert.assertEquals(externalView.getRecord().getMapFields().size(), _numPartitions);
for (Map<String, String> stateMap : externalView.getRecord().getMapFields().values()) {
Assert.assertTrue(!stateMap.keySet().contains(_participants[0].getInstanceName()));
Assert.assertTrue(!stateMap.keySet().contains(_participants[1].getInstanceName()));
}
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
Arrays.asList(_participants[0].getInstanceName(), _participants[1].getInstanceName()),
true);
}
@Test(enabled = false)
public void testOldDisableBatchEnable() throws InterruptedException {
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
_participants[0].getInstanceName(), false);
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
Arrays.asList(_participants[0].getInstanceName(), _participants[1].getInstanceName()),
true);
Thread.sleep(2000);
ExternalView externalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
Assert.assertEquals(externalView.getRecord().getMapFields().size(), _numPartitions);
int numOfFirstHost = 0;
for (Map<String, String> stateMap : externalView.getRecord().getMapFields().values()) {
if (stateMap.keySet().contains(_participants[0].getInstanceName())) {
numOfFirstHost++;
}
}
Assert.assertTrue(numOfFirstHost > 0);
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
_participants[0].getInstanceName(), true);
}
@Test(enabled = false)
public void testBatchDisableOldEnable() throws InterruptedException {
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
Arrays.asList(_participants[0].getInstanceName(), _participants[1].getInstanceName()),
false);
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
_participants[0].getInstanceName(), true);
Thread.sleep(2000);
ExternalView externalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
Assert.assertEquals(externalView.getRecord().getMapFields().size(), _numPartitions);
int numOfFirstHost = 0;
for (Map<String, String> stateMap : externalView.getRecord().getMapFields().values()) {
if (stateMap.keySet().contains(_participants[0].getInstanceName())) {
numOfFirstHost++;
}
Assert.assertTrue(!stateMap.keySet().contains(_participants[1].getInstanceName()));
}
Assert.assertTrue(numOfFirstHost > 0);
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
Arrays.asList(_participants[0].getInstanceName(), _participants[1].getInstanceName()),
true);
}
}
| 9,507 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestResourceGroupEndtoEnd.java
|
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.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.NotificationContext;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.ZkTestManager;
import org.apache.helix.manager.zk.CallbackHandler;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZKHelixManager;
import org.apache.helix.zookeeper.api.client.HelixZkClient;
import org.apache.helix.mock.participant.DummyProcess;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.Message;
import org.apache.helix.participant.StateMachineEngine;
import org.apache.helix.participant.statemachine.StateModel;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.apache.helix.spectator.RoutingTableProvider;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.zookeeper.api.client.RealmAwareZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestResourceGroupEndtoEnd extends ZkTestBase {
protected static final int GROUP_NODE_NR = 5;
protected static final int START_PORT = 12918;
protected static final String STATE_MODEL = "OnlineOffline";
protected static final String TEST_DB = "TestDB";
protected static final int PARTITIONS = 20;
protected static final int INSTANCE_GROUP_NR = 4;
protected static final int TOTAL_NODE_NR = GROUP_NODE_NR * INSTANCE_GROUP_NR;
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected TestParticipantManager[] _participants = new TestParticipantManager[TOTAL_NODE_NR];
protected ClusterControllerManager _controller;
protected RoutingTableProvider _routingTableProvider;
private HelixAdmin _admin;
HelixManager _spectator;
int _replica = 3;
@BeforeClass
public void beforeClass() throws Exception {
_admin = new ZKHelixAdmin(_gZkClient);
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
List<String> instanceGroupTags = new ArrayList<String>();
for (int i = 0; i < INSTANCE_GROUP_NR; i++) {
String groupTag = "cluster_" + i;
addInstanceGroup(CLUSTER_NAME, groupTag, GROUP_NODE_NR);
instanceGroupTags.add(groupTag);
}
for (String tag : instanceGroupTags) {
List<String> instances = _admin.getInstancesInClusterWithTag(CLUSTER_NAME, tag);
IdealState idealState = createIdealState(TEST_DB, tag, instances, PARTITIONS, _replica,
IdealState.RebalanceMode.CUSTOMIZED.toString(),
BuiltInStateModelDefinitions.OnlineOffline.name());
_gSetupTool.addResourceToCluster(CLUSTER_NAME, idealState.getResourceName(), idealState);
}
// start dummy participants
int i = 0;
for (String group : instanceGroupTags) {
List<String> instances = _admin.getInstancesInClusterWithTag(CLUSTER_NAME, group);
for (String instance : instances) {
_participants[i] =
new TestParticipantManager(ZK_ADDR, CLUSTER_NAME, TEST_DB, group, instance);
_participants[i].syncStart();
i++;
}
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
boolean result =
ClusterStateVerifier.verifyByZkCallback(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
CLUSTER_NAME));
Assert.assertTrue(result);
// start speculator
_routingTableProvider = new RoutingTableProvider();
_spectator =
HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "spectator", InstanceType.SPECTATOR,
ZK_ADDR);
_spectator.connect();
_spectator.addExternalViewChangeListener(_routingTableProvider);
Thread.sleep(1000);
}
@AfterClass
public void afterClass() {
// stop participants
for (int i = 0; i < TOTAL_NODE_NR; i++) {
_participants[i].syncStop();
}
_controller.syncStop();
_spectator.disconnect();
_routingTableProvider.shutdown();
deleteCluster(CLUSTER_NAME);
}
private void addInstanceGroup(String clusterName, String instanceTag, int numInstance) {
List<String> instances = new ArrayList<String>();
for (int i = 0; i < numInstance; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + instanceTag + "_" + (START_PORT + i);
instances.add(storageNodeName);
_gSetupTool.addInstanceToCluster(clusterName, storageNodeName);
_gSetupTool.addInstanceTag(clusterName, storageNodeName, instanceTag);
}
}
@Test
public void testRoutingTable() throws Exception {
// Verify routing table works
Set<InstanceConfig> allOnlineNodes =
_routingTableProvider.getInstancesForResourceGroup(TEST_DB, "ONLINE");
Assert.assertEquals(allOnlineNodes.size(), TOTAL_NODE_NR);
List<InstanceConfig> onlinePartitions =
_routingTableProvider.getInstancesForResourceGroup(TEST_DB, TEST_DB + "_0", "ONLINE");
Assert.assertEquals(onlinePartitions.size(), INSTANCE_GROUP_NR * _replica);
Set<InstanceConfig> selectedNodes = _routingTableProvider
.getInstancesForResourceGroup(TEST_DB, "ONLINE", Arrays.asList("cluster_2", "cluster_3"));
Assert.assertEquals(selectedNodes.size(), GROUP_NODE_NR * 2);
List<InstanceConfig> selectedPartition = _routingTableProvider
.getInstancesForResourceGroup(TEST_DB, TEST_DB + "_0", "ONLINE",
Arrays.asList("cluster_2", "cluster_3"));
Assert.assertEquals(selectedPartition.size(), _replica * 2);
}
@Test(dependsOnMethods = { "testRoutingTable" })
public void testEnableDisableClusters() throws InterruptedException {
// disable a resource
_gSetupTool.enableResource(CLUSTER_NAME, TEST_DB, "cluster_2", false);
Thread.sleep(2000);
Set<InstanceConfig> selectedNodes = _routingTableProvider
.getInstancesForResourceGroup(TEST_DB, "ONLINE", Arrays.asList("cluster_2", "cluster_3"));
Assert.assertEquals(selectedNodes.size(), GROUP_NODE_NR * 1);
List<InstanceConfig> selectedPartition = _routingTableProvider
.getInstancesForResourceGroup(TEST_DB, TEST_DB + "_0", "ONLINE",
Arrays.asList("cluster_2", "cluster_3"));
Assert.assertEquals(selectedPartition.size(), _replica * 1);
// enable a resource
_gSetupTool.enableResource(CLUSTER_NAME, TEST_DB, "cluster_2", true);
Thread.sleep(2000);
selectedNodes = _routingTableProvider
.getInstancesForResourceGroup(TEST_DB, "ONLINE", Arrays.asList("cluster_2", "cluster_3"));
Assert.assertEquals(selectedNodes.size(), GROUP_NODE_NR * 2);
selectedPartition = _routingTableProvider
.getInstancesForResourceGroup(TEST_DB, TEST_DB + "_0", "ONLINE",
Arrays.asList("cluster_2", "cluster_3"));
Assert.assertEquals(selectedPartition.size(), _replica * 2);
}
public static class MockProcess {
private static final Logger logger = LoggerFactory.getLogger(DummyProcess.class);
// public static final String rootNamespace = "rootNamespace";
private final String _zkConnectString;
private final String _clusterName;
private final String _instanceName;
private final String _resourceName;
private final String _resourceTag;
// private StateMachineEngine genericStateMachineHandler;
private int _transDelayInMs = 0;
private final String _clusterMangerType;
public MockProcess(String zkConnectString, String clusterName, String resourceName,
String instanceName, String resourceTag,
String clusterMangerType, int delay) {
_zkConnectString = zkConnectString;
_clusterName = clusterName;
_resourceName = resourceName;
_resourceTag = resourceTag;
_instanceName = instanceName;
_clusterMangerType = clusterMangerType;
_transDelayInMs = delay > 0 ? delay : 0;
}
static void sleep(long transDelay) {
try {
if (transDelay > 0) {
Thread.sleep(transDelay);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public HelixManager start() throws Exception {
HelixManager manager = null;
// zk cluster manager
if (_clusterMangerType.equalsIgnoreCase("zk")) {
manager =
HelixManagerFactory.getZKHelixManager(_clusterName, _instanceName,
InstanceType.PARTICIPANT, _zkConnectString);
} else {
throw new IllegalArgumentException("Unsupported cluster manager type:" + _clusterMangerType);
}
MockOnlineOfflineStateModelFactory stateModelFactory2 =
new MockOnlineOfflineStateModelFactory(_transDelayInMs, _resourceName, _resourceTag,
_instanceName);
// genericStateMachineHandler = new StateMachineEngine();
StateMachineEngine stateMach = manager.getStateMachineEngine();
stateMach.registerStateModelFactory("OnlineOffline", stateModelFactory2);
manager.connect();
//manager.getMessagingService().registerMessageHandlerFactory(MessageType.STATE_TRANSITION.name(), genericStateMachineHandler);
return manager;
}
public static class MockOnlineOfflineStateModelFactory extends
StateModelFactory<MockOnlineOfflineStateModel> {
int _delay;
String _instanceName;
String _resourceName;
String _resourceTag;
public MockOnlineOfflineStateModelFactory(int delay, String resourceName, String resourceTag,
String instanceName) {
_delay = delay;
_instanceName = instanceName;
_resourceName = resourceName;
_resourceTag = resourceTag;
}
@Override
public MockOnlineOfflineStateModel createNewStateModel(String resourceName, String stateUnitKey) {
MockOnlineOfflineStateModel model = new MockOnlineOfflineStateModel();
model.setDelay(_delay);
model.setInstanceName(_instanceName);
model.setResourceName(_resourceName);
model.setResourceTag(_resourceTag);
return model;
}
}
public static class MockOnlineOfflineStateModel extends StateModel {
int _transDelay = 0;
String _instanceName;
String _resourceName;
String _resourceTag;
public void setDelay(int delay) {
_transDelay = delay > 0 ? delay : 0;
}
public void setInstanceName(String instanceName) {_instanceName = instanceName;}
public void setResourceTag(String resourceTag) {
_resourceTag = resourceTag;
}
public void setResourceName(String resourceName) {
_resourceName = resourceName;
}
public void onBecomeOnlineFromOffline(Message message, NotificationContext context) {
String db = message.getPartitionName();
String instanceName = context.getManager().getInstanceName();
MockProcess.sleep(_transDelay);
logger.info("MockStateModel.onBecomeOnlineFromOffline(), instance:" + instanceName + ", db:"
+ db);
logger.info(
"MockStateModel.onBecomeOnlineFromOffline(), resource " + message.getResourceName()
+ ", partition"
+ message.getPartitionName());
verifyMessage(message);
}
public void onBecomeOfflineFromOnline(Message message, NotificationContext context) {
MockProcess.sleep(_transDelay);
logger.info(
"MockStateModel.onBecomeOfflineFromOnline(), resource " + message.getResourceName()
+ ", partition"
+ message.getPartitionName() + ", targetName: " + message.getTgtName());
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
verifyMessage(message);
}
public void onBecomeDroppedFromOffline(Message message, NotificationContext context) {
MockProcess.sleep(_transDelay);
logger.info(
"MockStateModel.onBecomeDroppedFromOffline(), resource " + message.getResourceName()
+ ", partition"
+ message.getPartitionName());
verifyMessage(message);
}
private void verifyMessage(Message message) {
assert _instanceName.equals(message.getTgtName());
assert _resourceName.equals(message.getResourceGroupName());
assert _resourceTag.equals(message.getResourceTag());
}
}
}
public static class TestParticipantManager extends ZKHelixManager implements Runnable, ZkTestManager {
private static Logger LOG = LoggerFactory.getLogger(TestParticipantManager.class);
private final CountDownLatch _startCountDown = new CountDownLatch(1);
private final CountDownLatch _stopCountDown = new CountDownLatch(1);
private final CountDownLatch _waitStopCompleteCountDown = new CountDownLatch(1);
private String _instanceGroup;
private String _resourceName;
public TestParticipantManager(String zkAddr, String clusterName, String resourceName,
String instanceGroup, String instanceName) {
super(clusterName, instanceName, InstanceType.PARTICIPANT, zkAddr);
_instanceGroup = instanceGroup;
_resourceName = resourceName;
}
public void syncStop() {
_stopCountDown.countDown();
try {
_waitStopCompleteCountDown.await();
} catch (InterruptedException e) {
LOG.error("exception in syncStop participant-manager", e);
}
}
public void syncStart() {
try {
new Thread(this).start();
_startCountDown.await();
} catch (InterruptedException e) {
LOG.error("exception in syncStart participant-manager", e);
}
}
@Override
public void run() {
try {
StateMachineEngine stateMach = getStateMachineEngine();
MockProcess.MockOnlineOfflineStateModelFactory
ofModelFactory =
new MockProcess.MockOnlineOfflineStateModelFactory(10, _resourceName, _instanceGroup,
getInstanceName());
stateMach.registerStateModelFactory("OnlineOffline", ofModelFactory);
connect();
_startCountDown.countDown();
_stopCountDown.await();
} catch (InterruptedException e) {
String msg =
"participant: " + getInstanceName() + ", " + Thread.currentThread().getName()
+ " is interrupted";
LOG.info(msg);
} catch (Exception e) {
LOG.error("exception running participant-manager", e);
} finally {
_startCountDown.countDown();
disconnect();
_waitStopCompleteCountDown.countDown();
}
}
@Override
public RealmAwareZkClient getZkClient() {
return _zkclient;
}
@Override
public List<CallbackHandler> getHandlers() {
return _handlers;
}
}
}
| 9,508 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestDrop.java
|
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 java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixDefinedState;
import org.apache.helix.PropertyKey;
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.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.mock.participant.ErrTransition;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.builder.CustomModeISBuilder;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestDrop extends ZkTestBase {
/**
* Assert externalView and currentState for each participant are empty
* @param clusterName
* @param db
* @param participants
*/
private void assertEmptyCSandEV(String clusterName, String db,
MockParticipantManager[] participants) throws Exception {
HelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
boolean isExternalViewNull = TestHelper.verify(() -> {
ExternalView externalView = accessor.getProperty(keyBuilder.externalView(db));
return (externalView == null);
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(isExternalViewNull);
for (MockParticipantManager participant : participants) {
String instanceName = participant.getInstanceName();
String sessionId = participant.getSessionId();
boolean isCurrentStateNull = TestHelper.verify(() -> {
CurrentState currentState = accessor.getProperty(keyBuilder.currentState(instanceName, sessionId, db));
return (currentState == null);
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(isCurrentStateNull);
}
}
@Test
public void testBasic() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 5;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
MockParticipantManager[] participants = new MockParticipantManager[n];
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
8, // partitions per resource
n, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// start participants
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
ZkHelixClusterVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
// Drop TestDB0
HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
admin.dropResource(clusterName, "TestDB0");
assertEmptyCSandEV(clusterName, "TestDB0", participants);
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testDropErrorPartitionAutoIS() throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 5;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
MockParticipantManager[] participants = new MockParticipantManager[n];
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
10, // partitions per resource
n, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
// start participants
Map<String, Set<String>> errTransitions = new HashMap<>();
errTransitions.put("SLAVE-MASTER", TestHelper.setOf("TestDB0_4"));
errTransitions.put("OFFLINE-SLAVE", TestHelper.setOf("TestDB0_8"));
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
if (i == 0) {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].setTransition(new ErrTransition(errTransitions));
} else {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
}
participants[i].syncStart();
}
Map<String, Map<String, String>> errStateMap = new HashMap<>();
errStateMap.put("TestDB0", new HashMap<>());
errStateMap.get("TestDB0").put("TestDB0_4", "localhost_12918");
errStateMap.get("TestDB0").put("TestDB0_8", "localhost_12918");
ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(clusterName)
.setZkClient(_gZkClient).setErrStates(errStateMap)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
// drop resource containing error partitions should drop the partition successfully
ClusterSetup.processCommandLineArgs(new String[] {
"--zkSvr", ZK_ADDR, "--dropResource", clusterName, "TestDB0"
});
// make sure TestDB0_4 and TestDB0_8 partitions are dropped
verifier = new BestPossibleExternalViewVerifier.Builder(clusterName)
.setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
Thread.sleep(400);
assertEmptyCSandEV(className, "TestDB0", participants);
// clean up
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testDropErrorPartitionFailedAutoIS() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 5;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
MockParticipantManager[] participants = new MockParticipantManager[n];
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
8, // partitions per resource
n, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
// start participants
Map<String, Set<String>> errTransitions = new HashMap<>();
errTransitions.put("SLAVE-MASTER", TestHelper.setOf("TestDB0_4"));
errTransitions.put("ERROR-DROPPED", TestHelper.setOf("TestDB0_4"));
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
if (i == 0) {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].setTransition(new ErrTransition(errTransitions));
} else {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
}
participants[i].syncStart();
}
Map<String, Map<String, String>> errStateMap = new HashMap<>();
errStateMap.put("TestDB0", new HashMap<>());
errStateMap.get("TestDB0").put("TestDB0_4", "localhost_12918");
ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(clusterName)
.setZkClient(_gZkClient).setErrStates(errStateMap)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
// drop resource containing error partitions should invoke error->dropped transition
// if error happens during error->dropped transition, partition should be disabled
ClusterSetup.processCommandLineArgs(new String[] {
"--zkSvr", ZK_ADDR, "--dropResource", clusterName, "TestDB0"
});
// make sure TestDB0_4 stay in ERROR state and is disabled
Assert.assertTrue(verifier.verifyByPolling());
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
// ExternalView should have TestDB0_4->localhost_12918_>ERROR
Thread.sleep(250L);
ExternalView ev = accessor.getProperty(keyBuilder.externalView("TestDB0"));
Set<String> partitions = ev.getPartitionSet();
Assert.assertEquals(partitions.size(), 1, "Should have TestDB0_4->localhost_12918->ERROR");
String errPartition = partitions.iterator().next();
Assert.assertEquals(errPartition, "TestDB0_4");
Map<String, String> stateMap = ev.getStateMap(errPartition);
Assert.assertEquals(stateMap.size(), 1);
Assert.assertEquals(stateMap.keySet().iterator().next(), "localhost_12918");
Assert.assertEquals(stateMap.get("localhost_12918"), HelixDefinedState.ERROR.name());
// localhost_12918 should have TestDB0_4 in ERROR state
CurrentState cs =
accessor.getProperty(keyBuilder.currentState(participants[0].getInstanceName(),
participants[0].getSessionId(), "TestDB0"));
Map<String, String> partitionStateMap = cs.getPartitionStateMap();
Assert.assertEquals(partitionStateMap.size(), 1);
Assert.assertEquals(partitionStateMap.keySet().iterator().next(), "TestDB0_4");
Assert.assertEquals(partitionStateMap.get("TestDB0_4"), HelixDefinedState.ERROR.name());
// all other participants should have cleaned up empty current state
for (int i = 1; i < n; i++) {
String instanceName = participants[i].getInstanceName();
String sessionId = participants[i].getSessionId();
Assert.assertNull(
accessor.getProperty(keyBuilder.currentState(instanceName, sessionId, "TestDB0")));
}
// clean up
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testDropErrorPartitionCustomIS() throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 2;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
MockParticipantManager[] participants = new MockParticipantManager[n];
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
2, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", false); // do rebalance
// set custom ideal-state
CustomModeISBuilder isBuilder = new CustomModeISBuilder("TestDB0");
isBuilder.setNumPartitions(2);
isBuilder.setNumReplica(2);
isBuilder.setStateModel("MasterSlave");
isBuilder.assignInstanceAndState("TestDB0_0", "localhost_12918", "MASTER");
isBuilder.assignInstanceAndState("TestDB0_0", "localhost_12919", "SLAVE");
isBuilder.assignInstanceAndState("TestDB0_1", "localhost_12919", "MASTER");
isBuilder.assignInstanceAndState("TestDB0_1", "localhost_12918", "SLAVE");
HelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
accessor.setProperty(keyBuilder.idealStates("TestDB0"), isBuilder.build());
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
// start participants
Map<String, Set<String>> errTransitions = new HashMap<>();
errTransitions.put("SLAVE-MASTER", TestHelper.setOf("TestDB0_0"));
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
if (i == 0) {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].setTransition(new ErrTransition(errTransitions));
} else {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
}
participants[i].syncStart();
}
Map<String, Map<String, String>> errStateMap = new HashMap<>();
errStateMap.put("TestDB0", new HashMap<>());
errStateMap.get("TestDB0").put("TestDB0_0", "localhost_12918");
ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(clusterName)
.setZkClient(_gZkClient).setErrStates(errStateMap)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
// drop resource containing error partitions should drop the partition successfully
ClusterSetup.processCommandLineArgs(new String[] {
"--zkSvr", ZK_ADDR, "--dropResource", clusterName, "TestDB0"
});
// make sure TestDB0_0 partition is dropped
verifier = new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling(), "Should be empty exeternal-view");
Thread.sleep(400);
assertEmptyCSandEV(clusterName, "TestDB0", participants);
// clean up
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testDropSchemataResource() throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 5;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
MockParticipantManager[] participants = new MockParticipantManager[n];
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
8, // partitions per resource
n, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
// start participants
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
ZkHelixClusterVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
// add schemata resource group
String command = "--zkSvr " + ZK_ADDR + " --addResource " + clusterName
+ " schemata 1 STORAGE_DEFAULT_SM_SCHEMATA";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
command = "--zkSvr " + ZK_ADDR + " --rebalance " + clusterName + " schemata " + n;
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.assertTrue(verifier.verifyByPolling());
// drop schemata resource group
// System.out.println("Dropping schemata resource group...");
command = "--zkSvr " + ZK_ADDR + " --dropResource " + clusterName + " schemata";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
Assert.assertTrue(verifier.verifyByPolling());
Thread.sleep(400);
assertEmptyCSandEV(clusterName, "schemata", participants);
// clean up
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,509 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestPartitionMovementThrottle.java
|
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.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.NotificationContext;
import org.apache.helix.TestHelper;
import org.apache.helix.api.config.StateTransitionThrottleConfig;
import org.apache.helix.controller.rebalancer.DelayedAutoRebalancer;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.integration.task.WorkflowGenerator;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.model.Message;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ClusterLiveNodesVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
private ConfigAccessor _configAccessor;
private Set<String> _dbs = new HashSet<>();
@Override
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NODE_NR; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
}
// add dummy participants
for (int i = 0; i < NODE_NR; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
participant.setTransition(new DelayedTransition());
_participants[i] = participant;
}
_configAccessor = new ConfigAccessor(_gZkClient);
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
setupThrottleConfig();
_clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME)
.setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
}
private void setupThrottleConfig() {
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
StateTransitionThrottleConfig resourceLoadThrottle =
new StateTransitionThrottleConfig(StateTransitionThrottleConfig.RebalanceType.LOAD_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.RESOURCE, 2);
StateTransitionThrottleConfig instanceLoadThrottle =
new StateTransitionThrottleConfig(StateTransitionThrottleConfig.RebalanceType.LOAD_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.INSTANCE, 2);
StateTransitionThrottleConfig clusterLoadThrottle =
new StateTransitionThrottleConfig(StateTransitionThrottleConfig.RebalanceType.LOAD_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.CLUSTER, 100);
StateTransitionThrottleConfig resourceRecoveryThrottle = new StateTransitionThrottleConfig(
StateTransitionThrottleConfig.RebalanceType.RECOVERY_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.RESOURCE, 3);
StateTransitionThrottleConfig clusterRecoveryThrottle = new StateTransitionThrottleConfig(
StateTransitionThrottleConfig.RebalanceType.RECOVERY_BALANCE,
StateTransitionThrottleConfig.ThrottleScope.CLUSTER, 100);
clusterConfig
.setStateTransitionThrottleConfigs(Arrays.asList(resourceLoadThrottle, instanceLoadThrottle,
clusterLoadThrottle, resourceRecoveryThrottle, clusterRecoveryThrottle));
clusterConfig.setPersistIntermediateAssignment(true);
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
}
@Test()
public void testResourceThrottle() throws Exception {
// start a few participants
for (int i = 0; i < NODE_NR - 2; i++) {
_participants[i].syncStart();
}
for (int i = 0; i < 5; i++) {
String dbName = "TestDB-" + i;
_gSetupTool.addResourceToCluster(CLUSTER_NAME, dbName, 10, STATE_MODEL,
RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName());
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, _replica);
_dbs.add(dbName);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
DelayedTransition.setDelay(20);
DelayedTransition.enableThrottleRecord();
// add 2 nodes
for (int i = NODE_NR - 2; i < NODE_NR; i++) {
_participants[i].syncStart();
}
Thread.sleep(2000);
for (String db : _dbs) {
// After the fix in IntermediateCalcStage where downward load-balance is now allowed even if
// there are recovery or error partitions present, maxPendingTransition below is adjusted from
// 2 to 5 because BOTH recovery balance and load balance could happen in the same pipeline
// iteration
Assert.assertTrue(getMaxParallelTransitionCount(
DelayedTransition.getResourcePatitionTransitionTimes(), db) <= 5);
}
}
@Test
public void testPartitionRecoveryRebalanceThrottle() throws InterruptedException {
// start some participants
for (int i = 0; i < NODE_NR - 2; i++) {
_participants[i].syncStart();
}
_gSetupTool
.addResourceToCluster(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB, 10, STATE_MODEL,
RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName());
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB, _replica);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// Set throttling after states are stable. Otherwise it takes too long to reach stable state
setSingleThrottlingConfig(StateTransitionThrottleConfig.RebalanceType.RECOVERY_BALANCE, 2);
DelayedTransition.setDelay(20);
DelayedTransition.enableThrottleRecord();
// start another 2 nodes
for (int i = NODE_NR - 2; i < NODE_NR; i++) {
_participants[i].syncStart();
}
Thread.sleep(2000);
for (int i = 0; i < NODE_NR; i++) {
Assert.assertTrue(
getMaxParallelTransitionCount(DelayedTransition.getInstancePatitionTransitionTimes(),
_participants[i].getInstanceName()) <= 2);
}
}
@Test
public void testANYtypeThrottle() throws InterruptedException {
// start some participants
for (int i = 0; i < NODE_NR - 3; i++) {
_participants[i].syncStart();
}
_gSetupTool.addResourceToCluster(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB + "_ANY", 20,
STATE_MODEL, RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName());
_gSetupTool
.rebalanceStorageCluster(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB + "_ANY", _replica);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// Set ANY type throttling after states are stable.
setSingleThrottlingConfig(StateTransitionThrottleConfig.RebalanceType.ANY, 1);
DelayedTransition.setDelay(20);
DelayedTransition.enableThrottleRecord();
// start another 3 nodes
for (int i = NODE_NR - 3; i < NODE_NR; i++) {
_participants[i].syncStart();
}
Thread.sleep(2000L);
for (int i = 0; i < NODE_NR; i++) {
Assert.assertTrue(
getMaxParallelTransitionCount(DelayedTransition.getInstancePatitionTransitionTimes(),
_participants[i].getInstanceName()) <= 1);
}
}
@Test
public void testThrottleOnlyClusterLevelAnyType() {
// start some participants
for (int i = 0; i < NODE_NR - 3; i++) {
_participants[i].syncStart();
}
// Add resource: TestDB_ANY of 20 partitions
_gSetupTool
.addResourceToCluster(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB + "_OnlyANY", 20,
STATE_MODEL, RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName());
// Act the rebalance process
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB + "_OnlyANY",
_replica);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// overwrite the cluster level throttle configuration
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
StateTransitionThrottleConfig anyTypeClusterThrottle =
new StateTransitionThrottleConfig(StateTransitionThrottleConfig.RebalanceType.ANY,
StateTransitionThrottleConfig.ThrottleScope.CLUSTER, 1);
clusterConfig.setStateTransitionThrottleConfigs(ImmutableList.of(anyTypeClusterThrottle));
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
DelayedTransition.setDelay(20);
DelayedTransition.enableThrottleRecord();
List<MockParticipantManager> newNodes =
Arrays.asList(_participants).subList(NODE_NR - 3, NODE_NR);
newNodes.forEach(MockParticipantManager::syncStart);
newNodes.forEach(node -> {
try {
Assert.assertTrue(TestHelper.verify(() -> getMaxParallelTransitionCount(
DelayedTransition.getInstancePatitionTransitionTimes(), node.getInstanceName()) <= 1,
1000 * 2));
} catch (Exception e) {
e.printStackTrace();
assert false;
}
});
ClusterLiveNodesVerifier liveNodesVerifier =
new ClusterLiveNodesVerifier(_gZkClient, CLUSTER_NAME,
Lists.transform(Arrays.asList(_participants), MockParticipantManager::getInstanceName));
Assert.assertTrue(liveNodesVerifier.verifyByZkCallback(1000));
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (int i = 0; i < NODE_NR; i++) {
_participants[i].syncStop();
}
}
@AfterMethod
public void cleanupTest() throws InterruptedException {
for (String db : _dbs) {
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, db);
Thread.sleep(20);
}
_dbs.clear();
Thread.sleep(50);
HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor<>(_gZkClient));
for (int i = 0; i < _participants.length; i++) {
_participants[i].syncStop();
_participants[i] =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _participants[i].getInstanceName());
}
try {
Assert.assertTrue(TestHelper.verify(() -> dataAccessor.getChildNames(dataAccessor.keyBuilder().liveInstances()).isEmpty(), 1000));
} catch (Exception e) {
e.printStackTrace();
System.out.println("There're live instances not cleaned up yet");
assert false;
}
DelayedTransition.clearThrottleRecord();
}
@Test(dependsOnMethods = {
"testResourceThrottle"
})
public void testResourceThrottleWithDelayRebalancer() {
// start a few participants
for (int i = 0; i < NODE_NR - 2; i++) {
_participants[i].syncStart();
}
int partition = 10;
int replica = 3;
int minActiveReplica = 2;
int delay = 100;
for (int i = 0; i < 5; i++) {
String dbName = "TestDB-" + i;
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
if (is != null) {
System.err.println(dbName + "exists!");
is.setReplicas(String.valueOf(replica));
is.setMinActiveReplicas(minActiveReplica);
is.setRebalanceDelay(delay);
is.setRebalancerClassName(DelayedAutoRebalancer.class.getName());
_gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, dbName, is);
} else {
createResourceWithDelayedRebalance(CLUSTER_NAME, dbName, STATE_MODEL, partition, replica,
minActiveReplica, delay);
}
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, _replica);
_dbs.add(dbName);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
DelayedTransition.setDelay(20);
DelayedTransition.enableThrottleRecord();
// add 2 nodes
for (int i = NODE_NR - 2; i < NODE_NR; i++) {
_participants[i].syncStart();
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _dbs) {
int maxInParallel =
getMaxParallelTransitionCount(DelayedTransition.getResourcePatitionTransitionTimes(), db);
System.out.println("MaxInParallel: " + maxInParallel + " maxPendingTransition: " + 2);
Assert.assertTrue(maxInParallel <= 2, "Throttle condition does not meet for " + db);
}
}
private int getMaxParallelTransitionCount(
Map<String, List<PartitionTransitionTime>> partitionTransitionTimesMap,
String throttledItemName) {
List<PartitionTransitionTime> pTimeList = partitionTransitionTimesMap.get(throttledItemName);
Map<Long, List<PartitionTransitionTime>> startMap = new HashMap<>();
Map<Long, List<PartitionTransitionTime>> endMap = new HashMap<>();
List<Long> startEndPoints = new ArrayList<>();
if (pTimeList == null) {
System.out.println("no throttle result for :" + throttledItemName);
return -1;
}
pTimeList.sort((o1, o2) -> (int) (o1.start - o2.start));
for (PartitionTransitionTime interval : pTimeList) {
if (!startMap.containsKey(interval.start)) {
startMap.put(interval.start, new ArrayList<>());
}
startMap.get(interval.start).add(interval);
if (!endMap.containsKey(interval.end)) {
endMap.put(interval.end, new ArrayList<>());
}
endMap.get(interval.end).add(interval);
startEndPoints.add(interval.start);
startEndPoints.add(interval.end);
}
Collections.sort(startEndPoints);
List<PartitionTransitionTime> temp = new ArrayList<>();
int maxInParallel = 0;
for (long point : startEndPoints) {
if (startMap.containsKey(point)) {
temp.addAll(startMap.get(point));
}
int curSize = size(temp);
if (curSize > maxInParallel) {
maxInParallel = curSize;
}
if (endMap.containsKey(point)) {
temp.removeAll(endMap.get(point));
}
}
System.out
.println("Max number of ST in parallel: " + maxInParallel + " for " + throttledItemName);
return maxInParallel;
}
private int size(List<PartitionTransitionTime> timeList) {
Set<String> partitions = new HashSet<>();
for (PartitionTransitionTime p : timeList) {
partitions.add(p.partition);
}
return partitions.size();
}
private static class PartitionTransitionTime {
String partition;
long start;
long end;
PartitionTransitionTime(String partition, long start, long end) {
this.partition = partition;
this.start = start;
this.end = end;
}
@Override
public String toString() {
return "[" + "partition='" + partition + '\'' + ", start=" + start + ", end=" + end + ']';
}
}
private void setSingleThrottlingConfig(StateTransitionThrottleConfig.RebalanceType rebalanceType,
int maxStateTransitions) {
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
StateTransitionThrottleConfig anyTypeInstanceThrottle = new StateTransitionThrottleConfig(
rebalanceType, StateTransitionThrottleConfig.ThrottleScope.INSTANCE, maxStateTransitions);
List<StateTransitionThrottleConfig> currentThrottleConfigs =
clusterConfig.getStateTransitionThrottleConfigs();
currentThrottleConfigs.add(anyTypeInstanceThrottle);
clusterConfig.setStateTransitionThrottleConfigs(currentThrottleConfigs);
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
}
private static class DelayedTransition extends DelayedTransitionBase {
private static Map<String, List<PartitionTransitionTime>> resourcePatitionTransitionTimes =
new ConcurrentHashMap<>();
private static Map<String, List<PartitionTransitionTime>> instancePatitionTransitionTimes =
new ConcurrentHashMap<>();
private static boolean _recordThrottle = false;
static Map<String, List<PartitionTransitionTime>> getResourcePatitionTransitionTimes() {
return resourcePatitionTransitionTimes;
}
static Map<String, List<PartitionTransitionTime>> getInstancePatitionTransitionTimes() {
return instancePatitionTransitionTimes;
}
static void enableThrottleRecord() {
_recordThrottle = true;
}
static void clearThrottleRecord() {
resourcePatitionTransitionTimes.clear();
instancePatitionTransitionTimes.clear();
}
@Override
public void doTransition(Message message, NotificationContext context)
throws InterruptedException {
long start = System.currentTimeMillis();
if (_delay > 0) {
Thread.sleep(_delay);
}
long end = System.currentTimeMillis();
if (_recordThrottle) {
PartitionTransitionTime partitionTransitionTime =
new PartitionTransitionTime(message.getPartitionName(), start, end);
if (!resourcePatitionTransitionTimes.containsKey(message.getResourceName())) {
resourcePatitionTransitionTimes.put(message.getResourceName(),
Collections.synchronizedList(new ArrayList<>()));
}
resourcePatitionTransitionTimes.get(message.getResourceName()).add(partitionTransitionTime);
if (!instancePatitionTransitionTimes.containsKey(message.getTgtName())) {
instancePatitionTransitionTimes.put(message.getTgtName(),
Collections.synchronizedList(new ArrayList<>()));
}
instancePatitionTransitionTimes.get(message.getTgtName()).add(partitionTransitionTime);
}
}
}
}
| 9,510 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestResetInstance.java
|
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 java.util.HashMap;
import java.util.Map;
import java.util.Set;
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.mock.participant.ErrTransition;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterStateVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestResetInstance extends ZkTestBase {
@Test
public void testResetInstance() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 5;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
10, // partitions per resource
n, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
Map<String, Set<String>> errPartitions = new HashMap<String, Set<String>>() {
{
put("SLAVE-MASTER", TestHelper.setOf("TestDB0_4"));
put("OFFLINE-SLAVE", TestHelper.setOf("TestDB0_8"));
}
};
// start mock participants
MockParticipantManager[] participants = new MockParticipantManager[n];
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
if (i == 0) {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].setTransition(new ErrTransition(errPartitions));
} else {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
}
participants[i].syncStart();
}
// verify cluster
Map<String, Map<String, String>> errStateMap = new HashMap<String, Map<String, String>>();
errStateMap.put("TestDB0", new HashMap<String, String>());
errStateMap.get("TestDB0").put("TestDB0_4", "localhost_12918");
errStateMap.get("TestDB0").put("TestDB0_8", "localhost_12918");
boolean result =
ClusterStateVerifier
.verifyByZkCallback((new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName, errStateMap)));
Assert.assertTrue(result, "Cluster verification fails");
// reset node "localhost_12918"
participants[0].setTransition(null);
String command = "--zkSvr " + ZK_ADDR + " --resetInstance " + clusterName + " localhost_12918";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
result =
ClusterStateVerifier
.verifyByZkCallback((new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName)));
Assert.assertTrue(result, "Cluster verification fails");
// clean up
controller.syncStop();
for (int i = 0; i < 5; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,511 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestEnableCompression.java
|
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.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.helix.InstanceType;
import org.apache.helix.PropertyPathBuilder;
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.model.IdealState;
import org.apache.helix.model.builder.CustomModeISBuilder;
import org.apache.helix.monitoring.mbeans.MBeanRegistrar;
import org.apache.helix.monitoring.mbeans.MonitorDomainNames;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.util.GZipCompressionUtil;
import org.apache.helix.zookeeper.api.client.HelixZkClient;
import org.apache.helix.zookeeper.impl.factory.SharedZkClientFactory;
import org.apache.helix.zookeeper.zkclient.metric.ZkClientMonitor;
import org.apache.helix.zookeeper.zkclient.serialize.BytesPushThroughSerializer;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Test controller, spectator and participant roles when compression is enabled.
* Compression can be enabled for a specific resource by setting enableCompression=true in the
* idealstate of the resource. Generally this is used when the number of partitions is large
*/
public class TestEnableCompression extends ZkTestBase {
private static final int ENABLE_COMPRESSION_WAIT = 20 * 60 * 1000;
private static final int ENABLE_COMPRESSION_POLL_INTERVAL = 2000;
@Test(timeOut = 10 * 10 * 1000L)
public void testEnableCompressionResource() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
MockParticipantManager[] participants = new MockParticipantManager[5];
// ClusterSetup setupTool = new ClusterSetup(ZK_ADDR);
int numNodes = 10;
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
0, // no resources, will be added later
0, // partitions per resource
numNodes, // number of nodes
0, // replicas
"OnlineOffline", false); // dont rebalance
List<String> instancesInCluster =
_gSetupTool.getClusterManagementTool().getInstancesInCluster(clusterName);
String resourceName = "TestResource";
Set<String> expectedResources = new HashSet<>();
expectedResources.add(resourceName);
CustomModeISBuilder customModeISBuilder = new CustomModeISBuilder(resourceName);
int numPartitions = 10000;
int numReplica = 3;
customModeISBuilder.setNumPartitions(numPartitions);
customModeISBuilder.setNumReplica(numReplica);
customModeISBuilder.setStateModel("OnlineOffline");
for (int p = 0; p < numPartitions; p++) {
String partitionName = resourceName + "_" + p;
customModeISBuilder.add(partitionName);
for (int r = 0; r < numReplica; r++) {
String instanceName = instancesInCluster.get((p % numNodes + r) % numNodes);
customModeISBuilder.assignInstanceAndState(partitionName, instanceName, "ONLINE");
}
}
IdealState idealstate = customModeISBuilder.build();
idealstate.getRecord().setBooleanField("enableCompression", true);
_gSetupTool.getClusterManagementTool().addResource(clusterName, resourceName, idealstate);
HelixZkClient.ZkClientConfig clientConfig = new HelixZkClient.ZkClientConfig();
clientConfig.setZkSerializer(new BytesPushThroughSerializer())
.setOperationRetryTimeout((long) (60 * 1000)).setConnectInitTimeout(60 * 1000);
HelixZkClient zkClient = SharedZkClientFactory.getInstance()
.buildZkClient(new HelixZkClient.ZkConnectionConfig(ZK_ADDR), clientConfig);
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
Set<String> expectedLiveInstances = new HashSet<>();
// 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();
expectedLiveInstances.add(instanceName);
}
BestPossibleExternalViewVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setExpectLiveInstances(expectedLiveInstances).setResources(expectedResources)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
boolean reuslt = verifier.verifyByPolling(ENABLE_COMPRESSION_WAIT, ENABLE_COMPRESSION_POLL_INTERVAL);
Assert.assertTrue((reuslt));
List<String> compressedPaths = new ArrayList<>();
findCompressedZNodes(zkClient, "/" + clusterName, compressedPaths);
System.out.println("compressed paths:" + compressedPaths);
// ONLY IDEALSTATE and EXTERNAL VIEW must be compressed
Assert.assertEquals(compressedPaths.size(), 2);
String idealstatePath = PropertyPathBuilder.idealState(clusterName, resourceName);
String externalViewPath = PropertyPathBuilder.externalView(clusterName, resourceName);
Assert.assertTrue(compressedPaths.contains(idealstatePath));
Assert.assertTrue(compressedPaths.contains(externalViewPath));
// Validate the compressed ZK nodes count == external view nodes
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName name =
MBeanRegistrar.buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE,
InstanceType.CONTROLLER.name(), ZkClientMonitor.MONITOR_KEY,
clusterName + "." + controller.getInstanceName());
// The controller ZkClient only writes one compressed node, which is the External View node.
long compressCount = (long) beanServer.getAttribute(name, "CompressedZnodeWriteCounter");
// Note since external view node is updated in every controller pipeline, there would be multiple compressed writes.
// However, the total count won't exceed the external view node version (starts from 0).
Assert.assertTrue(compressCount >= 1 && compressCount <= zkClient.getStat(externalViewPath).getVersion() + 1);
// clean up
controller.syncStop();
for (int i = 0; i < 5; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
private void findCompressedZNodes(HelixZkClient zkClient, String path,
List<String> compressedPaths) {
List<String> children = zkClient.getChildren(path);
if (children != null && children.size() > 0) {
for (String child : children) {
String childPath = (path.equals("/") ? "" : path) + "/" + child;
findCompressedZNodes(zkClient, childPath, compressedPaths);
}
} else {
byte[] data = zkClient.readData(path);
if (GZipCompressionUtil.isCompressed(data)) {
compressedPaths.add(path);
}
}
}
}
| 9,512 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestEntropyFreeNodeBounce.java
|
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.BaseDataAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.InstanceType;
import org.apache.helix.NotificationContext;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZKHelixManager;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.zookeeper.impl.client.ZkClient;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.model.Message;
import org.apache.helix.participant.statemachine.StateModel;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.apache.helix.participant.statemachine.StateModelInfo;
import org.apache.helix.participant.statemachine.Transition;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.apache.helix.tools.ClusterStateVerifier.ZkVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestEntropyFreeNodeBounce extends ZkUnitTestBase {
@Test
public void testBounceAll() throws Exception {
// pick numbers that don't divide evenly
final int NUM_PARTICIPANTS = 5;
final int NUM_PARTITIONS = 123;
final int NUM_REPLICAS = 1;
final String RESOURCE_PREFIX = "TestDB";
final String RESOURCE_NAME = RESOURCE_PREFIX + "0";
// create a cluster name based on this test name
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
// Set up cluster
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
NUM_PARTITIONS, // partitions per resource
NUM_PARTICIPANTS, // number of nodes
NUM_REPLICAS, // replicas
"OnlineOffline", RebalanceMode.FULL_AUTO, // use FULL_AUTO mode to test node tagging
true); // do rebalance
// Start the participants
HelixManager[] participants = new HelixManager[NUM_PARTICIPANTS];
for (int i = 0; i < NUM_PARTICIPANTS; i++) {
final String instanceName = "localhost_" + (12918 + i);
participants[i] = createParticipant(clusterName, instanceName);
participants[i].connect();
}
// Start the controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// get an admin and accessor
HelixAdmin helixAdmin = new ZKHelixAdmin(_gZkClient);
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
List<HelixManager> participantToClose = new ArrayList<>();
// do the test
try {
Thread.sleep(1000);
// ensure that the external view coalesces
boolean result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
ExternalView stableExternalView =
accessor.getProperty(keyBuilder.externalView(RESOURCE_NAME));
for (int i = 0; i < NUM_PARTICIPANTS; i++) {
// disable the controller, bounce the node, re-enable the controller, verify assignments
// remained the same
HelixManager participant = participants[i];
helixAdmin.enableCluster(clusterName, false);
participant.disconnect();
Thread.sleep(1000);
participant = createParticipant(clusterName, participant.getInstanceName());
participantToClose.add(participant);
participant.connect();
participants[i] = participant;
Thread.sleep(1000);
helixAdmin.enableCluster(clusterName, true);
Thread.sleep(1000);
result =
ClusterStateVerifier.verifyByZkCallback(new MatchingExternalViewVerifier(
stableExternalView, clusterName));
Assert.assertTrue(result);
}
} finally {
// clean up
controller.syncStop();
for (HelixManager participant : participantToClose) {
participant.disconnect();
}
TestHelper.dropCluster(clusterName, _gZkClient);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
private HelixManager createParticipant(String clusterName, String instanceName) {
HelixManager participant =
new ZKHelixManager(clusterName, instanceName, InstanceType.PARTICIPANT, ZK_ADDR);
participant.getStateMachineEngine().registerStateModelFactory("OnlineOffline",
new MockStateModelFactory());
return participant;
}
@StateModelInfo(initialState = "OFFLINE", states = {
"ONLINE", "OFFLINE", "DROPPED", "ERROR"
})
public static class MockStateModel extends StateModel {
@Transition(to = "*", from = "*")
public void onBecomeAnyFromAny(Message message, NotificationContext context) {
}
}
private static class MockStateModelFactory extends StateModelFactory<MockStateModel> {
@Override
public MockStateModel createNewStateModel(String resource, String partitionName) {
return new MockStateModel();
}
}
/**
* Simple verifier: just check that the external view matches a reference
*/
private static class MatchingExternalViewVerifier implements ZkVerifier {
private final HelixDataAccessor _accessor;
private final ExternalView _reference;
private final String _clusterName;
public MatchingExternalViewVerifier(ExternalView reference, String clusterName) {
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
_accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
_reference = reference;
_clusterName = clusterName;
}
@Override
public boolean verify() {
ExternalView externalView =
_accessor.getProperty(_accessor.keyBuilder().externalView(_reference.getResourceName()));
return _reference.equals(externalView);
}
@Override
public ZkClient getZkClient() {
return (ZkClient) _gZkClient;
}
@Override
public String getClusterName() {
return _clusterName;
}
}
}
| 9,513 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestAlertingRebalancerFailure.java
|
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.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.controller.rebalancer.strategy.CrushRebalanceStrategy;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
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.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.builder.FullAutoModeISBuilder;
import org.apache.helix.monitoring.mbeans.MonitorDomainNames;
import org.apache.helix.monitoring.mbeans.ResourceMonitor;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.apache.helix.monitoring.mbeans.ClusterStatusMonitor.CLUSTER_DN_KEY;
import static org.apache.helix.monitoring.mbeans.ClusterStatusMonitor.RESOURCE_DN_KEY;
import static org.apache.helix.util.StatusUpdateUtil.ErrorType.RebalanceResourceFailure;
public class TestAlertingRebalancerFailure extends ZkStandAloneCMTestBase {
private static final long TIMEOUT = 180 * 1000L;
private static final Set<String> _instanceNames = new HashSet<>();
private static final MBeanServerConnection _server = ManagementFactory.getPlatformMBeanServer();
protected static final int NODE_NR = 3;
private static String testDb = "TestDB_AlertingRebalancerFailure";
private ZKHelixDataAccessor accessor;
private PropertyKey errorNodeKey;
@Override
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
// Clean up all JMX objects
for (ObjectName mbean : _server.queryNames(null, null)) {
try {
_server.unregisterMBean(mbean);
} catch (Exception e) {
// OK
}
}
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NODE_NR; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
// start dummy participants
for (int i = 0; i < NODE_NR; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_instanceNames.add(instanceName);
_participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
_participants[i].syncStart();
}
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
accessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
errorNodeKey = accessor.keyBuilder().controllerTaskError(RebalanceResourceFailure.name());
_clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME)
.setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
}
@BeforeMethod
public void beforeMethod() throws IOException {
// Ensure error has been removed
accessor.removeProperty(errorNodeKey);
}
@Test
public void testParticipantUnavailable() throws Exception {
IdealState idealState = new FullAutoModeISBuilder(testDb)
.setStateModel(BuiltInStateModelDefinitions.MasterSlave.name())
.setStateModelFactoryName("DEFAULT").setNumPartitions(5).setNumReplica(3)
.setRebalancerMode(IdealState.RebalanceMode.FULL_AUTO)
.setRebalancerClass("org.apache.helix.controller.rebalancer.DelayedAutoRebalancer")
.setRebalanceStrategy(
"org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy").build();
_gSetupTool.addResourceToCluster(CLUSTER_NAME, testDb, idealState);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, testDb, 3);
ZkHelixClusterVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setResources(new HashSet<>(Collections.singleton(testDb)))
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
// disable then enable the resource to ensure no rebalancing error is generated during this
// process
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, testDb);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, testDb, idealState);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, testDb, 3);
Assert.assertTrue(verifier.verifyByPolling());
// Verify there is no rebalance error logged
Assert.assertNull(accessor.getProperty(errorNodeKey));
checkRebalanceFailureGauge(false);
checkResourceBestPossibleCalFailureState(ResourceMonitor.RebalanceStatus.NORMAL, testDb);
// kill nodes, so rebalance cannot be done
for (int i = 0; i < NODE_NR; i++) {
_participants[i].syncStop();
}
// Verify the rebalance error caused by no node available
pollForError(accessor, errorNodeKey);
checkRebalanceFailureGauge(true);
checkResourceBestPossibleCalFailureState(
ResourceMonitor.RebalanceStatus.BEST_POSSIBLE_STATE_CAL_FAILED, testDb);
// clean up
_gSetupTool.getClusterManagementTool().dropResource(CLUSTER_NAME, testDb);
for (int i = 0; i < NODE_NR; i++) {
_participants[i] =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _participants[i].getInstanceName());
_participants[i].syncStart();
}
}
@Test(dependsOnMethods = "testParticipantUnavailable")
public void testTagSetIncorrect() throws Exception {
_gSetupTool.addResourceToCluster(CLUSTER_NAME, testDb, 5,
BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.FULL_AUTO.name(),
CrushEdRebalanceStrategy.class.getName());
ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME)
.setZkClient(_gZkClient).setResources(new HashSet<>(Collections.singleton(testDb)))
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
_gSetupTool.getClusterManagementTool().rebalance(CLUSTER_NAME, testDb, 3);
Assert.assertTrue(verifier.verifyByPolling());
// Verify there is no rebalance error logged
Assert.assertNull(accessor.getProperty(errorNodeKey));
Assert.assertTrue(_clusterVerifier.verifyByPolling());
checkRebalanceFailureGauge(false);
checkResourceBestPossibleCalFailureState(ResourceMonitor.RebalanceStatus.NORMAL, testDb);
// set expected instance tag
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, testDb);
is.setInstanceGroupTag("RandomTag");
_gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, testDb, is);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, testDb, 3);
// Verify there is rebalance error logged
pollForError(accessor, errorNodeKey);
checkRebalanceFailureGauge(true);
checkResourceBestPossibleCalFailureState(
ResourceMonitor.RebalanceStatus.BEST_POSSIBLE_STATE_CAL_FAILED, testDb);
// clean up
_gSetupTool.getClusterManagementTool().dropResource(CLUSTER_NAME, testDb);
}
@Test(dependsOnMethods = "testTagSetIncorrect")
public void testWithDomainId() throws Exception {
int replicas = 2;
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
// 1. disable all participants except one node, then set domain Id
for (int i = NODE_NR - 1; i >= 0; i--) {
if (i < replicas) {
setDomainId(_participants[i].getInstanceName(), configAccessor);
} else {
setInstanceEnable(_participants[i].getInstanceName(), false, configAccessor);
}
}
// enable topology aware
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setTopologyAwareEnabled(true);
clusterConfig.setTopology("/Rack/Instance");
clusterConfig.setFaultZoneType("Rack");
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
// Ensure error caused by node config changes has been removed.
// Error may be recorded unexpectedly when a resource from other tests is not cleaned up.
accessor.removeProperty(errorNodeKey);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, testDb, 5,
BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.FULL_AUTO.name(),
CrushRebalanceStrategy.class.getName());
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, testDb, replicas);
ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME)
.setZkClient(_gZkClient).setResources(new HashSet<>(Collections.singleton(testDb)))
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
// Verify there is no rebalance error logged
Assert.assertNull(accessor.getProperty(errorNodeKey));
checkRebalanceFailureGauge(false);
checkResourceBestPossibleCalFailureState(ResourceMonitor.RebalanceStatus.NORMAL, testDb);
// 2. enable the rest nodes with no domain Id
for (int i = replicas; i < NODE_NR; i++) {
setInstanceEnable(_participants[i].getInstanceName(), true, configAccessor);
}
// Verify there is rebalance error logged
pollForError(accessor, errorNodeKey);
checkRebalanceFailureGauge(true);
checkResourceBestPossibleCalFailureState(
ResourceMonitor.RebalanceStatus.BEST_POSSIBLE_STATE_CAL_FAILED, testDb);
// 3. reset all nodes domain Id to be correct setting
for (int i = replicas; i < NODE_NR; i++) {
setDomainId(_participants[i].getInstanceName(), configAccessor);
}
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, testDb, replicas);
Assert.assertTrue(_clusterVerifier.verify());
// Verify that rebalance error state is removed
checkRebalanceFailureGauge(false);
checkResourceBestPossibleCalFailureState(ResourceMonitor.RebalanceStatus.NORMAL, testDb);
// clean up
_gSetupTool.getClusterManagementTool().dropResource(CLUSTER_NAME, testDb);
clusterConfig.setTopologyAwareEnabled(false);
}
private ObjectName getMbeanName(String clusterName) throws MalformedObjectNameException {
String clusterBeanName = String.format("%s=%s", CLUSTER_DN_KEY, clusterName);
return new ObjectName(
String.format("%s:%s", MonitorDomainNames.ClusterStatus.name(), clusterBeanName));
}
private ObjectName getResourceMbeanName(String clusterName, String resourceName)
throws MalformedObjectNameException {
String resourceBeanName =
String.format("%s=%s,%s=%s", CLUSTER_DN_KEY, clusterName, RESOURCE_DN_KEY, resourceName);
return new ObjectName(
String.format("%s:%s", MonitorDomainNames.ClusterStatus.name(), resourceBeanName));
}
private void setDomainId(String instanceName, ConfigAccessor configAccessor) {
String domain = String.format("Rack=%s, Instance=%s", instanceName, instanceName);
InstanceConfig instanceConfig = configAccessor.getInstanceConfig(CLUSTER_NAME, instanceName);
instanceConfig.setDomain(domain);
configAccessor.setInstanceConfig(CLUSTER_NAME, instanceName, instanceConfig);
}
private void setInstanceEnable(String instanceName, boolean enabled,
ConfigAccessor configAccessor) {
InstanceConfig instanceConfig = configAccessor.getInstanceConfig(CLUSTER_NAME, instanceName);
instanceConfig.setInstanceEnabled(enabled);
configAccessor.setInstanceConfig(CLUSTER_NAME, instanceName, instanceConfig);
}
private void checkRebalanceFailureGauge(final boolean expectFailure) throws Exception {
boolean result = TestHelper.verify(() -> {
try {
Long value =
(Long) _server.getAttribute(getMbeanName(CLUSTER_NAME), "RebalanceFailureGauge");
return value != null && (value == 1) == expectFailure;
} catch (Exception e) {
return false;
}
}, TIMEOUT);
Assert.assertTrue(result);
}
private void checkResourceBestPossibleCalFailureState(
final ResourceMonitor.RebalanceStatus expectedState, final String resourceName)
throws Exception {
boolean result = TestHelper.verify(() -> {
try {
String state = (String) _server
.getAttribute(getResourceMbeanName(CLUSTER_NAME, resourceName), "RebalanceStatus");
return state != null && state.equals(expectedState.name());
} catch (Exception e) {
return false;
}
}, TIMEOUT);
Assert.assertTrue(result);
}
private void pollForError(final HelixDataAccessor accessor, final PropertyKey key)
throws Exception {
boolean result = TestHelper.verify(() -> {
/*
* TODO re-enable this check when we start recording rebalance error again
* return accessor.getProperty(key) != null;
*/
return true;
}, TIMEOUT);
Assert.assertTrue(result);
}
}
| 9,514 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestEnablePartitionDuringDisable.java
|
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.HelixManager;
import org.apache.helix.NotificationContext;
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.mock.participant.MockTransition;
import org.apache.helix.model.Message;
import org.apache.helix.tools.ClusterSetup;
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 TestEnablePartitionDuringDisable extends ZkTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestEnablePartitionDuringDisable.class);
class EnablePartitionTransition extends MockTransition {
int slaveToOfflineCnt = 0;
int offlineToSlave = 0;
@Override
public void doTransition(Message message, NotificationContext context) {
HelixManager manager = context.getManager();
String clusterName = manager.getClusterName();
String instance = message.getTgtName();
String partitionName = message.getPartitionName();
String fromState = message.getFromState();
String toState = message.getToState();
if (instance.equals("localhost_12919") && partitionName.equals("TestDB0_0")) {
if (fromState.equals("SLAVE") && toState.equals("OFFLINE")) {
slaveToOfflineCnt++;
try {
String command = "--zkSvr " + ZK_ADDR + " --enablePartition true " + clusterName
+ " localhost_12919 TestDB0 TestDB0_0";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
} catch (Exception e) {
LOG.error("Exception in cluster setup", e);
}
} else if (slaveToOfflineCnt > 0 && fromState.equals("OFFLINE")
&& toState.equals("SLAVE")) {
offlineToSlave++;
}
}
}
}
@Test
public void testEnablePartitionDuringDisable() throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
10, // partitions per resource
5, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
// start participants
EnablePartitionTransition transition = new EnablePartitionTransition();
MockParticipantManager[] participants = new MockParticipantManager[5];
for (int i = 0; i < 5; i++) {
String instanceName = "localhost_" + (12918 + i);
if (instanceName.equals("localhost_12919")) {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].setTransition(transition);
} else {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
}
participants[i].syncStart();
}
boolean result = ClusterStateVerifier.verifyByZkCallback(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// disable partitions
String command = "--zkSvr " + ZK_ADDR + " --enablePartition false " + clusterName
+ " localhost_12919 TestDB0 TestDB0_0";
ClusterSetup.processCommandLineArgs(command.split("\\s+"));
// ensure we get 1 slaveToOffline and 1 offlineToSlave after disable partition
long startT = System.currentTimeMillis();
while (System.currentTimeMillis() - startT < 10000) // retry in 5s
{
if (transition.slaveToOfflineCnt > 0 && transition.offlineToSlave > 0) {
break;
}
Thread.sleep(100);
}
long endT = System.currentTimeMillis();
System.out.println("1 disable and re-enable took: " + (endT - startT) + "ms");
Assert.assertEquals(transition.slaveToOfflineCnt, 1, "should get 1 slaveToOffline transition");
Assert.assertEquals(transition.offlineToSlave, 1, "should get 1 offlineToSlave transition");
// clean up
controller.syncStop();
for (int i = 0; i < 5; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,515 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestStatusUpdate.java
|
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.List;
import java.util.Map;
import java.util.Set;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.ExternalView;
import org.apache.helix.util.StatusUpdateUtil;
import org.testng.Assert;
public class TestStatusUpdate extends ZkStandAloneCMTestBase {
// For now write participant StatusUpdates to log4j.
// TODO: Need to investigate another data channel to report to controller and re-enable
// this test
// @Test
public void testParticipantStatusUpdates() throws Exception {
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor(_gZkClient));
Builder keyBuilder = accessor.keyBuilder();
List<ExternalView> extViews = accessor.getChildValues(keyBuilder.externalViews(), true);
Assert.assertNotNull(extViews);
for (ExternalView extView : extViews) {
String resourceName = extView.getResourceName();
Set<String> partitionSet = extView.getPartitionSet();
for (String partition : partitionSet) {
Map<String, String> stateMap = extView.getStateMap(partition);
for (String instance : stateMap.keySet()) {
String state = stateMap.get(instance);
StatusUpdateUtil.StatusUpdateContents statusUpdates =
StatusUpdateUtil.StatusUpdateContents.getStatusUpdateContents(accessor, instance,
resourceName, partition);
Map<String, StatusUpdateUtil.TaskStatus> taskMessages = statusUpdates.getTaskMessages();
List<StatusUpdateUtil.Transition> transitions = statusUpdates.getTransitions();
if (state.equals("MASTER")) {
Assert.assertEquals(transitions.size() >= 2, true, "Invalid number of transitions");
StatusUpdateUtil.Transition lastTransition = transitions.get(transitions.size() - 1);
StatusUpdateUtil.Transition prevTransition = transitions.get(transitions.size() - 2);
Assert.assertEquals(taskMessages.get(lastTransition.getMsgID()),
StatusUpdateUtil.TaskStatus.COMPLETED, "Incomplete transition");
Assert.assertEquals(taskMessages.get(prevTransition.getMsgID()),
StatusUpdateUtil.TaskStatus.COMPLETED, "Incomplete transition");
Assert.assertEquals(lastTransition.getFromState(), "SLAVE", "Invalid State");
Assert.assertEquals(lastTransition.getToState(), "MASTER", "Invalid State");
} else if (state.equals("SLAVE")) {
Assert.assertEquals(transitions.size() >= 1, true, "Invalid number of transitions");
StatusUpdateUtil.Transition lastTransition = transitions.get(transitions.size() - 1);
Assert.assertEquals(lastTransition.getFromState().equals("MASTER")
|| lastTransition.getFromState().equals("OFFLINE"), true, "Invalid transition");
Assert.assertEquals(lastTransition.getToState(), "SLAVE", "Invalid State");
}
}
}
}
}
}
| 9,516 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/DelayedTransitionBase.java
|
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 org.apache.helix.NotificationContext;
import org.apache.helix.mock.participant.MockTransition;
import org.apache.helix.model.Message;
public class DelayedTransitionBase extends MockTransition {
protected static long _delay = 0;
public DelayedTransitionBase() {}
public DelayedTransitionBase(long delay) {
_delay = delay;
}
public static void setDelay(long delay) {
_delay = delay;
}
@Override
public void doTransition(Message message, NotificationContext context)
throws InterruptedException {
if (_delay > 0) {
Thread.sleep(_delay);
}
}
}
| 9,517 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestDisableResource.java
|
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 java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.helix.BaseDataAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestDisableResource extends ZkUnitTestBase {
private static final int N = 2;
private static final int PARTITION_NUM = 1;
@Test
public void testDisableResourceInSemiAutoMode() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
PARTITION_NUM, // partitions per resource
N, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// start participants
MockParticipantManager[] participants = new MockParticipantManager[N];
for (int i = 0; i < N; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
// Check for connection status
HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
boolean result = TestHelper.verify(() -> {
List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
for (int i = 0; i < N; i++) {
if (!participants[i].isConnected()
|| !liveInstances.contains(participants[i].getInstanceName())) {
return false;
}
}
return true;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
result = ClusterStateVerifier.verifyByZkCallback(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// Disable TestDB0
enableResource(clusterName, false);
result =
TestHelper.verify(
() -> !_gSetupTool.getClusterManagementTool()
.getResourceIdealState(clusterName, "TestDB0").isEnabled(),
TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
checkExternalView(clusterName);
// Re-enable TestDB0
enableResource(clusterName, true);
result =
TestHelper.verify(
() -> _gSetupTool.getClusterManagementTool()
.getResourceIdealState(clusterName, "TestDB0").isEnabled(),
TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// Clean up
controller.syncStop();
for (int i = 0; i < N; i++) {
participants[i].syncStop();
}
result = TestHelper.verify(() -> {
if (accessor.getPropertyStat(accessor.keyBuilder().controllerLeader()) != null) {
return false;
}
List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
for (int i = 0; i < N; i++) {
if (participants[i].isConnected()
|| liveInstances.contains(participants[i].getInstanceName())) {
return false;
}
}
return true;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testDisableResourceInFullAutoMode() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
PARTITION_NUM, // partitions per resource
N, // number of nodes
2, // replicas
"MasterSlave", RebalanceMode.FULL_AUTO, true); // do rebalance
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// start participants
MockParticipantManager[] participants = new MockParticipantManager[N];
for (int i = 0; i < N; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
// Check for connection status
HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
boolean result = TestHelper.verify(() -> {
List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
for (int i = 0; i < N; i++) {
if (!participants[i].isConnected()
|| !liveInstances.contains(participants[i].getInstanceName())) {
return false;
}
}
return true;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
// disable TestDB0
enableResource(clusterName, false);
result =
TestHelper.verify(
() -> !_gSetupTool.getClusterManagementTool()
.getResourceIdealState(clusterName, "TestDB0").isEnabled(),
TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
checkExternalView(clusterName);
// Re-enable TestDB0
enableResource(clusterName, true);
result =
TestHelper.verify(
() -> _gSetupTool.getClusterManagementTool()
.getResourceIdealState(clusterName, "TestDB0").isEnabled(),
TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// Clean up
controller.syncStop();
for (int i = 0; i < N; i++) {
participants[i].syncStop();
}
result = TestHelper.verify(() -> {
if (accessor.getPropertyStat(accessor.keyBuilder().controllerLeader()) != null) {
return false;
}
List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
for (int i = 0; i < N; i++) {
if (participants[i].isConnected()
|| liveInstances.contains(participants[i].getInstanceName())) {
return false;
}
}
return true;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
TestHelper.dropCluster(clusterName, _gZkClient);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testDisableResourceInCustomMode() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
PARTITION_NUM, // partitions per resource
N, // number of nodes
2, // replicas
"MasterSlave", RebalanceMode.CUSTOMIZED, true); // do rebalance
// set up custom ideal-state
HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0"));
idealState.setPartitionState("TestDB0_0", "localhost_12918", "SLAVE");
idealState.setPartitionState("TestDB0_0", "localhost_12919", "SLAVE");
accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState);
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// start participants
MockParticipantManager[] participants = new MockParticipantManager[N];
for (int i = 0; i < N; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
// Check for connection status
boolean result = TestHelper.verify(() -> {
List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
for (int i = 0; i < N; i++) {
if (!participants[i].isConnected()
|| !liveInstances.contains(participants[i].getInstanceName())) {
return false;
}
}
return true;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
BestPossibleExternalViewVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR)
.setZkClient(_gZkClient).build();
// Disable TestDB0
enableResource(clusterName, false);
// Check that the resource has been disabled
result =
TestHelper.verify(
() -> !_gSetupTool.getClusterManagementTool()
.getResourceIdealState(clusterName, "TestDB0").isEnabled(),
TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
Assert.assertTrue(verifier.verifyByPolling());
checkExternalView(clusterName);
// Re-enable TestDB0
enableResource(clusterName, true);
// Check that the resource has been enabled
result =
TestHelper.verify(
() -> _gSetupTool.getClusterManagementTool()
.getResourceIdealState(clusterName, "TestDB0").isEnabled(),
TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
Assert.assertTrue(verifier.verifyByPolling());
// Clean up
controller.syncStop();
for (int i = 0; i < N; i++) {
participants[i].syncStop();
}
result = TestHelper.verify(() -> {
if (accessor.getPropertyStat(accessor.keyBuilder().controllerLeader()) != null) {
return false;
}
List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
for (int i = 0; i < N; i++) {
if (participants[i].isConnected()
|| liveInstances.contains(participants[i].getInstanceName())) {
return false;
}
}
return true;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
TestHelper.dropCluster(clusterName, _gZkClient);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
private void enableResource(String clusterName, boolean enabled) {
HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
admin.enableResource(clusterName, "TestDB0", enabled);
}
/**
* Check all partitions are in OFFLINE state
* @param clusterName
* @throws Exception
*/
private void checkExternalView(String clusterName) throws Exception {
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
final HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
// verify that states of TestDB0 are all OFFLINE
boolean result = TestHelper.verify(() -> {
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
ExternalView extView = accessor.getProperty(keyBuilder.externalView("TestDB0"));
if (extView == null) {
return false;
}
Set<String> partitionSet = extView.getPartitionSet();
if (partitionSet == null || partitionSet.size() != PARTITION_NUM) {
return false;
}
for (String partition : partitionSet) {
Map<String, String> instanceStates = extView.getStateMap(partition);
for (String state : instanceStates.values()) {
if (!"OFFLINE".equals(state)) {
return false;
}
}
}
return true;
}, 10 * 1000);
Assert.assertTrue(result);
}
}
| 9,518 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestReelectedPipelineCorrectness.java
|
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.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.integration.manager.ClusterDistributedController;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* The controller pipeline will only update ideal states, live instances, and instance configs
* when the change. However, if a controller loses leadership and subsequently regains it, we need
* to ensure that the controller can verify its cache. That's what this test is for.
*/
public class TestReelectedPipelineCorrectness extends ZkUnitTestBase {
private static final int CHECK_INTERVAL = 50;
private static final int CHECK_TIMEOUT = 10000;
@Test
public void testReelection() throws Exception {
final int NUM_CONTROLLERS = 2;
final int NUM_PARTICIPANTS = 4;
final int NUM_PARTITIONS = 8;
final int NUM_REPLICAS = 2;
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
ClusterSetup setupTool = new ClusterSetup(ZK_ADDR);
// Set up cluster
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
NUM_PARTITIONS, // partitions per resource
NUM_PARTICIPANTS, // number of nodes
NUM_REPLICAS, // replicas
"MasterSlave", RebalanceMode.FULL_AUTO, true); // do rebalance
// configure distributed controllers
String controllerCluster = clusterName + "_controllers";
setupTool.addCluster(controllerCluster, true);
for (int i = 0; i < NUM_CONTROLLERS; i++) {
setupTool.addInstanceToCluster(controllerCluster, "controller_" + i);
}
setupTool.activateCluster(clusterName, controllerCluster, true);
// start participants
MockParticipantManager[] participants = new MockParticipantManager[NUM_PARTICIPANTS];
for (int i = 0; i < NUM_PARTICIPANTS; i++) {
final String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
// start controllers
ClusterDistributedController[] controllers = new ClusterDistributedController[NUM_CONTROLLERS];
for (int i = 0; i < NUM_CONTROLLERS; i++) {
controllers[i] =
new ClusterDistributedController(ZK_ADDR, controllerCluster, "controller_" + i);
controllers[i].syncStart();
}
Thread.sleep(1000);
// Ensure a balanced cluster
boolean result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// Disable the leader, resulting in a leader election
HelixDataAccessor accessor = participants[0].getHelixDataAccessor();
LiveInstance leader = accessor.getProperty(accessor.keyBuilder().controllerLeader());
int totalWait = 0;
while (leader == null && totalWait < CHECK_TIMEOUT) {
Thread.sleep(CHECK_INTERVAL);
totalWait += CHECK_INTERVAL;
leader = accessor.getProperty(accessor.keyBuilder().controllerLeader());
}
if (totalWait >= CHECK_TIMEOUT) {
Assert.fail("No leader was ever elected!");
}
String leaderId = leader.getId();
String standbyId = (leaderId.equals("controller_0")) ? "controller_1" : "controller_0";
HelixAdmin admin = setupTool.getClusterManagementTool();
admin.enableInstance(controllerCluster, leaderId, false);
// Stop a participant to make sure that the leader election worked
Thread.sleep(500);
participants[0].syncStop();
Thread.sleep(500);
result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// Disable the original standby (leaving 0 active controllers) and kill another participant
admin.enableInstance(controllerCluster, standbyId, false);
Thread.sleep(500);
participants[1].syncStop();
// Also change the ideal state
IdealState idealState = admin.getResourceIdealState(clusterName, "TestDB0");
idealState.setMaxPartitionsPerInstance(1);
admin.setResourceIdealState(clusterName, "TestDB0", idealState);
Thread.sleep(500);
// Also disable an instance in the main cluster
admin.enableInstance(clusterName, "localhost_12920", false);
// Re-enable the original leader
admin.enableInstance(controllerCluster, leaderId, true);
// Now check that both the ideal state and the live instances are adhered to by the rebalance
Thread.sleep(500);
result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// cleanup
for (int i = 0; i < NUM_CONTROLLERS; i++) {
controllers[i].syncStop();
}
for (int i = 2; i < NUM_PARTICIPANTS; i++) {
participants[i].syncStop();
}
TestHelper.dropCluster(clusterName, _gZkClient);
deleteCluster(controllerCluster);
System.out.println("STOP " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,519 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/TestRenamePartition.java
|
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.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
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.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.DefaultIdealStateCalculator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestRenamePartition extends ZkTestBase {
// map from clusterName to participants
private final Map<String, MockParticipantManager[]> _participantMap = new ConcurrentHashMap<>();
// map from clusterName to controllers
private final Map<String, ClusterControllerManager> _controllerMap = new ConcurrentHashMap<>();
@Test()
public void testRenamePartitionAutoIS() throws Exception {
String clusterName = "CLUSTER_" + getShortClassName() + "_auto";
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant start port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
10, // partitions per resource
5, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
startAndVerify(clusterName);
// rename partition name TestDB0_0 tp TestDB0_100
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
Builder keyBuilder = accessor.keyBuilder();
IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0"));
List<String> prioList = idealState.getRecord().getListFields().remove("TestDB0_0");
idealState.getRecord().getListFields().put("TestDB0_100", prioList);
accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState);
boolean result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
stop(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test()
public void testRenamePartitionCustomIS() throws Exception {
String clusterName = "CLUSTER_" + getShortClassName() + "_custom";
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant start port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
10, // partitions per resource
5, // number of nodes
3, // replicas
"MasterSlave", false); // do rebalance
// calculate idealState
List<String> instanceNames = Arrays.asList("localhost_12918", "localhost_12919",
"localhost_12920", "localhost_12921", "localhost_12922");
ZNRecord destIS = DefaultIdealStateCalculator.calculateIdealState(instanceNames, 10, 3 - 1,
"TestDB0", "MASTER", "SLAVE");
IdealState idealState = new IdealState(destIS);
idealState.setRebalanceMode(RebalanceMode.CUSTOMIZED);
idealState.setReplicas("3");
idealState.setStateModelDefRef("MasterSlave");
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
Builder keyBuilder = accessor.keyBuilder();
accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState);
startAndVerify(clusterName);
Map<String, String> stateMap = idealState.getRecord().getMapFields().remove("TestDB0_0");
idealState.getRecord().getMapFields().put("TestDB0_100", stateMap);
accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState);
boolean result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
stop(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
private void startAndVerify(String clusterName) {
MockParticipantManager[] participants = new MockParticipantManager[5];
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
// 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();
}
boolean result = ClusterStateVerifier.verifyByPolling(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
_participantMap.put(clusterName, participants);
_controllerMap.put(clusterName, controller);
}
private void stop(String clusterName) {
ClusterControllerManager controller = _controllerMap.get(clusterName);
if (controller != null) {
controller.syncStop();
}
MockParticipantManager[] participants = _participantMap.get(clusterName);
if (participants != null) {
for (MockParticipantManager participant : participants) {
participant.syncStop();
}
}
deleteCluster(clusterName);
}
}
| 9,520 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoIsWithEmptyMap.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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.PropertyPathBuilder;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.IdealState;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.apache.helix.tools.DefaultIdealStateCalculator;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestAutoIsWithEmptyMap extends ZkTestBase {
@Test
public void testAutoIsWithEmptyMap() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
10, // partitions per resource
5, // number of nodes
3, // replicas
"LeaderStandby", false); // do not rebalance
// calculate and set custom ideal state
String idealPath = PropertyPathBuilder.idealState(clusterName, "TestDB0");
ZNRecord curIdealState = _gZkClient.readData(idealPath);
List<String> instanceNames = new ArrayList<String>(5);
for (int i = 0; i < 5; i++) {
int port = 12918 + i;
instanceNames.add("localhost_" + port);
}
ZNRecord idealState =
DefaultIdealStateCalculator.calculateIdealState(instanceNames, 10, 2, "TestDB0", "LEADER",
"STANDBY");
// System.out.println(idealState);
// curIdealState.setSimpleField(IdealState.IdealStateProperty.IDEAL_STATE_MODE.toString(),
// "CUSTOMIZED");
curIdealState.setSimpleField(IdealState.IdealStateProperty.REPLICAS.toString(), "3");
curIdealState.setListFields(idealState.getListFields());
_gZkClient.writeData(idealPath, curIdealState);
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
// start participants
MockParticipantManager[] participants = new MockParticipantManager[5];
for (int i = 0; i < 5; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
boolean result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// clean up
controller.syncStop();
for (int i = 0; i < 5; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,521 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestClusterInMaintenanceModeWhenReachingMaxPartition.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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.ConfigAccessor;
import org.apache.helix.HelixDataAccessor;
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.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.MaintenanceSignal;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestClusterInMaintenanceModeWhenReachingMaxPartition extends ZkTestBase {
private final int NUM_NODE = 5;
protected static final int START_PORT = 12918;
protected static final int _PARTITIONS = 5;
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected ClusterControllerManager _controller;
private List<MockParticipantManager> _participants = new ArrayList<>();
private ZkHelixClusterVerifier _clusterVerifier;
private List<String> _testDBs = new ArrayList<>();
private HelixDataAccessor _dataAccessor;
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
// start dummy participants
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, storageNodeName);
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
_clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
_dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
}
private String[] TestStateModels = {
BuiltInStateModelDefinitions.MasterSlave.name(),
BuiltInStateModelDefinitions.OnlineOffline.name(),
BuiltInStateModelDefinitions.LeaderStandby.name()
};
@Test
public void testDisableCluster() throws Exception {
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setMaxPartitionsPerInstance(10);
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
int i = 0;
for (String stateModel : TestStateModels) {
String db = "Test-DB-" + i++;
int replica = 3;
createResourceWithDelayedRebalance(CLUSTER_NAME, db, stateModel, _PARTITIONS, replica,
replica, -1);
_testDBs.add(db);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
MaintenanceSignal maintenanceSignal =
_dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance());
Assert.assertNull(maintenanceSignal);
for (i = 2; i < NUM_NODE; i++) {
_participants.get(i).syncStop();
}
boolean result = TestHelper.verify(() -> {
MaintenanceSignal ms = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance());
return ms != null && ms.getReason() != null;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
}
@AfterClass
public void afterClass() throws Exception {
/*
* shutdown order: 1) disconnect the controller 2) disconnect participants
*/
_controller.syncStop();
for (MockParticipantManager participant : _participants) {
participant.syncStop();
}
deleteCluster(CLUSTER_NAME);
System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,522 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalance.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.TestHelper;
import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
import org.apache.helix.controller.rebalancer.AutoRebalancer;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
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.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.ZkVerifier;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.apache.helix.zookeeper.api.client.HelixZkClient;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.zookeeper.impl.client.ZkClient;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestAutoRebalance extends ZkStandAloneCMTestBase {
private String db2 = TEST_DB + "2";
private String _tag = "SSDSSD";
private Set<MockParticipantManager> _extraParticipants;
@Override
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
// Cache references to mock participants for teardown
_extraParticipants = new HashSet<>();
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL,
RebalanceMode.FULL_AUTO.name());
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db2, _PARTITIONS, "OnlineOffline",
RebalanceMode.FULL_AUTO.name());
setupAutoRebalancer();
for (int i = 0; i < NODE_NR; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
}
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, _replica);
for (int i = 0; i < 3; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.getClusterManagementTool().addInstanceTag(CLUSTER_NAME, storageNodeName, _tag);
}
_gSetupTool.rebalanceCluster(CLUSTER_NAME, db2, 1, "ucpx", _tag);
// start dummy participants
for (int i = 0; i < NODE_NR; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
participant.syncStart();
_participants[i] = participant;
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
Thread.sleep(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
boolean result = ClusterStateVerifier
.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB));
Assert.assertTrue(result);
}
@Override
@AfterClass
public void afterClass() throws Exception {
for (MockParticipantManager participantManager : _extraParticipants) {
participantManager.syncStop();
}
super.afterClass();
}
@Test()
public void testDropResourceAutoRebalance() throws Exception {
// add a resource to be dropped
_gSetupTool.addResourceToCluster(CLUSTER_NAME, "MyDB", _PARTITIONS, "OnlineOffline",
RebalanceMode.FULL_AUTO.name());
setupAutoRebalancer();
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "MyDB", 1);
Thread.sleep(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
boolean result = ClusterStateVerifier
.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, "MyDB"));
Assert.assertTrue(result);
String command = "-zkSvr " + ZK_ADDR + " -dropResource " + CLUSTER_NAME + " " + "MyDB";
ClusterSetup.processCommandLineArgs(command.split(" "));
TestHelper.verifyWithTimeout("verifyEmptyCurStateAndExtView", 30 * 1000, CLUSTER_NAME, "MyDB",
TestHelper.setOf("localhost_12918", "localhost_12919", "localhost_12920", "localhost_12921",
"localhost_12922"),
ZK_ADDR);
// add a resource to be dropped
_gSetupTool.addResourceToCluster(CLUSTER_NAME, "MyDB2", _PARTITIONS, "MasterSlave",
RebalanceMode.FULL_AUTO.name());
setupAutoRebalancer();
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "MyDB2", 1);
result = ClusterStateVerifier
.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, "MyDB2"));
Assert.assertTrue(result);
command = "-zkSvr " + ZK_ADDR + " -dropResource " + CLUSTER_NAME + " " + "MyDB2";
ClusterSetup.processCommandLineArgs(command.split(" "));
TestHelper.verifyWithTimeout("verifyEmptyCurStateAndExtView", 30 * 1000, CLUSTER_NAME, "MyDB2",
TestHelper.setOf("localhost_12918", "localhost_12919", "localhost_12920", "localhost_12921",
"localhost_12922"),
ZK_ADDR);
}
@Test()
public void testAutoRebalance() throws Exception {
// kill 1 node
_participants[0].syncStop();
ZkHelixClusterVerifier verifierClusterTestDb = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME)
.setResources(new HashSet<>(Collections.singleton(TEST_DB)))
.setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifierClusterTestDb.verifyByPolling());
ZkHelixClusterVerifier verifierClusterDb2 = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME)
.setResources(new HashSet<>(Collections.singleton(db2)))
.setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifierClusterDb2.verifyByPolling());
// add 2 nodes
for (int i = 0; i < 2; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (1000 + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, storageNodeName.replace(':', '_'));
_extraParticipants.add(participant);
participant.syncStart();
}
Assert.assertTrue(verifierClusterTestDb.verifyByPolling());
Assert.assertTrue(verifierClusterDb2.verifyByPolling());
HelixDataAccessor accessor =
new ZKHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor<>(_gZkClient));
Builder keyBuilder = accessor.keyBuilder();
ExternalView ev = accessor.getProperty(keyBuilder.externalView(db2));
Set<String> instancesSet = new HashSet<>();
for (String partitionName : ev.getRecord().getMapFields().keySet()) {
Map<String, String> assignmentMap = ev.getRecord().getMapField(partitionName);
instancesSet.addAll(assignmentMap.keySet());
}
Assert.assertEquals(instancesSet.size(), 2);
}
static boolean verifyBalanceExternalView(ZNRecord externalView, int partitionCount,
String masterState, int replica, int instances) {
if (externalView == null) {
return false;
}
Map<String, Integer> masterPartitionsCountMap = new HashMap<>();
for (String partitionName : externalView.getMapFields().keySet()) {
Map<String, String> assignmentMap = externalView.getMapField(partitionName);
// Assert.assertTrue(assignmentMap.size() >= replica);
for (String instance : assignmentMap.keySet()) {
if (assignmentMap.get(instance).equals(masterState)) {
if (!masterPartitionsCountMap.containsKey(instance)) {
masterPartitionsCountMap.put(instance, 0);
}
masterPartitionsCountMap.put(instance, masterPartitionsCountMap.get(instance) + 1);
}
}
}
int perInstancePartition = partitionCount / instances;
int totalCount = 0;
for (String instanceName : masterPartitionsCountMap.keySet()) {
int instancePartitionCount = masterPartitionsCountMap.get(instanceName);
totalCount += instancePartitionCount;
if (!(instancePartitionCount == perInstancePartition
|| instancePartitionCount == perInstancePartition + 1)) {
return false;
}
if (instancePartitionCount == perInstancePartition + 1) {
if (partitionCount % instances == 0) {
return false;
}
}
}
return partitionCount == totalCount;
}
// Ensure that we are testing the AutoRebalancer.
private void setupAutoRebalancer() {
HelixAdmin admin = _gSetupTool.getClusterManagementTool();
for (String resourceName : _gSetupTool.getClusterManagementTool()
.getResourcesInCluster(CLUSTER_NAME)) {
IdealState idealState = admin.getResourceIdealState(CLUSTER_NAME, resourceName);
idealState.setRebalancerClassName(AutoRebalancer.class.getName());
admin.setResourceIdealState(CLUSTER_NAME, resourceName, idealState);
}
}
public static class ExternalViewBalancedVerifier implements ZkVerifier {
String _clusterName;
String _resourceName;
HelixZkClient _client;
public ExternalViewBalancedVerifier(HelixZkClient client, String clusterName,
String resourceName) {
_clusterName = clusterName;
_resourceName = resourceName;
_client = client;
}
@Override
public boolean verify() {
HelixDataAccessor accessor =
new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<>(_gZkClient));
Builder keyBuilder = accessor.keyBuilder();
int numberOfPartitions;
try {
numberOfPartitions = accessor.getProperty(keyBuilder.idealStates(_resourceName)).getRecord()
.getListFields().size();
} catch (Exception e) {
return false;
}
ResourceControllerDataProvider cache = new ResourceControllerDataProvider();
cache.refresh(accessor);
IdealState idealState = cache.getIdealState(_resourceName);
if (idealState == null) {
return false;
}
String masterValue =
cache.getStateModelDef(idealState.getStateModelDefRef()).getStatesPriorityList().get(0);
int replicas = Integer.parseInt(cache.getIdealState(_resourceName).getReplicas());
String instanceGroupTag = cache.getIdealState(_resourceName).getInstanceGroupTag();
int instances = 0;
for (String liveInstanceName : cache.getLiveInstances().keySet()) {
if (cache.getInstanceConfigMap().get(liveInstanceName).containsTag(instanceGroupTag)) {
instances++;
}
}
if (instances == 0) {
instances = cache.getLiveInstances().size();
}
ExternalView ev = accessor.getProperty(keyBuilder.externalView(_resourceName));
if (ev == null) {
return false;
}
return verifyBalanceExternalView(ev.getRecord(), numberOfPartitions, masterValue, replicas,
instances);
}
@Override
public ZkClient getZkClient() {
return (ZkClient) _client;
}
@Override
public String getClusterName() {
return _clusterName;
}
}
}
| 9,523 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalancePartitionLimit.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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 java.util.HashMap;
import java.util.Map;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
import org.apache.helix.controller.rebalancer.AutoRebalancer;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
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.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.ZkVerifier;
import org.apache.helix.zookeeper.api.client.HelixZkClient;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.zookeeper.impl.client.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestAutoRebalancePartitionLimit extends ZkStandAloneCMTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestAutoRebalancePartitionLimit.class);
@Override
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, 100, "OnlineOffline",
RebalanceMode.FULL_AUTO.name(), 0, 25);
// Ensure that we are testing the AutoRebalancer.
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, TEST_DB);
idealState.setRebalancerClassName(AutoRebalancer.class.getName());
_gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, TEST_DB, idealState);
for (int i = 0; i < NODE_NR; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
}
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, 1);
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
}
@Test
public void testAutoRebalanceWithMaxParticipantCapacity() throws InterruptedException {
HelixManager manager = _controller;
HelixDataAccessor accessor = manager.getHelixDataAccessor();
// start dummy participants
for (int i = 0; i < NODE_NR; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
_participants[i].syncStart();
Thread.sleep(100);
boolean result = ClusterStateVerifier.verifyByPolling(
new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB), 10000, 100);
Assert.assertTrue(result);
ExternalView ev =
manager.getHelixDataAccessor().getProperty(accessor.keyBuilder().externalView(TEST_DB));
if (i < 3) {
Assert.assertEquals(ev.getPartitionSet().size(), 25 * (i + 1));
} else {
Assert.assertEquals(ev.getPartitionSet().size(), 100);
}
}
boolean result = ClusterStateVerifier
.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB));
Assert.assertTrue(result);
}
@Test()
public void testAutoRebalanceWithMaxPartitionPerNode() {
HelixManager manager = _controller;
// kill 1 node
_participants[0].syncStop();
boolean result = ClusterStateVerifier
.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB));
Assert.assertTrue(result);
HelixDataAccessor accessor = manager.getHelixDataAccessor();
ExternalView ev =
manager.getHelixDataAccessor().getProperty(accessor.keyBuilder().externalView(TEST_DB));
Assert.assertEquals(ev.getPartitionSet().size(), 100);
_participants[1].syncStop();
result = ClusterStateVerifier
.verifyByPolling(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB));
Assert.assertTrue(result);
ev = manager.getHelixDataAccessor().getProperty(accessor.keyBuilder().externalView(TEST_DB));
Assert.assertEquals(ev.getPartitionSet().size(), 75);
// add 2 nodes
MockParticipantManager[] newParticipants = new MockParticipantManager[2];
for (int i = 0; i < 2; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (1000 + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
String newInstanceName = storageNodeName.replace(':', '_');
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, newInstanceName);
newParticipants[i] = participant;
participant.syncStart();
}
Assert.assertTrue(ClusterStateVerifier.verifyByPolling(
new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB), 10000, 100));
// Clean up the extra mock participants
for (MockParticipantManager participant : newParticipants) {
if (participant != null && participant.isConnected()) {
participant.syncStop();
}
}
}
private static boolean verifyBalanceExternalView(ZNRecord externalView, int partitionCount,
String masterState, int replica, int instances, int maxPerInstance) {
Map<String, Integer> masterPartitionsCountMap = new HashMap<>();
for (String partitionName : externalView.getMapFields().keySet()) {
Map<String, String> assignmentMap = externalView.getMapField(partitionName);
for (String instance : assignmentMap.keySet()) {
if (assignmentMap.get(instance).equals(masterState)) {
if (!masterPartitionsCountMap.containsKey(instance)) {
masterPartitionsCountMap.put(instance, 0);
}
masterPartitionsCountMap.put(instance, masterPartitionsCountMap.get(instance) + 1);
}
}
}
int perInstancePartition = partitionCount / instances;
int totalCount = 0;
for (String instanceName : masterPartitionsCountMap.keySet()) {
int instancePartitionCount = masterPartitionsCountMap.get(instanceName);
totalCount += instancePartitionCount;
if (!(instancePartitionCount == perInstancePartition
|| instancePartitionCount == perInstancePartition + 1
|| instancePartitionCount == maxPerInstance)) {
return false;
}
if (instancePartitionCount == maxPerInstance) {
continue;
}
if (instancePartitionCount == perInstancePartition + 1) {
if (partitionCount % instances == 0) {
return false;
}
}
}
if (totalCount == maxPerInstance * instances) {
return true;
}
return partitionCount == totalCount;
}
public static class ExternalViewBalancedVerifier implements ZkVerifier {
String _clusterName;
String _resourceName;
HelixZkClient _client;
ExternalViewBalancedVerifier(HelixZkClient client, String clusterName, String resourceName) {
_clusterName = clusterName;
_resourceName = resourceName;
_client = client;
}
@Override
public boolean verify() {
HelixDataAccessor accessor =
new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<>(_gZkClient));
Builder keyBuilder = accessor.keyBuilder();
int numberOfPartitions = accessor.getProperty(keyBuilder.idealStates(_resourceName))
.getRecord().getListFields().size();
ResourceControllerDataProvider cache = new ResourceControllerDataProvider();
cache.refresh(accessor);
String masterValue =
cache.getStateModelDef(cache.getIdealState(_resourceName).getStateModelDefRef())
.getStatesPriorityList().get(0);
int replicas = Integer.parseInt(cache.getIdealState(_resourceName).getReplicas());
try {
return verifyBalanceExternalView(
accessor.getProperty(keyBuilder.externalView(_resourceName)).getRecord(),
numberOfPartitions, masterValue, replicas, cache.getLiveInstances().size(),
cache.getIdealState(_resourceName).getMaxPartitionsPerInstance());
} catch (Exception e) {
LOG.debug("Verify failed", e);
return false;
}
}
@Override
public ZkClient getZkClient() {
return (ZkClient) _client;
}
@Override
public String getClusterName() {
return _clusterName;
}
}
}
| 9,524 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestCustomizedIdealStateRebalancer.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.zookeeper.impl.client.ZkClient;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
import org.apache.helix.controller.rebalancer.Rebalancer;
import org.apache.helix.controller.stages.CurrentStateOutput;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.zookeeper.api.client.HelixZkClient;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.IdealStateProperty;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.ZkVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestCustomizedIdealStateRebalancer extends ZkStandAloneCMTestBase {
String db2 = TEST_DB + "2";
static boolean testRebalancerCreated = false;
static boolean testRebalancerInvoked = false;
public static class TestRebalancer implements Rebalancer<ResourceControllerDataProvider> {
@Override
public void init(HelixManager manager) {
testRebalancerCreated = true;
}
@Override
public IdealState computeNewIdealState(String resourceName, IdealState currentIdealState,
CurrentStateOutput currentStateOutput, ResourceControllerDataProvider clusterData) {
testRebalancerInvoked = true;
List<String> liveNodes = Lists.newArrayList(clusterData.getLiveInstances().keySet());
int i = 0;
for (String partition : currentIdealState.getPartitionSet()) {
int index = i++ % liveNodes.size();
String instance = liveNodes.get(index);
currentIdealState.getPreferenceList(partition).clear();
currentIdealState.getPreferenceList(partition).add(instance);
currentIdealState.getInstanceStateMap(partition).clear();
currentIdealState.getInstanceStateMap(partition).put(instance, "MASTER");
}
currentIdealState.setReplicas("1");
return currentIdealState;
}
}
@Test
public void testCustomizedIdealStateRebalancer() throws InterruptedException {
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db2, 60, "MasterSlave");
_gSetupTool.addResourceProperty(CLUSTER_NAME, db2,
IdealStateProperty.REBALANCER_CLASS_NAME.toString(),
TestCustomizedIdealStateRebalancer.TestRebalancer.class.getName());
_gSetupTool.addResourceProperty(CLUSTER_NAME, db2, IdealStateProperty.REBALANCE_MODE.toString(),
RebalanceMode.USER_DEFINED.toString());
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db2, 3);
boolean result =
ClusterStateVerifier.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient,
CLUSTER_NAME, db2));
Assert.assertTrue(result);
Thread.sleep(1000);
HelixDataAccessor accessor =
new ZKHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
Builder keyBuilder = accessor.keyBuilder();
ExternalView ev = accessor.getProperty(keyBuilder.externalView(db2));
Assert.assertEquals(ev.getPartitionSet().size(), 60);
for (String partition : ev.getPartitionSet()) {
Assert.assertEquals(ev.getStateMap(partition).size(), 1);
}
IdealState is = accessor.getProperty(keyBuilder.idealStates(db2));
for (String partition : is.getPartitionSet()) {
Assert.assertEquals(is.getPreferenceList(partition).size(), 0);
Assert.assertEquals(is.getInstanceStateMap(partition).size(), 0);
}
Assert.assertTrue(testRebalancerCreated);
Assert.assertTrue(testRebalancerInvoked);
}
public static class ExternalViewBalancedVerifier implements ZkVerifier {
HelixZkClient _client;
String _clusterName;
String _resourceName;
public ExternalViewBalancedVerifier(HelixZkClient client, String clusterName, String resourceName) {
_client = client;
_clusterName = clusterName;
_resourceName = resourceName;
}
@Override
public boolean verify() {
try {
HelixDataAccessor accessor =
new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<ZNRecord>(_client));
Builder keyBuilder = accessor.keyBuilder();
int numberOfPartitions =
accessor.getProperty(keyBuilder.idealStates(_resourceName)).getRecord().getListFields()
.size();
ResourceControllerDataProvider cache = new ResourceControllerDataProvider();
cache.refresh(accessor);
String masterValue =
cache.getStateModelDef(cache.getIdealState(_resourceName).getStateModelDefRef())
.getStatesPriorityList().get(0);
int replicas = Integer.parseInt(cache.getIdealState(_resourceName).getReplicas());
String instanceGroupTag = cache.getIdealState(_resourceName).getInstanceGroupTag();
int instances = 0;
for (String liveInstanceName : cache.getLiveInstances().keySet()) {
if (cache.getInstanceConfigMap().get(liveInstanceName).containsTag(instanceGroupTag)) {
instances++;
}
}
if (instances == 0) {
instances = cache.getLiveInstances().size();
}
return verifyBalanceExternalView(
accessor.getProperty(keyBuilder.externalView(_resourceName)).getRecord(),
numberOfPartitions, masterValue, replicas, instances);
} catch (Exception e) {
return false;
}
}
@Override
public ZkClient getZkClient() {
return (ZkClient) _client;
}
@Override
public String getClusterName() {
return _clusterName;
}
}
static boolean verifyBalanceExternalView(ZNRecord externalView, int partitionCount,
String masterState, int replica, int instances) {
Map<String, Integer> masterPartitionsCountMap = new HashMap<String, Integer>();
for (String partitionName : externalView.getMapFields().keySet()) {
Map<String, String> assignmentMap = externalView.getMapField(partitionName);
// Assert.assertTrue(assignmentMap.size() >= replica);
for (String instance : assignmentMap.keySet()) {
if (assignmentMap.get(instance).equals(masterState)) {
if (!masterPartitionsCountMap.containsKey(instance)) {
masterPartitionsCountMap.put(instance, 0);
}
masterPartitionsCountMap.put(instance, masterPartitionsCountMap.get(instance) + 1);
}
}
}
int perInstancePartition = partitionCount / instances;
int totalCount = 0;
for (String instanceName : masterPartitionsCountMap.keySet()) {
int instancePartitionCount = masterPartitionsCountMap.get(instanceName);
totalCount += instancePartitionCount;
if (!(instancePartitionCount == perInstancePartition || instancePartitionCount == perInstancePartition + 1)) {
return false;
}
if (instancePartitionCount == perInstancePartition + 1) {
if (partitionCount % instances == 0) {
return false;
}
}
}
if (partitionCount != totalCount) {
return false;
}
return true;
}
}
| 9,525 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestZeroReplicaAvoidance.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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 java.util.Map;
import org.apache.helix.ExternalViewChangeListener;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.IdealStateChangeListener;
import org.apache.helix.InstanceType;
import org.apache.helix.NotificationContext;
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.mock.participant.MockTransition;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.Message;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestZeroReplicaAvoidance extends ZkTestBase
implements ExternalViewChangeListener, IdealStateChangeListener {
private final int NUM_NODE = 6;
private final int START_PORT = 12918;
private final String CLASS_NAME = getShortClassName();
private final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
private List<MockParticipantManager> _participants = new ArrayList<>();
private ZkHelixClusterVerifier _clusterVerifier;
private boolean _testSuccess = true;
private boolean _startListen = false;
private ClusterControllerManager _controller;
@BeforeMethod
public void beforeMethod() {
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, storageNodeName);
participant.setTransition(new DelayedTransition());
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
_clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
}
@AfterMethod
public void afterMethod() {
_startListen = false;
if (_controller != null && _controller.isConnected()) {
_controller.syncStop();
}
for (MockParticipantManager participant : _participants) {
if (participant != null && participant.isConnected()) {
participant.syncStop();
}
}
_participants.clear();
deleteCluster(CLUSTER_NAME);
}
private String[] TestStateModels = {
BuiltInStateModelDefinitions.MasterSlave.name(),
BuiltInStateModelDefinitions.OnlineOffline.name(),
BuiltInStateModelDefinitions.LeaderStandby.name()
};
@Test
public void testDelayedRebalancer() throws Exception {
System.out.println("START testDelayedRebalancer at " + new Date(System.currentTimeMillis()));
HelixManager manager =
HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, null, InstanceType.SPECTATOR, ZK_ADDR);
manager.connect();
manager.addExternalViewChangeListener(this);
manager.addIdealStateChangeListener(this);
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
// Start half number of nodes.
int i = 0;
for (; i < NUM_NODE / 2; i++) {
_participants.get(i).syncStart();
}
int replica = 3;
int partition = 30;
for (String stateModel : TestStateModels) {
String db = "Test-DB-" + stateModel;
createResourceWithDelayedRebalance(CLUSTER_NAME, db, stateModel, partition, replica, replica,
0);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling(50000L, 100L));
_startListen = true;
DelayedTransition.setDelay(5);
// add the other half of nodes.
for (; i < NUM_NODE; i++) {
_participants.get(i).syncStart();
}
Assert.assertTrue(_clusterVerifier.verify(70000L));
Assert.assertTrue(_testSuccess);
if (manager.isConnected()) {
manager.disconnect();
}
System.out.println("END testDelayedRebalancer at " + new Date(System.currentTimeMillis()));
}
@Test
public void testWagedRebalancer() throws Exception {
System.out.println("START testWagedRebalancer at " + new Date(System.currentTimeMillis()));
HelixManager manager =
HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, null, InstanceType.SPECTATOR, ZK_ADDR);
manager.connect();
manager.addExternalViewChangeListener(this);
manager.addIdealStateChangeListener(this);
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
// Start half number of nodes.
int i = 0;
for (; i < NUM_NODE / 2; i++) {
_participants.get(i).syncStart();
}
int replica = 3;
int partition = 30;
for (String stateModel : TestStateModels) {
String db = "Test-DB-" + stateModel;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, partition, replica, replica);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling(50000L, 100L));
_startListen = true;
DelayedTransition.setDelay(5);
// add the other half of nodes.
for (; i < NUM_NODE; i++) {
_participants.get(i).syncStart();
}
Assert.assertTrue(_clusterVerifier.verify(70000L));
Assert.assertTrue(_testSuccess);
if (manager.isConnected()) {
manager.disconnect();
}
System.out.println("END testWagedRebalancer at " + new Date(System.currentTimeMillis()));
}
/**
* Validate instances for each partition is on different zone and with necessary tagged
* instances.
*/
private void validateNoZeroReplica(IdealState is, ExternalView ev) {
int replica = is.getReplicaCount(NUM_NODE);
StateModelDefinition stateModelDef =
BuiltInStateModelDefinitions.valueOf(is.getStateModelDefRef()).getStateModelDefinition();
for (String partition : is.getPartitionSet()) {
Map<String, String> evStateMap = ev.getRecord().getMapField(partition);
Map<String, String> isStateMap = is.getInstanceStateMap(partition);
validateMap(is.getResourceName(), partition, replica, evStateMap, stateModelDef);
validateMap(is.getResourceName(), partition, replica, isStateMap, stateModelDef);
}
}
private void validateMap(String resource, String partition, int replica,
Map<String, String> instanceStateMap, StateModelDefinition stateModelDef) {
if (instanceStateMap == null || instanceStateMap.isEmpty()) {
_testSuccess = false;
Assert.fail(
String.format("Resource %s partition %s has no active replica!", resource, partition));
}
if (instanceStateMap.size() < replica) {
_testSuccess = false;
Assert.fail(
String.format("Resource %s partition %s has %d active replica, less than required %d!",
resource, partition, instanceStateMap.size(), replica));
}
Map<String, Integer> stateCountMap = stateModelDef.getStateCountMap(NUM_NODE, replica);
String topState = stateModelDef.getStatesPriorityList().get(0);
if (stateCountMap.get(topState) == 1) {
int topCount = 0;
for (String val : instanceStateMap.values()) {
if (topState.equals(val)) {
topCount++;
}
}
if (topCount > 1) {
_testSuccess = false;
Assert.fail(String.format("Resource %s partition %s has %d replica in %s, more than 1!",
resource, partition, topCount, topState));
}
}
}
@Override
public void onExternalViewChange(List<ExternalView> externalViewList,
NotificationContext changeContext) {
if (!_startListen) {
return;
}
for (ExternalView view : externalViewList) {
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME,
view.getResourceName());
validateNoZeroReplica(is, view);
}
}
@Override
public void onIdealStateChange(List<IdealState> idealStates, NotificationContext changeContext) {
if (!_startListen) {
return;
}
for (IdealState is : idealStates) {
ExternalView view = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, is.getResourceName());
validateNoZeroReplica(is, view);
}
}
private static class DelayedTransition extends MockTransition {
private static long _delay = 0;
public static void setDelay(int delay) {
_delay = delay;
}
@Override
public void doTransition(Message message, NotificationContext context)
throws InterruptedException {
if (_delay > 0) {
Thread.sleep(_delay);
}
}
}
}
| 9,526 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestSemiAutoRebalance.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
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.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.MasterSlaveSMD;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestSemiAutoRebalance extends ZkTestBase {
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected static final int PARTICIPANT_NUMBER = 5;
protected static final int PARTICIPANT_START_PORT = 12918;
protected static final String DB_NAME = "TestDB";
protected static final int PARTITION_NUMBER = 20;
protected static final int REPLICA_NUMBER = 3;
protected static final String STATE_MODEL = "MasterSlave";
protected List<MockParticipantManager> _participants = new ArrayList<>();
protected ClusterControllerManager _controller;
protected HelixDataAccessor _accessor;
protected PropertyKey.Builder _keyBuilder;
@BeforeClass
public void beforeClass() throws InterruptedException {
System.out
.println("START " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, DB_NAME, PARTITION_NUMBER, STATE_MODEL,
IdealState.RebalanceMode.SEMI_AUTO.toString());
_accessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
_keyBuilder = _accessor.keyBuilder();
List<String> instances = new ArrayList<String>();
for (int i = 0; i < PARTICIPANT_NUMBER; i++) {
String instance = PARTICIPANT_PREFIX + "_" + (PARTICIPANT_START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, instance);
instances.add(instance);
}
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, DB_NAME, REPLICA_NUMBER);
// start dummy participants
for (int i = 0; i < PARTICIPANT_NUMBER; i++) {
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instances.get(i));
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME)
.setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
}
@AfterClass
public void afterClass() throws Exception {
_controller.syncStop();
for (MockParticipantManager p : _participants) {
p.syncStop();
}
deleteCluster(CLUSTER_NAME);
System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testAddParticipant() throws InterruptedException {
String newInstance = PARTICIPANT_PREFIX + "_" + (PARTICIPANT_START_PORT + _participants.size());
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, newInstance);
MockParticipantManager newParticipant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, newInstance);
newParticipant.syncStart();
Thread.sleep(1000);
List<String> instances = _accessor.getChildNames(_keyBuilder.instanceConfigs());
Assert.assertEquals(instances.size(), _participants.size() + 1);
Assert.assertTrue(instances.contains(newInstance));
List<String> liveInstances = _accessor.getChildNames(_keyBuilder.liveInstances());
Assert.assertEquals(liveInstances.size(), _participants.size() + 1);
Assert.assertTrue(liveInstances.contains(newInstance));
// nothing for new participant
ExternalView externalView = _accessor.getProperty(_keyBuilder.externalView(DB_NAME));
Assert.assertNotNull(externalView);
for (String partition : externalView.getPartitionSet()) {
Map<String, String> stateMap = externalView.getStateMap(partition);
Assert.assertFalse(stateMap.containsKey(newInstance));
}
// clear
newParticipant.syncStop();
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, newInstance, false);
_gSetupTool.dropInstanceFromCluster(CLUSTER_NAME, newInstance);
instances = _accessor.getChildNames(_keyBuilder.instanceConfigs());
Assert.assertEquals(instances.size(), _participants.size());
liveInstances = _accessor.getChildNames(_keyBuilder.liveInstances());
Assert.assertEquals(liveInstances.size(), _participants.size());
}
@Test(dependsOnMethods = "testAddParticipant")
public void testStopAndReStartParticipant() throws InterruptedException {
MockParticipantManager participant = _participants.get(0);
String instance = participant.getInstanceName();
Map<String, MasterSlaveSMD.States> affectedPartitions =
new HashMap<String, MasterSlaveSMD.States>();
ExternalView externalView = _accessor.getProperty(_keyBuilder.externalView(DB_NAME));
for (String partition : externalView.getPartitionSet()) {
Map<String, String> stateMap = externalView.getStateMap(partition);
if (stateMap.containsKey(instance)) {
affectedPartitions.put(partition, MasterSlaveSMD.States.valueOf(stateMap.get(instance)));
}
}
stopParticipant(participant, affectedPartitions);
// create a new participant
participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instance);
_participants.set(0, participant);
startParticipant(participant, affectedPartitions);
}
private void stopParticipant(MockParticipantManager participant,
Map<String, MasterSlaveSMD.States> affectedPartitions) throws InterruptedException {
participant.syncStop();
Thread.sleep(1000);
ExternalView externalView = _accessor.getProperty(_keyBuilder.externalView(DB_NAME));
// No re-assignment of partition, if a MASTER is removed, one of SLAVE would be prompted
for (Map.Entry<String, MasterSlaveSMD.States> entry : affectedPartitions.entrySet()) {
Map<String, String> stateMap = externalView.getStateMap(entry.getKey());
Assert.assertEquals(stateMap.size(), REPLICA_NUMBER - 1);
Assert.assertTrue(stateMap.values().contains(MasterSlaveSMD.States.MASTER.toString()));
}
}
private void startParticipant(MockParticipantManager participant,
Map<String, MasterSlaveSMD.States> affectedPartitions) throws InterruptedException {
String instance = participant.getInstanceName();
participant.syncStart();
Thread.sleep(2000);
ExternalView externalView = _accessor.getProperty(_keyBuilder.externalView(DB_NAME));
// Everything back to the initial state
for (Map.Entry<String, MasterSlaveSMD.States> entry : affectedPartitions.entrySet()) {
Map<String, String> stateMap = externalView.getStateMap(entry.getKey());
Assert.assertEquals(stateMap.size(), REPLICA_NUMBER);
Assert.assertTrue(stateMap.containsKey(instance));
Assert.assertEquals(stateMap.get(instance), entry.getValue().toString());
}
}
}
| 9,527 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalanceWithDisabledInstance.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.helix.HelixAdmin;
import org.apache.helix.TestHelper;
import org.apache.helix.controller.rebalancer.AutoRebalancer;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestAutoRebalanceWithDisabledInstance extends ZkStandAloneCMTestBase {
private static String TEST_DB_2 = "TestDB2";
@BeforeClass
@Override
public void beforeClass() throws Exception {
super.beforeClass();
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB_2, _PARTITIONS, STATE_MODEL,
RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName());
setupAutoRebalancer();
_gSetupTool.rebalanceResource(CLUSTER_NAME, TEST_DB_2, _replica);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
}
@Test()
public void testDisableEnableInstanceAutoRebalance() throws Exception {
String disabledInstance = _participants[0].getInstanceName();
Set<String> currentPartitions =
getCurrentPartitionsOnInstance(CLUSTER_NAME, TEST_DB_2, disabledInstance);
Assert.assertFalse(currentPartitions.isEmpty());
// disable instance
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, disabledInstance, false);
// check that the instance is really disabled
boolean result = TestHelper.verify(
() -> !_gSetupTool.getClusterManagementTool()
.getInstanceConfig(CLUSTER_NAME, disabledInstance).getInstanceEnabled(),
TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
currentPartitions = getCurrentPartitionsOnInstance(CLUSTER_NAME, TEST_DB_2, disabledInstance);
Assert.assertTrue(currentPartitions.isEmpty());
// enable instance
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, disabledInstance, true);
// check that the instance is really enabled
result = TestHelper.verify(
() -> _gSetupTool.getClusterManagementTool()
.getInstanceConfig(CLUSTER_NAME, disabledInstance).getInstanceEnabled(),
TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
currentPartitions = getCurrentPartitionsOnInstance(CLUSTER_NAME, TEST_DB_2, disabledInstance);
Assert.assertFalse(currentPartitions.isEmpty());
}
@Test()
public void testAddDisabledInstanceAutoRebalance() throws Exception {
// add disabled instance.
String nodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + NODE_NR);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, nodeName);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, nodeName);
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, nodeName, false);
// check that the instance is really disabled
boolean result =
TestHelper
.verify(
() -> !_gSetupTool.getClusterManagementTool()
.getInstanceConfig(CLUSTER_NAME, nodeName).getInstanceEnabled(),
TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
participant.syncStart();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
Set<String> currentPartitions =
getCurrentPartitionsOnInstance(CLUSTER_NAME, TEST_DB_2, nodeName);
Assert.assertTrue(currentPartitions.isEmpty());
// enable instance
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, nodeName, true);
// check that the instance is really enabled
result =
TestHelper
.verify(
() -> _gSetupTool.getClusterManagementTool()
.getInstanceConfig(CLUSTER_NAME, nodeName).getInstanceEnabled(),
TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
currentPartitions = getCurrentPartitionsOnInstance(CLUSTER_NAME, TEST_DB_2, nodeName);
Assert.assertFalse(currentPartitions.isEmpty());
// Kill the newly added MockParticipant so that the cluster could be cleaned up
participant.syncStop();
}
private Set<String> getCurrentPartitionsOnInstance(String cluster, String dbName,
String instance) {
HelixAdmin admin = _gSetupTool.getClusterManagementTool();
Set<String> partitionSet = new HashSet<>();
ExternalView ev = admin.getResourceExternalView(cluster, dbName);
for (String partition : ev.getRecord().getMapFields().keySet()) {
Map<String, String> assignments = ev.getRecord().getMapField(partition);
for (String ins : assignments.keySet()) {
if (ins.equals(instance)) {
partitionSet.add(partition);
}
}
}
return partitionSet;
}
// Ensure that we are testing the AutoRebalancer.
private void setupAutoRebalancer() {
HelixAdmin admin = _gSetupTool.getClusterManagementTool();
for (String resourceName : _gSetupTool.getClusterManagementTool()
.getResourcesInCluster(CLUSTER_NAME)) {
IdealState idealState = admin.getResourceIdealState(CLUSTER_NAME, resourceName);
idealState.setRebalancerClassName(AutoRebalancer.class.getName());
admin.setResourceIdealState(CLUSTER_NAME, resourceName, idealState);
}
}
}
| 9,528 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestCustomRebalancer.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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 com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
import org.apache.helix.controller.rebalancer.CustomRebalancer;
import org.apache.helix.controller.stages.CurrentStateOutput;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.OnlineOfflineSMD;
import org.apache.helix.model.Partition;
import org.apache.helix.model.Resource;
import org.apache.helix.model.ResourceAssignment;
import org.apache.helix.model.StateModelDefinition;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TestCustomRebalancer {
/**
* This test was written because there is an edge case where an instance becomes disabled while a
* partition is bootstrapping by way of pending
* messages.
* The newly bootstrapped partitions never get further state transitions because the instance
* won't ever get added to instanceStateMap (this issue has been fixed). In other words, if there
* are mapping changes while a partition is bootstrapping, the final state should go into the best
* possible mapping for clusters to converge correctly.
*/
@Test
public void testDisabledBootstrappingPartitions() {
String resourceName = "Test";
String partitionName = "Test0";
String instanceName = "localhost";
String stateModelName = "OnlineOffline";
StateModelDefinition stateModelDef = new OnlineOfflineSMD();
IdealState idealState = new IdealState(resourceName);
idealState.setStateModelDefRef(stateModelName);
idealState.setPartitionState(partitionName, instanceName, "ONLINE");
Resource resource = new Resource(resourceName);
resource.addPartition(partitionName);
CustomRebalancer customRebalancer = new CustomRebalancer();
ResourceControllerDataProvider cache = mock(ResourceControllerDataProvider.class);
when(cache.getStateModelDef(stateModelName)).thenReturn(stateModelDef);
when(cache.getDisabledInstancesForPartition(resource.getResourceName(), partitionName))
.thenReturn(ImmutableSet.of(instanceName));
when(cache.getLiveInstances())
.thenReturn(ImmutableMap.of(instanceName, new LiveInstance(instanceName)));
CurrentStateOutput currOutput = new CurrentStateOutput();
ResourceAssignment resourceAssignment =
customRebalancer.computeBestPossiblePartitionState(cache, idealState, resource, currOutput);
Assert.assertEquals(
resourceAssignment.getReplicaMap(new Partition(partitionName)).get(instanceName),
stateModelDef.getInitialState());
}
}
| 9,529 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestMixedModeAutoRebalance.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.NotificationContext;
import org.apache.helix.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.controller.rebalancer.strategy.CrushRebalanceStrategy;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.mock.participant.MockMSModelFactory;
import org.apache.helix.mock.participant.MockMSStateModel;
import org.apache.helix.mock.participant.MockTransition;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.Message;
import org.apache.helix.model.ResourceConfig;
import org.apache.helix.participant.statemachine.StateModelInfo;
import org.apache.helix.participant.statemachine.Transition;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestMixedModeAutoRebalance extends ZkTestBase {
private final int NUM_NODE = 5;
private static final int START_PORT = 12918;
private static final int _PARTITIONS = 5;
private final String CLASS_NAME = getShortClassName();
private final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
private ClusterControllerManager _controller;
private List<MockParticipantManager> _participants = new ArrayList<>();
private int _replica = 3;
private ZkHelixClusterVerifier _clusterVerifier;
private ConfigAccessor _configAccessor;
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
// start dummy participants
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, storageNodeName);
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
_clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
_configAccessor = new ConfigAccessor(_gZkClient);
}
@DataProvider(name = "stateModels")
public static Object [][] stateModels() {
return new Object[][] { {BuiltInStateModelDefinitions.MasterSlave.name(), true, CrushRebalanceStrategy.class.getName()},
{BuiltInStateModelDefinitions.OnlineOffline.name(), true, CrushRebalanceStrategy.class.getName()},
{BuiltInStateModelDefinitions.LeaderStandby.name(), true, CrushRebalanceStrategy.class.getName()},
{BuiltInStateModelDefinitions.MasterSlave.name(), false, CrushRebalanceStrategy.class.getName()},
{BuiltInStateModelDefinitions.OnlineOffline.name(), false, CrushRebalanceStrategy.class.getName()},
{BuiltInStateModelDefinitions.LeaderStandby.name(), false, CrushRebalanceStrategy.class.getName()},
{BuiltInStateModelDefinitions.MasterSlave.name(), true, CrushEdRebalanceStrategy.class.getName()},
{BuiltInStateModelDefinitions.OnlineOffline.name(), true, CrushEdRebalanceStrategy.class.getName()}
};
}
protected void createResource(String dbName, String stateModel, int numPartition, int replica,
boolean delayEnabled, String rebalanceStrategy) {
if (delayEnabled) {
createResourceWithDelayedRebalance(CLUSTER_NAME, dbName, stateModel, numPartition, replica,
replica - 1, 200, rebalanceStrategy);
} else {
createResourceWithDelayedRebalance(CLUSTER_NAME, dbName, stateModel, numPartition, replica,
replica, 0, rebalanceStrategy);
}
}
@Test(dataProvider = "stateModels")
public void testUserDefinedPreferenceListsInFullAuto(String stateModel, boolean delayEnabled,
String rebalanceStrateyName) throws Exception {
String dbName = "Test-DB-" + stateModel;
createResource(dbName, stateModel, _PARTITIONS, _replica, delayEnabled,
rebalanceStrateyName);
try {
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
Map<String, List<String>> userDefinedPreferenceLists = idealState.getPreferenceLists();
List<String> userDefinedPartitions = new ArrayList<>();
for (String partition : userDefinedPreferenceLists.keySet()) {
List<String> preferenceList = new ArrayList<>();
for (int k = _replica; k >= 0; k--) {
String instance = _participants.get(k).getInstanceName();
preferenceList.add(instance);
}
userDefinedPreferenceLists.put(partition, preferenceList);
userDefinedPartitions.add(partition);
}
ResourceConfig resourceConfig =
new ResourceConfig.Builder(dbName).setPreferenceLists(userDefinedPreferenceLists).build();
_configAccessor.setResourceConfig(CLUSTER_NAME, dbName, resourceConfig);
Assert.assertTrue(_clusterVerifier.verify(3000));
verifyUserDefinedPreferenceLists(dbName, userDefinedPreferenceLists,
userDefinedPartitions);
while (userDefinedPartitions.size() > 0) {
IdealState originIS =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
Set<String> nonUserDefinedPartitions = new HashSet<>(originIS.getPartitionSet());
nonUserDefinedPartitions.removeAll(userDefinedPartitions);
removePartitionFromUserDefinedList(dbName, userDefinedPartitions);
// TODO: Remove wait once we enable the BestPossibleExternalViewVerifier for the WAGED rebalancer.
Assert.assertTrue(_clusterVerifier.verify(3000));
verifyUserDefinedPreferenceLists(dbName, userDefinedPreferenceLists,
userDefinedPartitions);
verifyNonUserDefinedAssignment(dbName, originIS, nonUserDefinedPartitions);
}
} finally {
_gSetupTool.getClusterManagementTool().dropResource(CLUSTER_NAME, dbName);
_clusterVerifier.verify(5000);
}
}
@Test
public void testUserDefinedPreferenceListsInFullAutoWithErrors() throws Exception {
String dbName = "Test-DB-withErrors";
createResource(dbName, BuiltInStateModelDefinitions.MasterSlave.name(), 5, _replica, false,
CrushRebalanceStrategy.class.getName());
try {
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
Map<String, List<String>> userDefinedPreferenceLists = idealState.getPreferenceLists();
List<String> newNodes = new ArrayList<>();
for (int i = NUM_NODE; i < NUM_NODE + _replica; i++) {
String instance = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, instance);
// start dummy participants
MockParticipantManager participant =
new TestMockParticipantManager(ZK_ADDR, CLUSTER_NAME, instance);
participant.syncStart();
_participants.add(participant);
newNodes.add(instance);
}
List<String> userDefinedPartitions = new ArrayList<>();
for (String partition : userDefinedPreferenceLists.keySet()) {
userDefinedPreferenceLists.put(partition, newNodes);
userDefinedPartitions.add(partition);
}
ResourceConfig resourceConfig =
new ResourceConfig.Builder(dbName).setPreferenceLists(userDefinedPreferenceLists).build();
_configAccessor.setResourceConfig(CLUSTER_NAME, dbName, resourceConfig);
TestHelper.verify(() -> {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, dbName);
if (ev != null) {
for (String partition : ev.getPartitionSet()) {
Map<String, String> stateMap = ev.getStateMap(partition);
if (stateMap.values().contains("ERROR")) {
return true;
}
}
}
return false;
}, 2000);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, dbName);
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
validateMinActiveAndTopStateReplica(is, ev, _replica, NUM_NODE);
} finally {
_gSetupTool.getClusterManagementTool().dropResource(CLUSTER_NAME, dbName);
_clusterVerifier.verify(5000);
}
}
private void verifyUserDefinedPreferenceLists(String db,
Map<String, List<String>> userDefinedPreferenceLists, List<String> userDefinedPartitions)
throws InterruptedException {
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
for (String p : userDefinedPreferenceLists.keySet()) {
List<String> userDefined = userDefinedPreferenceLists.get(p);
List<String> preferenceListInIs = is.getPreferenceList(p);
if (userDefinedPartitions.contains(p)) {
Assert.assertTrue(userDefined.equals(preferenceListInIs));
} else {
if (userDefined.equals(preferenceListInIs)) {
Assert.fail("Something is not good!");
}
Assert.assertFalse(userDefined.equals(preferenceListInIs), String
.format("Partition %s, List in Is: %s, List as defined in config: %s", p, preferenceListInIs,
userDefined));
}
}
}
private void verifyNonUserDefinedAssignment(String db, IdealState originIS, Set<String> nonUserDefinedPartitions)
throws InterruptedException {
IdealState newIS = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
Assert.assertEquals(originIS.getPartitionSet(), newIS.getPartitionSet());
for (String p : newIS.getPartitionSet()) {
if (nonUserDefinedPartitions.contains(p)) {
// for non user defined partition, mapping should keep the same
Assert.assertEquals(newIS.getPreferenceList(p), originIS.getPreferenceList(p));
}
}
}
private void removePartitionFromUserDefinedList(String db, List<String> userDefinedPartitions) {
ResourceConfig resourceConfig = _configAccessor.getResourceConfig(CLUSTER_NAME, db);
Map<String, List<String>> lists = resourceConfig.getPreferenceLists();
lists.remove(userDefinedPartitions.get(0));
resourceConfig.setPreferenceLists(lists);
userDefinedPartitions.remove(0);
_configAccessor.setResourceConfig(CLUSTER_NAME, db, resourceConfig);
}
@AfterClass
public void afterClass() throws Exception {
/**
* shutdown order: 1) disconnect the controller 2) disconnect participants
*/
_controller.syncStop();
for (MockParticipantManager participant : _participants) {
participant.syncStop();
}
deleteCluster(CLUSTER_NAME);
System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
}
public static class TestMockParticipantManager extends MockParticipantManager {
public TestMockParticipantManager(String zkAddr, String clusterName, String instanceName) {
super(zkAddr, clusterName, instanceName);
_msModelFactory = new MockDelayMSStateModelFactory();
}
@Override
public void finalize() {
super.finalize();
}
}
public static class MockDelayMSStateModelFactory extends MockMSModelFactory {
@Override
public MockDelayMSStateModel createNewStateModel(String resourceName,
String partitionKey) {
MockDelayMSStateModel model = new MockDelayMSStateModel(null);
return model;
}
}
// mock delay master-slave state model
@StateModelInfo(initialState = "OFFLINE", states = { "MASTER", "SLAVE", "ERROR" })
public static class MockDelayMSStateModel extends MockMSStateModel {
public MockDelayMSStateModel(MockTransition transition) {
super(transition);
}
@Transition(to = "*", from = "*")
public void generalTransitionHandle(Message message, NotificationContext context) {
throw new IllegalArgumentException("AAA");
}
}
}
| 9,530 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestInstanceOperation.java
|
package org.apache.helix.integration.rebalancer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixRollbackException;
import org.apache.helix.NotificationContext;
import org.apache.helix.PropertyPathBuilder;
import org.apache.helix.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.constants.InstanceConstants;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.controller.rebalancer.waged.AssignmentMetadataStore;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBucketDataAccessor;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.Message;
import org.apache.helix.model.ResourceAssignment;
import org.apache.helix.participant.StateMachineEngine;
import org.apache.helix.participant.statemachine.StateModel;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.apache.helix.participant.statemachine.StateModelInfo;
import org.apache.helix.participant.statemachine.Transition;
import org.apache.helix.tools.ClusterVerifiers.StrictMatchExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestInstanceOperation extends ZkTestBase {
protected final int NUM_NODE = 6;
protected static final int START_PORT = 12918;
protected static final int PARTITIONS = 20;
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
private int REPLICA = 3;
protected ClusterControllerManager _controller;
List<MockParticipantManager> _participants = new ArrayList<>();
List<String> _participantNames = new ArrayList<>();
private Set<String> _allDBs = new HashSet<>();
private ZkHelixClusterVerifier _clusterVerifier;
private ConfigAccessor _configAccessor;
private long _stateModelDelay = 3L;
private HelixAdmin _admin;
protected AssignmentMetadataStore _assignmentMetadataStore;
HelixDataAccessor _dataAccessor;
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NUM_NODE; i++) {
String participantName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
addParticipant(participantName);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
_clusterVerifier = new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
.setDeactivatedNodeAwareness(true)
.setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
_configAccessor = new ConfigAccessor(_gZkClient);
_dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.stateTransitionCancelEnabled(true);
clusterConfig.setDelayRebalaceEnabled(true);
clusterConfig.setRebalanceDelayTime(1800000L);
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
createTestDBs(1800000L);
setUpWagedBaseline();
_admin = new ZKHelixAdmin(_gZkClient);
}
@Test
public void testEvacuate() throws Exception {
System.out.println("START TestInstanceOperation.testEvacuate() at " + new Date(System.currentTimeMillis()));
// EV should contain all participants, check resources one by one
Map<String, ExternalView> assignment = getEV();
for (String resource : _allDBs) {
Assert.assertTrue(getParticipantsInEv(assignment.get(resource)).containsAll(_participantNames));
}
// evacuated instance
String instanceToEvacuate = _participants.get(0).getInstanceName();
_gSetupTool.getClusterManagementTool()
.setInstanceOperation(CLUSTER_NAME, instanceToEvacuate, InstanceConstants.InstanceOperation.EVACUATE);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// New ev should contain all instances but the evacuated one
assignment = getEV();
List<String> currentActiveInstances =
_participantNames.stream().filter(n -> !n.equals(instanceToEvacuate)).collect(Collectors.toList());
for (String resource : _allDBs) {
validateAssignmentInEv(assignment.get(resource));
Set<String> newPAssignedParticipants = getParticipantsInEv(assignment.get(resource));
Assert.assertFalse(newPAssignedParticipants.contains(instanceToEvacuate));
Assert.assertTrue(newPAssignedParticipants.containsAll(currentActiveInstances));
}
Assert.assertTrue(_admin.isEvacuateFinished(CLUSTER_NAME, instanceToEvacuate));
Assert.assertTrue(_admin.isReadyForPreparingJoiningCluster(CLUSTER_NAME, instanceToEvacuate));
}
@Test(dependsOnMethods = "testEvacuate")
public void testRevertEvacuation() throws Exception {
System.out.println("START TestInstanceOperation.testRevertEvacuation() at " + new Date(System.currentTimeMillis()));
// revert an evacuate instance
String instanceToEvacuate = _participants.get(0).getInstanceName();
_gSetupTool.getClusterManagementTool()
.setInstanceOperation(CLUSTER_NAME, instanceToEvacuate, null);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// EV should contain all participants, check resources one by one
Map<String, ExternalView> assignment = getEV();
for (String resource : _allDBs) {
Assert.assertTrue(getParticipantsInEv(assignment.get(resource)).containsAll(_participantNames));
validateAssignmentInEv(assignment.get(resource));
}
}
@Test(dependsOnMethods = "testRevertEvacuation")
public void testAddingNodeWithEvacuationTag() throws Exception {
System.out.println("START TestInstanceOperation.testAddingNodeWithEvacuationTag() at " + new Date(System.currentTimeMillis()));
// first disable and instance, and wait for all replicas to be moved out
String mockNewInstance = _participants.get(0).getInstanceName();
_gSetupTool.getClusterManagementTool()
.enableInstance(CLUSTER_NAME, mockNewInstance, false);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
//ev should contain all instances but the disabled one
Map<String, ExternalView> assignment = getEV();
List<String> currentActiveInstances =
_participantNames.stream().filter(n -> !n.equals(mockNewInstance)).collect(Collectors.toList());
for (String resource : _allDBs) {
validateAssignmentInEv(assignment.get(resource), REPLICA-1);
Set<String> newPAssignedParticipants = getParticipantsInEv(assignment.get(resource));
Assert.assertFalse(newPAssignedParticipants.contains(mockNewInstance));
Assert.assertTrue(newPAssignedParticipants.containsAll(currentActiveInstances));
}
// add evacuate tag and enable instance
_gSetupTool.getClusterManagementTool()
.setInstanceOperation(CLUSTER_NAME, mockNewInstance, InstanceConstants.InstanceOperation.EVACUATE);
_gSetupTool.getClusterManagementTool()
.enableInstance(CLUSTER_NAME, mockNewInstance, true);
//ev should be the same
assignment = getEV();
currentActiveInstances =
_participantNames.stream().filter(n -> !n.equals(mockNewInstance)).collect(Collectors.toList());
for (String resource : _allDBs) {
validateAssignmentInEv(assignment.get(resource), REPLICA-1);
Set<String> newPAssignedParticipants = getParticipantsInEv(assignment.get(resource));
Assert.assertFalse(newPAssignedParticipants.contains(mockNewInstance));
Assert.assertTrue(newPAssignedParticipants.containsAll(currentActiveInstances));
}
// now remove operation tag
String instanceToEvacuate = _participants.get(0).getInstanceName();
_gSetupTool.getClusterManagementTool()
.setInstanceOperation(CLUSTER_NAME, instanceToEvacuate, null);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// EV should contain all participants, check resources one by one
assignment = getEV();
for (String resource : _allDBs) {
Assert.assertTrue(getParticipantsInEv(assignment.get(resource)).containsAll(_participantNames));
validateAssignmentInEv(assignment.get(resource));
}
}
@Test(dependsOnMethods = "testAddingNodeWithEvacuationTag")
public void testEvacuateAndCancelBeforeBootstrapFinish() throws Exception {
System.out.println("START TestInstanceOperation.testEvacuateAndCancelBeforeBootstrapFinish() at " + new Date(System.currentTimeMillis()));
// add a resource where downward state transition is slow
createResourceWithDelayedRebalance(CLUSTER_NAME, "TEST_DB3_DELAYED_CRUSHED", "MasterSlave", PARTITIONS, REPLICA,
REPLICA - 1, 200000, CrushEdRebalanceStrategy.class.getName());
_allDBs.add("TEST_DB3_DELAYED_CRUSHED");
// add a resource where downward state transition is slow
createResourceWithWagedRebalance(CLUSTER_NAME, "TEST_DB4_DELAYED_WAGED", "MasterSlave",
PARTITIONS, REPLICA, REPLICA - 1);
_allDBs.add("TEST_DB4_DELAYED_WAGED");
// wait for assignment to finish
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// set bootstrap ST delay to a large number
_stateModelDelay = -10000L;
// evacuate an instance
String instanceToEvacuate = _participants.get(0).getInstanceName();
_gSetupTool.getClusterManagementTool()
.setInstanceOperation(CLUSTER_NAME, instanceToEvacuate, InstanceConstants.InstanceOperation.EVACUATE);
// Messages should be pending at all instances besides the evacuate one
for (String participant : _participantNames) {
if (participant.equals(instanceToEvacuate)) {
continue;
}
TestHelper.verify(
() -> ((_dataAccessor.getChildNames(_dataAccessor.keyBuilder().messages(participant))).isEmpty()), 30000);
}
Assert.assertFalse(_admin.isEvacuateFinished(CLUSTER_NAME, instanceToEvacuate));
Assert.assertFalse(_admin.isReadyForPreparingJoiningCluster(CLUSTER_NAME, instanceToEvacuate));
// sleep a bit so ST messages can start executing
Thread.sleep(Math.abs(_stateModelDelay / 100));
// before we cancel, check current EV
Map<String, ExternalView> assignment = getEV();
for (String resource : _allDBs) {
// check every replica has >= 3 partitions and a top state partition
validateAssignmentInEv(assignment.get(resource));
}
// cancel the evacuation
_gSetupTool.getClusterManagementTool()
.setInstanceOperation(CLUSTER_NAME, instanceToEvacuate, null);
assignment = getEV();
for (String resource : _allDBs) {
// check every replica has >= 3 active replicas, even before cluster converge
validateAssignmentInEv(assignment.get(resource));
}
// check cluster converge. We have longer delay for ST then verifier timeout. It will only converge if we cancel ST.
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// EV should contain all participants, check resources one by one
assignment = getEV();
for (String resource : _allDBs) {
Assert.assertTrue(getParticipantsInEv(assignment.get(resource)).containsAll(_participantNames));
// check every replica has >= 3 active replicas again
validateAssignmentInEv(assignment.get(resource));
}
}
@Test(dependsOnMethods = "testEvacuateAndCancelBeforeBootstrapFinish")
public void testEvacuateAndCancelBeforeDropFinish() throws Exception {
System.out.println("START TestInstanceOperation.testEvacuateAndCancelBeforeDropFinish() at " + new Date(System.currentTimeMillis()));
// set DROP ST delay to a large number
_stateModelDelay = 10000L;
// evacuate an instance
String instanceToEvacuate = _participants.get(0).getInstanceName();
_gSetupTool.getClusterManagementTool()
.setInstanceOperation(CLUSTER_NAME, instanceToEvacuate, InstanceConstants.InstanceOperation.EVACUATE);
// message should be pending at the to evacuate participant
TestHelper.verify(
() -> ((_dataAccessor.getChildNames(_dataAccessor.keyBuilder().messages(instanceToEvacuate))).isEmpty()), 30000);
Assert.assertFalse(_admin.isEvacuateFinished(CLUSTER_NAME, instanceToEvacuate));
// cancel evacuation
_gSetupTool.getClusterManagementTool()
.setInstanceOperation(CLUSTER_NAME, instanceToEvacuate, null);
// check every replica has >= 3 active replicas, even before cluster converge
Map<String, ExternalView> assignment = getEV();
for (String resource : _allDBs) {
validateAssignmentInEv(assignment.get(resource));
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// EV should contain all participants, check resources one by one
assignment = getEV();
for (String resource : _allDBs) {
Assert.assertTrue(getParticipantsInEv(assignment.get(resource)).containsAll(_participantNames));
// check every replica has >= 3 active replicas
validateAssignmentInEv(assignment.get(resource));
}
}
@Test(dependsOnMethods = "testEvacuateAndCancelBeforeDropFinish")
public void testMarkEvacuationAfterEMM() throws Exception {
System.out.println("START TestInstanceOperation.testMarkEvacuationAfterEMM() at " + new Date(System.currentTimeMillis()));
_stateModelDelay = 1000L;
Assert.assertFalse(_gSetupTool.getClusterManagementTool().isInMaintenanceMode(CLUSTER_NAME));
_gSetupTool.getClusterManagementTool().manuallyEnableMaintenanceMode(CLUSTER_NAME, true, null,
null);
addParticipant(PARTICIPANT_PREFIX + "_" + (START_PORT + NUM_NODE));
Assert.assertTrue(_clusterVerifier.verifyByPolling());
Map<String, ExternalView> assignment = getEV();
for (String resource : _allDBs) {
Assert.assertFalse(getParticipantsInEv(assignment.get(resource)).contains(_participantNames.get(NUM_NODE)));
}
// set evacuate operation
String instanceToEvacuate = _participants.get(0).getInstanceName();
_gSetupTool.getClusterManagementTool()
.setInstanceOperation(CLUSTER_NAME, instanceToEvacuate, InstanceConstants.InstanceOperation.EVACUATE);
// there should be no evacuation happening
for (String resource : _allDBs) {
Assert.assertTrue(getParticipantsInEv(assignment.get(resource)).contains(instanceToEvacuate));
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// exit MM
_gSetupTool.getClusterManagementTool().manuallyEnableMaintenanceMode(CLUSTER_NAME, false, null,
null);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
assignment = getEV();
List<String> currentActiveInstances =
_participantNames.stream().filter(n -> !n.equals(instanceToEvacuate)).collect(Collectors.toList());
for (String resource : _allDBs) {
validateAssignmentInEv(assignment.get(resource));
Set<String> newPAssignedParticipants = getParticipantsInEv(assignment.get(resource));
Assert.assertFalse(newPAssignedParticipants.contains(instanceToEvacuate));
Assert.assertTrue(newPAssignedParticipants.containsAll(currentActiveInstances));
}
Assert.assertTrue(_admin.isReadyForPreparingJoiningCluster(CLUSTER_NAME, instanceToEvacuate));
}
@Test(dependsOnMethods = "testMarkEvacuationAfterEMM")
public void testEvacuationWithOfflineInstancesInCluster() throws Exception {
System.out.println("START TestInstanceOperation.testEvacuationWithOfflineInstancesInCluster() at " + new Date(System.currentTimeMillis()));
_participants.get(1).syncStop();
_participants.get(2).syncStop();
String evacuateInstanceName = _participants.get(_participants.size()-2).getInstanceName();
_gSetupTool.getClusterManagementTool()
.setInstanceOperation(CLUSTER_NAME, evacuateInstanceName, InstanceConstants.InstanceOperation.EVACUATE);
Map<String, ExternalView> assignment;
// EV should contain all participants, check resources one by one
assignment = getEV();
for (String resource : _allDBs) {
TestHelper.verify(() -> {
ExternalView ev = assignment.get(resource);
for (String partition : ev.getPartitionSet()) {
AtomicInteger activeReplicaCount = new AtomicInteger();
ev.getStateMap(partition)
.values()
.stream()
.filter(v -> v.equals("MASTER") || v.equals("LEADER") || v.equals("SLAVE") || v.equals("FOLLOWER")
|| v.equals("STANDBY"))
.forEach(v -> activeReplicaCount.getAndIncrement());
if (activeReplicaCount.get() < REPLICA - 1 || (ev.getStateMap(partition).containsKey(evacuateInstanceName)
&& ev.getStateMap(partition).get(evacuateInstanceName).equals("MASTER") && ev.getStateMap(partition)
.get(evacuateInstanceName)
.equals("LEADER"))) {
return false;
}
}
return true;
}, 30000);
}
_participants.get(1).syncStart();
_participants.get(2).syncStart();
}
private void addParticipant(String participantName) {
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, participantName);
// start dummy participants
MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, participantName);
StateMachineEngine stateMachine = participant.getStateMachineEngine();
// Using a delayed state model
StDelayMSStateModelFactory delayFactory = new StDelayMSStateModelFactory();
stateMachine.registerStateModelFactory("MasterSlave", delayFactory);
participant.syncStart();
_participants.add(participant);
_participantNames.add(participantName);
}
private void createTestDBs(long delayTime) throws InterruptedException {
createResourceWithDelayedRebalance(CLUSTER_NAME, "TEST_DB0_CRUSHED",
BuiltInStateModelDefinitions.LeaderStandby.name(), PARTITIONS, REPLICA, REPLICA - 1, -1,
CrushEdRebalanceStrategy.class.getName());
_allDBs.add("TEST_DB0_CRUSHED");
createResourceWithDelayedRebalance(CLUSTER_NAME, "TEST_DB1_CRUSHED",
BuiltInStateModelDefinitions.LeaderStandby.name(), PARTITIONS, REPLICA, REPLICA - 1, 2000000,
CrushEdRebalanceStrategy.class.getName());
_allDBs.add("TEST_DB1_CRUSHED");
createResourceWithWagedRebalance(CLUSTER_NAME, "TEST_DB2_WAGED", BuiltInStateModelDefinitions.LeaderStandby.name(),
PARTITIONS, REPLICA, REPLICA - 1);
_allDBs.add("TEST_DB2_WAGED");
Assert.assertTrue(_clusterVerifier.verifyByPolling());
}
private Map<String, ExternalView> getEV() {
Map<String, ExternalView> externalViews = new HashMap<String, ExternalView>();
for (String db : _allDBs) {
ExternalView ev = _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
externalViews.put(db, ev);
}
return externalViews;
}
private boolean verifyIS(String evacuateInstanceName) {
for (String db : _allDBs) {
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
for (String partition : is.getPartitionSet()) {
List<String> newPAssignedParticipants = is.getPreferenceList(partition);
if (newPAssignedParticipants.contains(evacuateInstanceName)) {
System.out.println("partition " + partition + " assignment " + newPAssignedParticipants + " ev " + evacuateInstanceName);
return false;
}
}
}
return true;
}
private Set<String> getParticipantsInEv(ExternalView ev) {
Set<String> assignedParticipants = new HashSet<>();
for (String partition : ev.getPartitionSet()) {
ev.getStateMap(partition)
.keySet()
.stream()
.filter(k -> !ev.getStateMap(partition).get(k).equals("OFFLINE"))
.forEach(assignedParticipants::add);
}
return assignedParticipants;
}
// verify that each partition has >=REPLICA (3 in this case) replicas
private void validateAssignmentInEv(ExternalView ev) {
validateAssignmentInEv(ev, REPLICA);
}
private void validateAssignmentInEv(ExternalView ev, int expectedNumber) {
Set<String> partitionSet = ev.getPartitionSet();
for (String partition : partitionSet) {
AtomicInteger activeReplicaCount = new AtomicInteger();
ev.getStateMap(partition)
.values()
.stream()
.filter(v -> v.equals("MASTER") || v.equals("LEADER") || v.equals("SLAVE") || v.equals("FOLLOWER") || v.equals("STANDBY"))
.forEach(v -> activeReplicaCount.getAndIncrement());
Assert.assertTrue(activeReplicaCount.get() >=expectedNumber);
}
}
private void setUpWagedBaseline() {
_assignmentMetadataStore = new AssignmentMetadataStore(new ZkBucketDataAccessor(ZK_ADDR), CLUSTER_NAME) {
public Map<String, ResourceAssignment> getBaseline() {
// Ensure this metadata store always read from the ZK without using cache.
super.reset();
return super.getBaseline();
}
public synchronized Map<String, ResourceAssignment> getBestPossibleAssignment() {
// Ensure this metadata store always read from the ZK without using cache.
super.reset();
return super.getBestPossibleAssignment();
}
};
// Set test instance capacity and partition weights
ClusterConfig clusterConfig = _dataAccessor.getProperty(_dataAccessor.keyBuilder().clusterConfig());
String testCapacityKey = "TestCapacityKey";
clusterConfig.setInstanceCapacityKeys(Collections.singletonList(testCapacityKey));
clusterConfig.setDefaultInstanceCapacityMap(Collections.singletonMap(testCapacityKey, 100));
clusterConfig.setDefaultPartitionWeightMap(Collections.singletonMap(testCapacityKey, 1));
_dataAccessor.setProperty(_dataAccessor.keyBuilder().clusterConfig(), clusterConfig);
}
// A state transition model where either downward ST are slow (_stateModelDelay >0) or upward ST are slow (_stateModelDelay <0)
public class StDelayMSStateModelFactory extends StateModelFactory<StDelayMSStateModel> {
@Override
public StDelayMSStateModel createNewStateModel(String resourceName, String partitionKey) {
StDelayMSStateModel model = new StDelayMSStateModel();
return model;
}
}
@StateModelInfo(initialState = "OFFLINE", states = {"MASTER", "SLAVE", "ERROR"})
public class StDelayMSStateModel extends StateModel {
public StDelayMSStateModel() {
_cancelled = false;
}
private void sleepWhileNotCanceled(long sleepTime) throws InterruptedException{
while(sleepTime >0 && !isCancelled()) {
Thread.sleep(5000);
sleepTime = sleepTime - 5000;
}
if (isCancelled()) {
_cancelled = false;
throw new HelixRollbackException("EX");
}
}
@Transition(to = "SLAVE", from = "OFFLINE")
public void onBecomeSlaveFromOffline(Message message, NotificationContext context) throws InterruptedException {
if (_stateModelDelay < 0) {
sleepWhileNotCanceled(Math.abs(_stateModelDelay));
}
}
@Transition(to = "MASTER", from = "SLAVE")
public void onBecomeMasterFromSlave(Message message, NotificationContext context) throws InterruptedException {
if (_stateModelDelay < 0) {
sleepWhileNotCanceled(Math.abs(_stateModelDelay));
}
}
@Transition(to = "SLAVE", from = "MASTER")
public void onBecomeSlaveFromMaster(Message message, NotificationContext context) throws InterruptedException {
if (_stateModelDelay > 0) {
sleepWhileNotCanceled(_stateModelDelay);
}
}
@Transition(to = "OFFLINE", from = "SLAVE")
public void onBecomeOfflineFromSlave(Message message, NotificationContext context) throws InterruptedException {
if (_stateModelDelay > 0) {
sleepWhileNotCanceled(_stateModelDelay);
}
}
@Transition(to = "DROPPED", from = "OFFLINE")
public void onBecomeDroppedFromOffline(Message message, NotificationContext context) throws InterruptedException {
if (_stateModelDelay > 0) {
sleepWhileNotCanceled(_stateModelDelay);
}
}
}
}
| 9,531 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
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.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.MaintenanceSignal;
import org.apache.helix.monitoring.mbeans.MonitorDomainNames;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.apache.helix.monitoring.mbeans.ClusterStatusMonitor.CLUSTER_DN_KEY;
import static org.apache.helix.util.StatusUpdateUtil.ErrorType.RebalanceResourceFailure;
public class TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit extends ZkTestBase {
private static final int NUM_NODE = 10;
private static final int START_PORT = 12918;
private static final int _PARTITIONS = 5;
private static final MBeanServerConnection _server = ManagementFactory.getPlatformMBeanServer();
private final String CLASS_NAME = getShortClassName();
private final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
private ClusterControllerManager _controller;
private List<MockParticipantManager> _participants = new ArrayList<>();
private HelixDataAccessor _dataAccessor;
private int _maxOfflineInstancesAllowed = 4;
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NUM_NODE; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, instanceName);
// start dummy participants
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
ZkHelixClusterVerifier clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
_dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setMaxOfflineInstancesAllowed(_maxOfflineInstancesAllowed);
clusterConfig.setNumOfflineInstancesForAutoExit(0);
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
for (int i = 0; i < 3; i++) {
String db = "Test-DB-" + i++;
createResourceWithDelayedRebalance(CLUSTER_NAME, db,
BuiltInStateModelDefinitions.MasterSlave.name(), _PARTITIONS, 3, 3, -1);
}
Assert.assertTrue(clusterVerifier.verifyByPolling());
}
@AfterMethod
public void afterMethod() {
cleanupRebalanceError();
}
@Test
public void testWithDisabledInstancesLimit() throws Exception {
MaintenanceSignal maintenanceSignal =
_dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance());
Assert.assertNull(maintenanceSignal);
checkForRebalanceError(false);
HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
// disable instance
int i;
for (i = 2; i < 2 + _maxOfflineInstancesAllowed; i++) {
String instance = _participants.get(i).getInstanceName();
admin.enableInstance(CLUSTER_NAME, instance, false);
}
boolean result = TestHelper.verify(() -> {
MaintenanceSignal ms = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance());
return ms == null;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
String instance = _participants.get(i).getInstanceName();
admin.enableInstance(CLUSTER_NAME, instance, false);
ZkHelixClusterVerifier clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(clusterVerifier.verifyByPolling());
result = TestHelper.verify(() -> {
MaintenanceSignal ms =_dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance());
return ms != null && ms.getReason() != null;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
checkForRebalanceError(true);
for (i = 2; i < 2 + _maxOfflineInstancesAllowed + 1; i++) {
instance = _participants.get(i).getInstanceName();
admin.enableInstance(CLUSTER_NAME, instance, true);
}
admin.enableMaintenanceMode(CLUSTER_NAME, false);
Assert.assertTrue(clusterVerifier.verifyByPolling());
}
@Test(dependsOnMethods = "testWithDisabledInstancesLimit")
public void testWithOfflineInstancesLimit() throws Exception {
MaintenanceSignal maintenanceSignal =
_dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance());
Assert.assertNull(maintenanceSignal);
checkForRebalanceError(false);
int i;
for (i = 2; i < 2 + _maxOfflineInstancesAllowed; i++) {
_participants.get(i).syncStop();
}
boolean result = TestHelper.verify(() -> {
MaintenanceSignal ms = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance());
return ms == null;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
_participants.get(i).syncStop();
result = TestHelper.verify(() -> {
MaintenanceSignal ms =_dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance());
return ms != null && ms.getReason() != null;
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
// Verify there is rebalance error logged
checkForRebalanceError(true);
}
@AfterClass
public void afterClass() throws Exception {
/*
* shutdown order: 1) disconnect the controller 2) disconnect participants
*/
_controller.syncStop();
for (MockParticipantManager participant : _participants) {
participant.syncStop();
}
deleteCluster(CLUSTER_NAME);
System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
}
private void checkForRebalanceError(final boolean expectError) throws Exception {
boolean result = TestHelper.verify(() -> {
/*
* TODO re-enable this check when we start recording rebalance error again
* ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
* PropertyKey errorNodeKey =
* accessor.keyBuilder().controllerTaskError(RebalanceResourceFailure.name());
* Assert.assertEquals(accessor.getProperty(errorNodeKey) != null, expectError);
*/
Long value =
(Long) _server.getAttribute(getClusterMbeanName(CLUSTER_NAME), "RebalanceFailureGauge");
return expectError == (value != null && value > 0);
}, TestHelper.WAIT_DURATION);
Assert.assertTrue(result);
}
private void cleanupRebalanceError() {
ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
PropertyKey errorNodeKey =
accessor.keyBuilder().controllerTaskError(RebalanceResourceFailure.name());
accessor.removeProperty(errorNodeKey);
}
private ObjectName getClusterMbeanName(String clusterName) throws MalformedObjectNameException {
String clusterBeanName = String.format("%s=%s", CLUSTER_DN_KEY, clusterName);
return new ObjectName(
String.format("%s:%s", MonitorDomainNames.ClusterStatus.name(), clusterBeanName));
}
}
| 9,532 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAbnormalStatesResolver.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import com.google.common.collect.ImmutableMap;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.Criteria;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.InstanceType;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
import org.apache.helix.controller.rebalancer.constraint.ExcessiveTopStateResolver;
import org.apache.helix.controller.rebalancer.constraint.MockAbnormalStateResolver;
import org.apache.helix.controller.rebalancer.constraint.MonitoredAbnormalResolver;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.messaging.AsyncCallback;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.MasterSlaveSMD;
import org.apache.helix.model.Message;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestAbnormalStatesResolver extends ZkStandAloneCMTestBase {
// TODO: remove this wait time once we have a better way to determine if the rebalance has been
// TODO: done as a reaction of the test operations.
protected static final int DEFAULT_REBALANCE_PROCESSING_WAIT_TIME = 1000;
@Test
public void testConfigureResolver() {
ResourceControllerDataProvider cache = new ResourceControllerDataProvider(CLUSTER_NAME);
// Verify the initial setup.
cache.refresh(_controller.getHelixDataAccessor());
for (String stateModelDefName : cache.getStateModelDefMap().keySet()) {
Assert.assertEquals(cache.getAbnormalStateResolver(stateModelDefName).getResolverClass(),
MonitoredAbnormalResolver.DUMMY_STATE_RESOLVER.getResolverClass());
}
// Update the resolver configuration for MasterSlave state model.
ConfigAccessor configAccessor = new ConfigAccessor.Builder().setZkAddress(ZK_ADDR).build();
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setAbnormalStateResolverMap(
ImmutableMap.of(MasterSlaveSMD.name, MockAbnormalStateResolver.class.getName()));
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
cache.requireFullRefresh();
cache.refresh(_controller.getHelixDataAccessor());
for (String stateModelDefName : cache.getStateModelDefMap().keySet()) {
Assert.assertEquals(cache.getAbnormalStateResolver(stateModelDefName).getResolverClass(),
stateModelDefName.equals(MasterSlaveSMD.name) ?
MockAbnormalStateResolver.class :
MonitoredAbnormalResolver.DUMMY_STATE_RESOLVER.getResolverClass());
}
// Reset the resolver map
clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setAbnormalStateResolverMap(Collections.emptyMap());
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
}
@Test(dependsOnMethods = "testConfigureResolver")
public void testExcessiveTopStateResolver() throws InterruptedException {
BestPossibleExternalViewVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verify());
// 1. Find a partition with a MASTER replica and a SLAVE replica
HelixAdmin admin = new ZKHelixAdmin.Builder().setZkAddress(ZK_ADDR).build();
ExternalView ev = admin.getResourceExternalView(CLUSTER_NAME, TEST_DB);
String targetPartition = ev.getPartitionSet().iterator().next();
Map<String, String> partitionAssignment = ev.getStateMap(targetPartition);
String slaveHost = partitionAssignment.entrySet().stream()
.filter(entry -> entry.getValue().equals(MasterSlaveSMD.States.SLAVE.name())).findAny()
.get().getKey();
long previousMasterUpdateTime =
getTopStateUpdateTime(ev, targetPartition, MasterSlaveSMD.States.MASTER.name());
// Build SLAVE to MASTER message
String msgId = new UUID(123, 456).toString();
Message msg = createMessage(Message.MessageType.STATE_TRANSITION, msgId,
MasterSlaveSMD.States.SLAVE.name(), MasterSlaveSMD.States.MASTER.name(), TEST_DB,
slaveHost);
msg.setStateModelDef(MasterSlaveSMD.name);
Criteria cr = new Criteria();
cr.setInstanceName(slaveHost);
cr.setRecipientInstanceType(InstanceType.PARTICIPANT);
cr.setSessionSpecific(true);
cr.setPartition(targetPartition);
cr.setResource(TEST_DB);
cr.setClusterName(CLUSTER_NAME);
AsyncCallback callback = new AsyncCallback() {
@Override
public void onTimeOut() {
Assert.fail("The test state transition timeout.");
}
@Override
public void onReplyMessage(Message message) {
Assert.assertEquals(message.getMsgState(), Message.MessageState.READ);
}
};
// 2. Send the SLAVE to MASTER message to the SLAVE host to make abnormal partition states.
// 2.A. Without resolver, the fixing is not completely done by the default rebalancer logic.
_controller.getMessagingService()
.sendAndWait(cr, msg, callback, (int) TestHelper.WAIT_DURATION);
// Wait until the partition status is fixed, verify if the result is as expected
verifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
ev = admin.getResourceExternalView(CLUSTER_NAME, TEST_DB);
Assert.assertEquals(ev.getStateMap(targetPartition).values().stream()
.filter(state -> state.equals(MasterSlaveSMD.States.MASTER.name())).count(), 1);
// Since the resolver is not used in the auto default fix process, there is no update on the
// original master. So if there is any data issue, it was not fixed.
long currentMasterUpdateTime =
getTopStateUpdateTime(ev, targetPartition, MasterSlaveSMD.States.MASTER.name());
Assert.assertFalse(currentMasterUpdateTime > previousMasterUpdateTime);
// 2.B. with resolver configured, the fixing is complete.
ConfigAccessor configAccessor = new ConfigAccessor.Builder().setZkAddress(ZK_ADDR).build();
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setAbnormalStateResolverMap(
ImmutableMap.of(MasterSlaveSMD.name, ExcessiveTopStateResolver.class.getName()));
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
_controller.getMessagingService()
.sendAndWait(cr, msg, callback, (int) TestHelper.WAIT_DURATION);
// Wait until the partition status is fixed, verify if the result is as expected
Assert.assertTrue(verifier.verifyByPolling());
ev = admin.getResourceExternalView(CLUSTER_NAME, TEST_DB);
Assert.assertEquals(ev.getStateMap(targetPartition).values().stream()
.filter(state -> state.equals(MasterSlaveSMD.States.MASTER.name())).count(), 1);
// Now the resolver is used in the auto fix process, the original master has also been refreshed.
// The potential data issue has been fixed in this process.
currentMasterUpdateTime =
getTopStateUpdateTime(ev, targetPartition, MasterSlaveSMD.States.MASTER.name());
Assert.assertTrue(currentMasterUpdateTime > previousMasterUpdateTime);
// Reset the resolver map
clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setAbnormalStateResolverMap(Collections.emptyMap());
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
}
private long getTopStateUpdateTime(ExternalView ev, String partition, String state) {
String topStateHost = ev.getStateMap(partition).entrySet().stream()
.filter(entry -> entry.getValue().equals(state)).findFirst().get().getKey();
MockParticipantManager participant = Arrays.stream(_participants)
.filter(instance -> instance.getInstanceName().equals(topStateHost)).findFirst().get();
HelixDataAccessor accessor = _controller.getHelixDataAccessor();
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
CurrentState currentState = accessor.getProperty(keyBuilder
.currentState(participant.getInstanceName(), participant.getSessionId(),
ev.getResourceName()));
return currentState.getEndTime(partition);
}
}
| 9,533 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestFullAutoNodeTagging.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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 java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.helix.BaseDataAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.TestHelper.Verifier;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZNRecordSerializer;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.zookeeper.impl.client.ZkClient;
import org.apache.helix.zookeeper.impl.factory.DedicatedZkClientFactory;
import org.apache.helix.zookeeper.api.client.HelixZkClient;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.apache.helix.tools.ClusterStateVerifier.ZkVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Test that node tagging behaves correctly in FULL_AUTO mode
*/
public class TestFullAutoNodeTagging extends ZkUnitTestBase {
private static final Logger LOG = LoggerFactory.getLogger(TestFullAutoNodeTagging.class);
@Test
public void testUntag() throws Exception {
final int NUM_PARTICIPANTS = 2;
final int NUM_PARTITIONS = 4;
final int NUM_REPLICAS = 1;
final String RESOURCE_NAME = "TestResource0";
final String TAG = "ASSIGNABLE";
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
final String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
// Set up cluster
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestResource", // resource name prefix
1, // resources
NUM_PARTITIONS, // partitions per resource
NUM_PARTICIPANTS, // number of nodes
NUM_REPLICAS, // replicas
"OnlineOffline", RebalanceMode.FULL_AUTO, // use FULL_AUTO mode to test node tagging
true); // do rebalance
// Tag the resource
final HelixAdmin helixAdmin = new ZKHelixAdmin(_gZkClient);
IdealState idealState = helixAdmin.getResourceIdealState(clusterName, RESOURCE_NAME);
idealState.setInstanceGroupTag(TAG);
helixAdmin.setResourceIdealState(clusterName, RESOURCE_NAME, idealState);
// Get a data accessor
final HelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
final PropertyKey.Builder keyBuilder = accessor.keyBuilder();
// Tag the participants
for (int i = 0; i < NUM_PARTICIPANTS; i++) {
final String instanceName = "localhost_" + (12918 + i);
helixAdmin.addInstanceTag(clusterName, instanceName, TAG);
}
// Start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// Start participants
MockParticipantManager[] participants = new MockParticipantManager[NUM_PARTICIPANTS];
for (int i = 0; i < NUM_PARTICIPANTS; i++) {
final String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
// Verify that there are NUM_PARTITIONS partitions in the external view, each having
// NUM_REPLICAS replicas, where all assigned replicas are to tagged nodes, and they are all
// ONLINE.
Verifier v = new Verifier() {
@Override
public boolean verify() throws Exception {
ExternalView externalView =
pollForProperty(ExternalView.class, accessor, keyBuilder.externalView(RESOURCE_NAME),
true);
if (externalView == null) {
return false;
}
Set<String> taggedInstances =
Sets.newHashSet(helixAdmin.getInstancesInClusterWithTag(clusterName, TAG));
Set<String> partitionSet = externalView.getPartitionSet();
if (partitionSet.size() != NUM_PARTITIONS) {
return false;
}
for (String partitionName : partitionSet) {
Map<String, String> stateMap = externalView.getStateMap(partitionName);
if (stateMap.size() != NUM_REPLICAS) {
return false;
}
for (String participantName : stateMap.keySet()) {
if (!taggedInstances.contains(participantName)) {
return false;
}
String state = stateMap.get(participantName);
if (!state.equalsIgnoreCase("ONLINE")) {
return false;
}
}
}
return true;
}
};
// Run the verifier for both nodes tagged
boolean initialResult = TestHelper.verify(v, 10 * 1000);
Assert.assertTrue(initialResult);
// Untag a node
helixAdmin.removeInstanceTag(clusterName, "localhost_12918", TAG);
// Verify again
boolean finalResult = TestHelper.verify(v, 10 * 1000);
Assert.assertTrue(finalResult);
// clean up
controller.syncStop();
for (int i = 0; i < NUM_PARTICIPANTS; i++) {
participants[i].syncStop();
}
TestHelper.dropCluster(clusterName, _gZkClient);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
/**
* Ensure that no assignments happen when there are no tagged nodes, but the resource is tagged
*/
@Test
public void testResourceTaggedFirst() throws Exception {
final int NUM_PARTICIPANTS = 10;
final int NUM_PARTITIONS = 4;
final int NUM_REPLICAS = 2;
final String RESOURCE_NAME = "TestDB0";
final String TAG = "ASSIGNABLE";
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
// Set up cluster
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
NUM_PARTITIONS, // partitions per resource
NUM_PARTICIPANTS, // number of nodes
NUM_REPLICAS, // replicas
"MasterSlave", RebalanceMode.FULL_AUTO, // use FULL_AUTO mode to test node tagging
true); // do rebalance
// tag the resource
HelixAdmin helixAdmin = new ZKHelixAdmin(ZK_ADDR);
IdealState idealState = helixAdmin.getResourceIdealState(clusterName, RESOURCE_NAME);
idealState.setInstanceGroupTag(TAG);
helixAdmin.setResourceIdealState(clusterName, RESOURCE_NAME, idealState);
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// start participants
MockParticipantManager[] participants = new MockParticipantManager[NUM_PARTICIPANTS];
for (int i = 0; i < NUM_PARTICIPANTS; i++) {
final String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
Thread.sleep(1000);
boolean result =
ClusterStateVerifier.verifyByZkCallback(new EmptyZkVerifier(clusterName, RESOURCE_NAME));
Assert.assertTrue(result, "External view and current state must be empty");
// cleanup
for (int i = 0; i < NUM_PARTICIPANTS; i++) {
participants[i].syncStop();
}
controller.syncStop();
TestHelper.dropCluster(clusterName, _gZkClient);
}
/**
* Basic test for tagging behavior. 10 participants, of which 4 are tagged. Launch all 10,
* checking external view every time a tagged node is started. Then shut down all 10, checking
* external view every time a tagged node is killed.
*/
@Test
public void testSafeAssignment() throws Exception {
final int NUM_PARTICIPANTS = 10;
final int NUM_PARTITIONS = 4;
final int NUM_REPLICAS = 2;
final String RESOURCE_NAME = "TestDB0";
final String TAG = "ASSIGNABLE";
final String[] TAGGED_NODES = {
"localhost_12920", "localhost_12922", "localhost_12924", "localhost_12925"
};
Set<String> taggedNodes = Sets.newHashSet(TAGGED_NODES);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
// Set up cluster
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
NUM_PARTITIONS, // partitions per resource
NUM_PARTICIPANTS, // number of nodes
NUM_REPLICAS, // replicas
"MasterSlave", RebalanceMode.FULL_AUTO, // use FULL_AUTO mode to test node tagging
true); // do rebalance
// tag the resource and participants
HelixAdmin helixAdmin = new ZKHelixAdmin(ZK_ADDR);
for (String taggedNode : TAGGED_NODES) {
helixAdmin.addInstanceTag(clusterName, taggedNode, TAG);
}
IdealState idealState = helixAdmin.getResourceIdealState(clusterName, RESOURCE_NAME);
idealState.setInstanceGroupTag(TAG);
helixAdmin.setResourceIdealState(clusterName, RESOURCE_NAME, idealState);
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// start participants
MockParticipantManager[] participants = new MockParticipantManager[NUM_PARTICIPANTS];
for (int i = 0; i < NUM_PARTICIPANTS; i++) {
final String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
// ensure that everything is valid if this is a tagged node that is starting
if (taggedNodes.contains(instanceName)) {
// make sure that the best possible matches the external view
Thread.sleep(500);
boolean result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// make sure that the tagged state of the nodes is still balanced
result =
ClusterStateVerifier.verifyByZkCallback(new TaggedZkVerifier(clusterName,
RESOURCE_NAME, TAGGED_NODES, false));
Assert.assertTrue(result, "initial assignment with all tagged nodes live is invalid");
}
}
// cleanup
for (int i = 0; i < NUM_PARTICIPANTS; i++) {
String participantName = participants[i].getInstanceName();
participants[i].syncStop();
if (taggedNodes.contains(participantName)) {
// check that the external view is still correct even after removing tagged nodes
taggedNodes.remove(participantName);
Thread.sleep(500);
boolean result =
ClusterStateVerifier.verifyByZkCallback(new TaggedZkVerifier(clusterName,
RESOURCE_NAME, TAGGED_NODES, taggedNodes.isEmpty()));
Assert.assertTrue(result, "incorrect state after removing " + participantName + ", "
+ taggedNodes + " remain");
}
}
controller.syncStop();
TestHelper.dropCluster(clusterName, _gZkClient);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
/**
* Checker for basic validity of the external view given node tagging requirements
*/
private static class TaggedZkVerifier implements ZkVerifier {
private final String _clusterName;
private final String _resourceName;
private final String[] _taggedNodes;
private final boolean _isEmptyAllowed;
private final HelixZkClient _zkClient;
/**
* Create a verifier for a specific cluster and resource
* @param clusterName the cluster to verify
* @param resourceName the resource within the cluster to verify
* @param taggedNodes nodes tagged with the resource tag
* @param isEmptyAllowed true if empty assignments are legal
*/
public TaggedZkVerifier(String clusterName, String resourceName, String[] taggedNodes,
boolean isEmptyAllowed) {
_clusterName = clusterName;
_resourceName = resourceName;
_taggedNodes = taggedNodes;
_isEmptyAllowed = isEmptyAllowed;
_zkClient = DedicatedZkClientFactory.getInstance()
.buildZkClient(new HelixZkClient.ZkConnectionConfig(ZK_ADDR));
_zkClient.setZkSerializer(new ZNRecordSerializer());
}
@Override
public boolean verify() {
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_zkClient);
HelixDataAccessor accessor = new ZKHelixDataAccessor(_clusterName, baseAccessor);
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
ExternalView externalView = accessor.getProperty(keyBuilder.externalView(_resourceName));
Set<String> taggedNodeSet = ImmutableSet.copyOf(_taggedNodes);
// set up counts of partitions, masters, and slaves per node
Map<String, Integer> partitionCount = Maps.newHashMap();
int partitionSum = 0;
Map<String, Integer> masterCount = Maps.newHashMap();
int masterSum = 0;
Map<String, Integer> slaveCount = Maps.newHashMap();
int slaveSum = 0;
for (String partitionName : externalView.getPartitionSet()) {
Map<String, String> stateMap = externalView.getStateMap(partitionName);
for (String participantName : stateMap.keySet()) {
String state = stateMap.get(participantName);
if (state.equalsIgnoreCase("MASTER") || state.equalsIgnoreCase("SLAVE")) {
partitionSum++;
incrementCount(partitionCount, participantName);
if (!taggedNodeSet.contains(participantName)) {
// not allowed to have a non-tagged node assigned
LOG.error("Participant " + participantName + " is not tag, but has an assigned node");
return false;
} else if (state.equalsIgnoreCase("MASTER")) {
masterSum++;
incrementCount(masterCount, participantName);
} else if (state.equalsIgnoreCase("SLAVE")) {
slaveSum++;
incrementCount(slaveCount, participantName);
}
}
}
}
// check balance in partitions per node
if (partitionCount.size() > 0) {
boolean partitionMapDividesEvenly = partitionSum % partitionCount.size() == 0;
boolean withinAverage =
withinAverage(partitionCount, _isEmptyAllowed, partitionMapDividesEvenly);
if (!withinAverage) {
LOG.error("partition counts deviate from average");
return false;
}
} else {
if (!_isEmptyAllowed) {
LOG.error("partition assignments are empty");
return false;
}
}
// check balance in masters per node
if (masterCount.size() > 0) {
boolean masterMapDividesEvenly = masterSum % masterCount.size() == 0;
boolean withinAverage = withinAverage(masterCount, _isEmptyAllowed, masterMapDividesEvenly);
if (!withinAverage) {
LOG.error("master counts deviate from average");
return false;
}
} else {
if (!_isEmptyAllowed) {
LOG.error("master assignments are empty");
return false;
}
}
// check balance in slaves per node
if (slaveCount.size() > 0) {
boolean slaveMapDividesEvenly = slaveSum % slaveCount.size() == 0;
boolean withinAverage = withinAverage(slaveCount, true, slaveMapDividesEvenly);
if (!withinAverage) {
LOG.error("slave counts deviate from average");
return false;
}
}
return true;
}
private void incrementCount(Map<String, Integer> countMap, String key) {
if (!countMap.containsKey(key)) {
countMap.put(key, 0);
}
countMap.put(key, countMap.get(key) + 1);
}
private boolean withinAverage(Map<String, Integer> countMap, boolean isEmptyAllowed,
boolean dividesEvenly) {
if (countMap.size() == 0) {
if (!isEmptyAllowed) {
LOG.error("Map not allowed to be empty");
return false;
}
return true;
}
int upperBound = 1;
if (!dividesEvenly) {
upperBound = 2;
}
int average = computeAverage(countMap);
if (average == -1) {
return false;
}
for (String participantName : countMap.keySet()) {
int count = countMap.get(participantName);
if (count < average - 1 || count > average + upperBound) {
LOG.error("Count " + count + " for " + participantName + " too far from average of "
+ average);
return false;
}
}
return true;
}
private int computeAverage(Map<String, Integer> countMap) {
if (countMap.size() == 0) {
return -1;
}
int total = 0;
for (int value : countMap.values()) {
total += value;
}
return total / countMap.size();
}
@Override
public ZkClient getZkClient() {
return (ZkClient) _zkClient;
}
@Override
public String getClusterName() {
return _clusterName;
}
}
}
| 9,534 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestCustomIdealState.java
|
package org.apache.helix.integration.rebalancer;
/*
* 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.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.integration.TestDriver;
import org.apache.helix.tools.ClusterSetup;
import org.testng.annotations.Test;
public class TestCustomIdealState extends ZkTestBase {
@Test
public void testBasic() throws Exception {
int numResources = 2;
int numPartitionsPerResource = 100;
int numInstance = 5;
int replica = 3;
String uniqClusterName = "TestCustomIS_" + "rg" + numResources + "_p" + numPartitionsPerResource
+ "_n" + numInstance + "_r" + replica + "_basic";
System.out.println("START " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
TestDriver.setupClusterWithoutRebalance(uniqClusterName, ZK_ADDR, numResources,
numPartitionsPerResource, numInstance, replica);
for (int i = 0; i < numInstance; i++) {
TestDriver.startDummyParticipant(uniqClusterName, i);
}
TestDriver.startController(uniqClusterName);
TestDriver.setIdealState(uniqClusterName, 2000, 50);
TestDriver.verifyCluster(uniqClusterName, 3000, 50 * 1000);
TestDriver.stopCluster(uniqClusterName);
deleteCluster(uniqClusterName);
System.out.println("STOP " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testNonAliveInstances() throws Exception {
int numResources = 2;
int numPartitionsPerResource = 50;
int numInstance = 5;
int replica = 3;
String uniqClusterName = "TestCustomIS_" + "rg" + numResources + "_p" + numPartitionsPerResource
+ "_n" + numInstance + "_r" + replica + "_nonalive";
System.out.println("START " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
TestDriver.setupClusterWithoutRebalance(uniqClusterName, ZK_ADDR, numResources,
numPartitionsPerResource, numInstance, replica);
for (int i = 0; i < numInstance / 2; i++) {
TestDriver.startDummyParticipant(uniqClusterName, i);
}
TestDriver.startController(uniqClusterName);
TestDriver.setIdealState(uniqClusterName, 0, 100);
// wait some time for customized ideal state being populated
Thread.sleep(1000);
// start the rest of participants after ideal state is set
for (int i = numInstance / 2; i < numInstance; i++) {
TestDriver.startDummyParticipant(uniqClusterName, i);
}
TestDriver.verifyCluster(uniqClusterName, 4000, 50 * 1000);
TestDriver.stopCluster(uniqClusterName);
deleteCluster(uniqClusterName);
System.out.println("STOP " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test()
public void testDrop() throws Exception {
int numResources = 2;
int numPartitionsPerResource = 50;
int numInstance = 5;
int replica = 3;
String uniqClusterName = "TestCustomIS_" + "rg" + numResources + "_p" + numPartitionsPerResource
+ "_n" + numInstance + "_r" + replica + "_drop";
System.out.println("START " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
TestDriver.setupClusterWithoutRebalance(uniqClusterName, ZK_ADDR, numResources,
numPartitionsPerResource, numInstance, replica);
for (int i = 0; i < numInstance; i++) {
TestDriver.startDummyParticipant(uniqClusterName, i);
}
TestDriver.startController(uniqClusterName);
TestDriver.setIdealState(uniqClusterName, 2000, 50);
TestDriver.verifyCluster(uniqClusterName, 3000, 50 * 1000);
// drop resource group
ClusterSetup setup = new ClusterSetup(ZK_ADDR);
setup.dropResourceFromCluster(uniqClusterName, "TestDB0");
TestHelper.verifyWithTimeout("verifyEmptyCurStateAndExtView", 30 * 1000, uniqClusterName,
"TestDB0", TestHelper.setOf("localhost_12918", "localhost_12919",
"localhost_12920", "localhost_12921", "localhost_12922"),
ZK_ADDR);
TestDriver.stopCluster(uniqClusterName);
deleteCluster(uniqClusterName);
System.out.println("STOP " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,535 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/WagedRebalancer/TestWagedLoadedCluster.java
|
package org.apache.helix.integration.rebalancer.WagedRebalancer;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional warnrmation
* 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.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import com.google.common.collect.ImmutableMap;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.rebalancer.waged.AssignmentMetadataStore;
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.ZkBucketDataAccessor;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.Message;
import org.apache.helix.model.ResourceAssignment;
import org.apache.helix.model.ResourceConfig;
import org.apache.helix.participant.StateMachineEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* This test case is specially targeting for n - n+1 issue.
*
* Initially, all the partitions are equal size and equal weight
* from both CU, DISK.
* All the nodes are equally loaded.
* The test case will do the following:
* For one resource, we will double its CU weight.
* The rebalancer will be triggered.
*
* We have a monitoring thread which is constantly monitoring the instance capacity.
* - It looks at current state resource assignment + pending messages
* - it has ASSERT in place to make sure we NEVER cross instance capacity (CU)
*/
public class TestWagedLoadedCluster extends ZkTestBase {
protected final int NUM_NODE = 6;
protected static final int START_PORT = 13000;
protected static final int PARTITIONS = 10;
protected static final String CLASS_NAME = TestWagedLoadedCluster.class.getSimpleName();
protected static final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected ClusterControllerManager _controller;
protected AssignmentMetadataStore _assignmentMetadataStore;
List<MockParticipantManager> _participants = new ArrayList<>();
List<String> _nodes = new ArrayList<>();
private final Set<String> _allDBs = new HashSet<>();
private CountDownLatch _completedTest = new CountDownLatch(1);
private CountDownLatch _weightUpdatedLatch = new CountDownLatch(1); // when 0, weight is updated
private Thread _verifyThread = null;
private final Map<String, Integer> _defaultInstanceCapacity =
ImmutableMap.of("CU", 50, "DISK", 50);
private final Map<String, Integer> _defaultPartitionWeight =
ImmutableMap.of("CU", 10, "DISK", 10);
private final Map<String, Integer> _newPartitionWeight =
ImmutableMap.of("CU", 20, "DISK", 10);
private final int DEFAULT_DELAY = 500; // 0.5 second
private static final Logger LOG = LoggerFactory.getLogger(CLASS_NAME);
@BeforeClass
public void beforeClass() throws Exception {
LOG.info("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
// create 6 node cluster
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
_nodes.add(storageNodeName);
}
// ST downward message will get delayed by 5sec.
startParticipants(DEFAULT_DELAY);
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
_assignmentMetadataStore =
new AssignmentMetadataStore(new ZkBucketDataAccessor(ZK_ADDR), CLUSTER_NAME) {
public Map<String, ResourceAssignment> getBaseline() {
// Ensure this metadata store always read from the ZK without using cache.
super.reset();
return super.getBaseline();
}
public synchronized Map<String, ResourceAssignment> getBestPossibleAssignment() {
// Ensure this metadata store always read from the ZK without using cache.
super.reset();
return super.getBestPossibleAssignment();
}
};
// Set test instance capacity and partition weights
HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
ClusterConfig clusterConfig =
dataAccessor.getProperty(dataAccessor.keyBuilder().clusterConfig());
clusterConfig.setDefaultInstanceCapacityMap(_defaultInstanceCapacity);
clusterConfig.setDefaultPartitionWeightMap(_defaultPartitionWeight);
dataAccessor.setProperty(dataAccessor.keyBuilder().clusterConfig(), clusterConfig);
// Create 3 resources with 2 partitions each.
for (int i = 0; i < 3; i++) {
String db = "Test-WagedDB-" + i;
createResourceWithWagedRebalance(CLUSTER_NAME, db, BuiltInStateModelDefinitions.MasterSlave.name(),
2 /*numPartitions*/, 3 /*replicas*/, 3 /*minActiveReplicas*/);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, 3);
_allDBs.add(db);
}
// Start a thread which will keep validating instance usage using currentState and pending messages.
_verifyThread = new Thread(() -> {
while (_completedTest.getCount() > 0) {
try {
validateInstanceUsage();
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
LOG.debug("Exception in validateInstanceUsageThread", e);
} catch (Exception e) {
LOG.error("Exception in validateInstanceUsageThread", e);
}
}
});
}
public boolean validateInstanceUsage() {
try {
HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
PropertyKey.Builder propertyKeyBuilder = dataAccessor.keyBuilder();
// For each instance, get the currentState map and pending messages.
for (MockParticipantManager participant : _participants) {
String instance = participant.getInstanceName();
int totalCUUsage = 0;
List<String> resourceNames = dataAccessor.
getChildNames(propertyKeyBuilder.currentStates(instance, participant.getSessionId()));
for (String resourceName : resourceNames) {
PropertyKey currentStateKey = propertyKeyBuilder.currentState(instance,
participant.getSessionId(), resourceName);
CurrentState currentState = dataAccessor.getProperty(currentStateKey);
if (currentState != null && currentState.getPartitionStateMap().size() > 0) {
if (_weightUpdatedLatch.getCount() == 0 && resourceName.equals("Test-WagedDB-0")) {
// For Test-WagedDB-0, the partition weight is updated to 20 CU.
totalCUUsage += currentState.getPartitionStateMap().size() * 20;
} else {
totalCUUsage += currentState.getPartitionStateMap().size() * 10;
}
}
}
List<Message> messages = dataAccessor.getChildValues(dataAccessor.keyBuilder().messages(instance), false);
for (Message m : messages) {
if (m.getFromState().equals("OFFLINE") && m.getToState().equals("SLAVE")) {
totalCUUsage += 10;
}
}
assert(totalCUUsage <= 50);
}
} catch (Exception e) {
LOG.error("Exception in validateInstanceUsage", e);
return false;
}
return true;
}
private void startParticipants(int delay) {
// start dummy participants
for (String node : _nodes) {
MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
StateMachineEngine stateMach = participant.getStateMachineEngine();
TestWagedClusterExpansion.WagedDelayMSStateModelFactory delayFactory =
new TestWagedClusterExpansion.WagedDelayMSStateModelFactory().setDelay(delay);
stateMach.registerStateModelFactory("MasterSlave", delayFactory);
participant.syncStart();
_participants.add(participant);
}
}
@Test
public void testUpdateInstanceCapacity() throws Exception {
// Check modified time for external view of the first resource.
// if pipeline is run, then external view would be persisted.
_verifyThread.start();
// Update the weight for one of the resource.
HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
String db = "Test-WagedDB-0";
ResourceConfig resourceConfig = dataAccessor.getProperty(dataAccessor.keyBuilder().resourceConfig(db));
if (resourceConfig == null) {
resourceConfig = new ResourceConfig(db);
}
resourceConfig.setPartitionCapacityMap(
Collections.singletonMap(ResourceConfig.DEFAULT_PARTITION_KEY, _newPartitionWeight));
dataAccessor.setProperty(dataAccessor.keyBuilder().resourceConfig(db), resourceConfig);
Thread.currentThread().sleep(100);
_weightUpdatedLatch.countDown();
Thread.currentThread().sleep(3000);
_completedTest.countDown();
Thread.currentThread().sleep(100);
}
@AfterClass
public void afterClass() throws Exception {
try {
if (_controller != null && _controller.isConnected()) {
_controller.syncStop();
}
for (MockParticipantManager p : _participants) {
if (p != null && p.isConnected()) {
p.syncStop();
}
}
deleteCluster(CLUSTER_NAME);
//_verifyThread.interrupt();
} catch (Exception e) {
LOG.info("After class throwing exception, {}", e);
}
}
}
| 9,536 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/WagedRebalancer/TestWagedRebalanceTopologyAware.java
|
package org.apache.helix.integration.rebalancer.WagedRebalancer;
/*
* 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.ConfigAccessor;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.InstanceConfig;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestWagedRebalanceTopologyAware extends TestWagedRebalanceFaultZone {
private static final String TOLOPOGY_DEF = "/DOMAIN/ZONE/INSTANCE";
private static final String DOMAIN_NAME = "Domain";
private static final String FAULT_ZONE = "ZONE";
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setTopology(TOLOPOGY_DEF);
clusterConfig.setFaultZoneType(FAULT_ZONE);
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
addInstanceConfig(storageNodeName, i, ZONES, TAGS);
}
// start dummy participants
for (String node : _nodes) {
MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
enableTopologyAwareRebalance(_gZkClient, CLUSTER_NAME, true);
}
protected void addInstanceConfig(String storageNodeName, int seqNo, int zoneCount, int tagCount) {
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
String zone = "zone-" + seqNo % zoneCount;
String tag = "tag-" + seqNo % tagCount;
InstanceConfig config =
_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, storageNodeName);
config.setDomain(
String.format("DOMAIN=%s,ZONE=%s,INSTANCE=%s", DOMAIN_NAME, zone, storageNodeName));
config.addTag(tag);
_gSetupTool.getClusterManagementTool().setInstanceConfig(CLUSTER_NAME, storageNodeName, config);
_nodeToZoneMap.put(storageNodeName, zone);
_nodeToTagMap.put(storageNodeName, tag);
_nodes.add(storageNodeName);
}
@Test
public void testZoneIsolation() throws Exception {
super.testZoneIsolation();
}
@Test
public void testZoneIsolationWithInstanceTag() throws Exception {
super.testZoneIsolationWithInstanceTag();
}
@Test(dependsOnMethods = { "testZoneIsolation", "testZoneIsolationWithInstanceTag" })
public void testLackEnoughLiveRacks() throws Exception {
super.testLackEnoughLiveRacks();
}
@Test(dependsOnMethods = { "testLackEnoughLiveRacks" })
public void testLackEnoughRacks() throws Exception {
super.testLackEnoughRacks();
}
@Test(dependsOnMethods = { "testZoneIsolation", "testZoneIsolationWithInstanceTag" })
public void testAddZone() throws Exception {
super.testAddZone();
}
}
| 9,537 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/WagedRebalancer/TestDelayedWagedRebalanceWithDisabledInstance.java
|
package org.apache.helix.integration.rebalancer.WagedRebalancer;
/*
* 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.HashMap;
import java.util.Map;
import org.apache.helix.TestHelper;
import org.apache.helix.integration.rebalancer.DelayedAutoRebalancer.TestDelayedAutoRebalanceWithDisabledInstance;
import org.apache.helix.model.ExternalView;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Inherit TestDelayedAutoRebalanceWithDisabledInstance to ensure the test logic is the same.
*/
public class TestDelayedWagedRebalanceWithDisabledInstance extends TestDelayedAutoRebalanceWithDisabledInstance {
// create test DBs, wait it converged and return externalviews
protected Map<String, ExternalView> createTestDBs(long delayTime)
throws InterruptedException {
Map<String, ExternalView> externalViews = new HashMap<>();
int i = 0;
for (String stateModel : TestStateModels) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_minActiveReplica);
_testDBs.add(db);
}
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
externalViews.put(db, ev);
}
return externalViews;
}
@Test
public void testDelayedPartitionMovement() {
// Waged Rebalancer takes cluster level delay config only. Skip this test.
}
@Test
public void testDisableDelayRebalanceInResource() {
// Waged Rebalancer takes cluster level delay config only. Skip this test.
}
@Test(dependsOnMethods = {"testDelayedPartitionMovement"})
public void testDelayedPartitionMovementWithClusterConfigedDelay()
throws Exception {
super.testDelayedPartitionMovementWithClusterConfigedDelay();
}
@Test(dependsOnMethods = {"testDelayedPartitionMovementWithClusterConfigedDelay"})
public void testMinimalActiveReplicaMaintain()
throws Exception {
super.testMinimalActiveReplicaMaintain();
}
@Test(dependsOnMethods = {"testDelayedPartitionMovement"})
public void testMinimalActiveReplicaMaintainWithOneOffline() throws Exception {
super.testMinimalActiveReplicaMaintainWithOneOffline();
}
@Test(dependsOnMethods = {"testMinimalActiveReplicaMaintain"})
public void testPartitionMovementAfterDelayTime()
throws Exception {
super.testPartitionMovementAfterDelayTime();
}
@Test(dependsOnMethods = {"testDisableDelayRebalanceInResource"})
public void testDisableDelayRebalanceInCluster()
throws Exception {
super.testDisableDelayRebalanceInCluster();
}
@Test(dependsOnMethods = {"testDisableDelayRebalanceInCluster"})
public void testDisableDelayRebalanceInInstance()
throws Exception {
super.testDisableDelayRebalanceInInstance();
}
@Test(dependsOnMethods = {"testDisableDelayRebalanceInInstance"})
public void testOnDemandRebalance() throws Exception {
super.testOnDemandRebalance();
}
@Test(dependsOnMethods = {"testOnDemandRebalance"})
public void testExpiredOnDemandRebalanceTimestamp() throws Exception {
super.testExpiredOnDemandRebalanceTimestamp();
}
@Test(dependsOnMethods = {"testExpiredOnDemandRebalanceTimestamp"})
public void testOnDemandRebalanceAfterDelayRebalanceHappen() throws Exception {
super.testOnDemandRebalanceAfterDelayRebalanceHappen();
}
}
| 9,538 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/WagedRebalancer/TestWagedRebalance.java
|
package org.apache.helix.integration.rebalancer.WagedRebalancer;
/*
* 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.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableMap;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixException;
import org.apache.helix.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.controller.rebalancer.strategy.CrushRebalanceStrategy;
import org.apache.helix.controller.rebalancer.util.RebalanceScheduler;
import org.apache.helix.controller.rebalancer.waged.AssignmentMetadataStore;
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.ZkBucketDataAccessor;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.ResourceAssignment;
import org.apache.helix.model.ResourceConfig;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.tools.ClusterVerifiers.HelixClusterVerifier;
import org.apache.helix.tools.ClusterVerifiers.StrictMatchExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.apache.helix.util.HelixUtil;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestWagedRebalance extends ZkTestBase {
protected final int NUM_NODE = 6;
protected static final int START_PORT = 12918;
protected static final int PARTITIONS = 20;
protected static final int TAGS = 2;
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected ClusterControllerManager _controller;
protected AssignmentMetadataStore _assignmentMetadataStore;
List<MockParticipantManager> _participants = new ArrayList<>();
Map<String, String> _nodeToTagMap = new HashMap<>();
List<String> _nodes = new ArrayList<>();
private Set<String> _allDBs = new HashSet<>();
private int _replica = 3;
private static String[] _testModels = {
BuiltInStateModelDefinitions.OnlineOffline.name(),
BuiltInStateModelDefinitions.MasterSlave.name(),
BuiltInStateModelDefinitions.LeaderStandby.name()
};
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
addInstanceConfig(storageNodeName, i, TAGS);
}
// start dummy participants
for (String node : _nodes) {
MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
// It's a hacky way to workaround the package restriction. Note that we still want to hide the
// AssignmentMetadataStore constructor to prevent unexpected update to the assignment records.
_assignmentMetadataStore =
new AssignmentMetadataStore(new ZkBucketDataAccessor(ZK_ADDR), CLUSTER_NAME) {
public Map<String, ResourceAssignment> getBaseline() {
// Ensure this metadata store always read from the ZK without using cache.
super.reset();
return super.getBaseline();
}
public synchronized Map<String, ResourceAssignment> getBestPossibleAssignment() {
// Ensure this metadata store always read from the ZK without using cache.
super.reset();
return super.getBestPossibleAssignment();
}
};
// Set test instance capacity and partition weights
HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
ClusterConfig clusterConfig =
dataAccessor.getProperty(dataAccessor.keyBuilder().clusterConfig());
String testCapacityKey = "TestCapacityKey";
clusterConfig.setInstanceCapacityKeys(Collections.singletonList(testCapacityKey));
clusterConfig.setDefaultInstanceCapacityMap(Collections.singletonMap(testCapacityKey, 100));
clusterConfig.setDefaultPartitionWeightMap(Collections.singletonMap(testCapacityKey, 1));
dataAccessor.setProperty(dataAccessor.keyBuilder().clusterConfig(), clusterConfig);
}
protected void addInstanceConfig(String storageNodeName, int seqNo, int tagCount) {
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
String tag = "tag-" + seqNo % tagCount;
_gSetupTool.getClusterManagementTool().addInstanceTag(CLUSTER_NAME, storageNodeName, tag);
_nodeToTagMap.put(storageNodeName, tag);
_nodes.add(storageNodeName);
}
@Test
public void test() throws Exception {
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
validate(_replica);
// Adding 3 more resources
i = 0;
for (String stateModel : _testModels) {
String moreDB = "More-Test-DB-" + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, moreDB, stateModel, PARTITIONS, _replica,
_replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, moreDB, _replica);
_allDBs.add(moreDB);
validate(_replica);
}
// Drop the 3 additional resources
for (int j = 0; j < 3; j++) {
String moreDB = "More-Test-DB-" + j++;
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, moreDB);
_allDBs.remove(moreDB);
validate(_replica);
}
}
/**
* Use HelixUtil.getIdealAssignmentForWagedFullAuto() to compute the cluster-wide assignment and
* verify that it matches with the result from the original WAGED rebalancer's algorithm result.
*/
@Test(dependsOnMethods = "test")
public void testRebalanceTool() throws InterruptedException {
// Create resources for testing
// It is important to let controller to use sync mode the same as getTargetAssignmentForWagedFullAuto
// to make the test correct and stable.
HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
ClusterConfig clusterConfigGlobal =
dataAccessor.getProperty(dataAccessor.keyBuilder().clusterConfig());
clusterConfigGlobal.setGlobalRebalanceAsyncMode(false);
dataAccessor.setProperty(dataAccessor.keyBuilder().clusterConfig(), clusterConfigGlobal);
try {
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
validate(_replica);
// Read cluster parameters from ZK
dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
ClusterConfig clusterConfig = dataAccessor.getProperty(dataAccessor.keyBuilder().clusterConfig());
List<InstanceConfig> instanceConfigs = dataAccessor.getChildValues(dataAccessor.keyBuilder().instanceConfigs(), true);
List<String> liveInstances = dataAccessor.getChildNames(dataAccessor.keyBuilder().liveInstances());
List<IdealState> idealStates = dataAccessor.getChildValues(dataAccessor.keyBuilder().idealStates(), true);
List<ResourceConfig> resourceConfigs = dataAccessor.getChildValues(dataAccessor.keyBuilder().resourceConfigs(), true);
// Verify that utilResult contains the assignment for the resources added
Map<String, ResourceAssignment> utilResult = HelixUtil
.getTargetAssignmentForWagedFullAuto(ZK_ADDR, clusterConfig, instanceConfigs,
liveInstances, idealStates, resourceConfigs);
Assert.assertNotNull(utilResult);
Assert.assertEquals(utilResult.size(), idealStates.size());
for (IdealState idealState : idealStates) {
Assert.assertTrue(utilResult.containsKey(idealState.getResourceName()));
StateModelDefinition stateModelDefinition =
BuiltInStateModelDefinitions.valueOf(idealState.getStateModelDefRef()).getStateModelDefinition();
for (String partition : idealState.getPartitionSet()) {
Assert.assertEquals(utilResult.get(idealState.getResourceName()).getRecord().getMapField(partition),
HelixUtil.computeIdealMapping(idealState.getPreferenceList(partition),
stateModelDefinition, new HashSet<>(liveInstances)));
}
}
// Verify that the partition state mapping mode also works
Map<String, ResourceAssignment> paritionMappingBasedResult = HelixUtil
.getImmediateAssignmentForWagedFullAuto(ZK_ADDR, clusterConfig, instanceConfigs,
liveInstances, idealStates, resourceConfigs);
Assert.assertNotNull(paritionMappingBasedResult);
Assert.assertEquals(paritionMappingBasedResult.size(), idealStates.size());
for (IdealState idealState : idealStates) {
Assert.assertTrue(paritionMappingBasedResult.containsKey(idealState.getResourceName()));
Assert.assertEquals(
paritionMappingBasedResult.get(idealState.getResourceName()).getRecord().getMapFields(),
idealState.getRecord().getMapFields());
}
// Try to add a few extra instances
String instance_0 = "instance_0";
String instance_1 = "instance_1";
Set<String> newInstances = new HashSet<>();
newInstances.add(instance_0);
newInstances.add(instance_1);
liveInstances.addAll(newInstances);
for (String instance : newInstances) {
InstanceConfig instanceConfig = new InstanceConfig(instance);
instanceConfigs.add(instanceConfig);
}
utilResult = HelixUtil
.getTargetAssignmentForWagedFullAuto(ZK_ADDR, clusterConfig, instanceConfigs,
liveInstances, idealStates, resourceConfigs);
Set<String> instancesWithAssignments = new HashSet<>();
utilResult.values().forEach(
resourceAssignment -> resourceAssignment.getRecord().getMapFields().values().forEach(entry -> instancesWithAssignments.addAll(entry.keySet())));
// The newly added instances should contain some partitions
Assert.assertTrue(instancesWithAssignments.contains(instance_0));
Assert.assertTrue(instancesWithAssignments.contains(instance_1));
// Perform the same test with immediate assignment
utilResult = HelixUtil
.getImmediateAssignmentForWagedFullAuto(ZK_ADDR, clusterConfig, instanceConfigs,
liveInstances, idealStates, resourceConfigs);
Set<String> instancesWithAssignmentsImmediate = new HashSet<>();
utilResult.values().forEach(
resourceAssignment -> resourceAssignment.getRecord().getMapFields().values().forEach(entry -> instancesWithAssignmentsImmediate.addAll(entry.keySet())));
// The newly added instances should contain some partitions
Assert.assertTrue(instancesWithAssignmentsImmediate.contains(instance_0));
Assert.assertTrue(instancesWithAssignmentsImmediate.contains(instance_1));
// Force FAILED_TO_CALCULATE and ensure that both util functions return no mappings
String testCapacityKey = "key";
clusterConfig.setDefaultPartitionWeightMap(Collections.singletonMap(testCapacityKey, 2));
clusterConfig.setDefaultInstanceCapacityMap(Collections.singletonMap(testCapacityKey, 1));
clusterConfig.setInstanceCapacityKeys(Collections.singletonList(testCapacityKey));
try {
HelixUtil.getTargetAssignmentForWagedFullAuto(ZK_ADDR, clusterConfig, instanceConfigs,
liveInstances, idealStates, resourceConfigs);
Assert.fail("Expected HelixException for calculaation failure");
} catch (HelixException e) {
Assert.assertEquals(e.getMessage(),
"getIdealAssignmentForWagedFullAuto(): Calculation failed: Failed to compute BestPossibleState!");
}
try {
HelixUtil.getImmediateAssignmentForWagedFullAuto(ZK_ADDR, clusterConfig, instanceConfigs,
liveInstances, idealStates, resourceConfigs);
Assert.fail("Expected HelixException for calculaation failure");
} catch (HelixException e) {
Assert.assertEquals(e.getMessage(),
"getIdealAssignmentForWagedFullAuto(): Calculation failed: Failed to compute BestPossibleState!");
}
} finally {
// restore the config with async mode
clusterConfigGlobal =
dataAccessor.getProperty(dataAccessor.keyBuilder().clusterConfig());
clusterConfigGlobal.setGlobalRebalanceAsyncMode(true);
dataAccessor.setProperty(dataAccessor.keyBuilder().clusterConfig(), clusterConfigGlobal);
}
}
@Test(dependsOnMethods = "test")
public void testWithInstanceTag() throws Exception {
Set<String> tags = new HashSet<String>(_nodeToTagMap.values());
int i = 3;
for (String tag : tags) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db,
BuiltInStateModelDefinitions.MasterSlave.name(), PARTITIONS, _replica, _replica);
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
is.setInstanceGroupTag(tag);
_gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, db, is);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
validate(_replica);
}
@Test(dependsOnMethods = "test")
public void testChangeIdealState() throws InterruptedException {
String dbName = "Test-DB-" + TestHelper.getTestMethodName();
createResourceWithWagedRebalance(CLUSTER_NAME, dbName,
BuiltInStateModelDefinitions.MasterSlave.name(), PARTITIONS, _replica, _replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, _replica);
_allDBs.add(dbName);
validate(_replica);
// Adjust the replica count
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
int newReplicaFactor = _replica - 1;
is.setReplicas("" + newReplicaFactor);
_gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, dbName, is);
validate(newReplicaFactor);
// Adjust the partition list
is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
is.setNumPartitions(PARTITIONS + 1);
_gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, dbName, is);
_gSetupTool.getClusterManagementTool().rebalance(CLUSTER_NAME, dbName, newReplicaFactor);
validate(newReplicaFactor);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, dbName);
Assert.assertEquals(ev.getPartitionSet().size(), PARTITIONS + 1);
// Customize the partition list instead of calling rebalance.
// So there is no other changes in the IdealState. The rebalancer shall still trigger
// new baseline calculation in this case.
is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
is.setPreferenceList(dbName + "_customizedPartition", Collections.EMPTY_LIST);
_gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, dbName, is);
validate(newReplicaFactor);
ev = _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, dbName);
Assert.assertEquals(ev.getPartitionSet().size(), PARTITIONS + 2);
}
@Test(dependsOnMethods = "test")
public void testDisableInstance() throws InterruptedException {
String dbName = "Test-DB-" + TestHelper.getTestMethodName();
createResourceWithWagedRebalance(CLUSTER_NAME, dbName,
BuiltInStateModelDefinitions.MasterSlave.name(), PARTITIONS, _replica, _replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, _replica);
_allDBs.add(dbName);
validate(_replica);
// Disable participants, keep only three left
Set<String> disableParticipants = new HashSet<>();
try {
for (int i = 3; i < _participants.size(); i++) {
MockParticipantManager p = _participants.get(i);
disableParticipants.add(p.getInstanceName());
InstanceConfig config = _gSetupTool.getClusterManagementTool()
.getInstanceConfig(CLUSTER_NAME, p.getInstanceName());
config.setInstanceEnabled(false);
_gSetupTool.getClusterManagementTool()
.setInstanceConfig(CLUSTER_NAME, p.getInstanceName(), config);
}
validate(_replica);
// Verify there is no assignment on the disabled participants.
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, dbName);
for (String partition : ev.getPartitionSet()) {
Map<String, String> replicaStateMap = ev.getStateMap(partition);
for (String instance : replicaStateMap.keySet()) {
Assert.assertFalse(disableParticipants.contains(instance));
}
}
} finally {
// recover the config
for (String instanceName : disableParticipants) {
InstanceConfig config =
_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, instanceName);
config.setInstanceEnabled(true);
_gSetupTool.getClusterManagementTool()
.setInstanceConfig(CLUSTER_NAME, instanceName, config);
}
}
}
@Test(dependsOnMethods = "testDisableInstance")
public void testLackEnoughLiveInstances() throws Exception {
// shutdown participants, keep only two left
for (int i = 2; i < _participants.size(); i++) {
_participants.get(i).syncStop();
}
int j = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + j++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
// Verify if the partitions get assigned
validate(2);
// restart the participants within the zone
for (int i = 2; i < _participants.size(); i++) {
MockParticipantManager p = _participants.get(i);
MockParticipantManager newNode =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, p.getInstanceName());
_participants.set(i, newNode);
newNode.syncStart();
}
// Verify if the partitions get assigned
validate(_replica);
}
@Test(dependsOnMethods = "testDisableInstance")
public void testLackEnoughInstances() throws Exception {
// shutdown participants, keep only two left
for (int i = 2; i < _participants.size(); i++) {
MockParticipantManager p = _participants.get(i);
p.syncStop();
_gSetupTool.getClusterManagementTool()
.enableInstance(CLUSTER_NAME, p.getInstanceName(), false);
_gSetupTool.dropInstanceFromCluster(CLUSTER_NAME, p.getInstanceName());
}
int j = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + j++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
// Verify if the partitions get assigned
validate(2);
// Create new participants within the zone
for (int i = 2; i < _participants.size(); i++) {
MockParticipantManager p = _participants.get(i);
String replaceNodeName = p.getInstanceName() + "-replacement_" + START_PORT;
addInstanceConfig(replaceNodeName, i, TAGS);
MockParticipantManager newNode =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, replaceNodeName);
_participants.set(i, newNode);
newNode.syncStart();
}
// Verify if the partitions get assigned
validate(_replica);
}
@Test(dependsOnMethods = "test")
public void testMixedRebalancerUsage() throws InterruptedException {
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + i++;
if (i == 0) {
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db, PARTITIONS, stateModel,
IdealState.RebalanceMode.FULL_AUTO + "", CrushRebalanceStrategy.class.getName());
} else if (i == 1) {
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db, PARTITIONS, stateModel,
IdealState.RebalanceMode.FULL_AUTO + "", CrushEdRebalanceStrategy.class.getName());
} else {
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_replica);
}
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
validate(_replica);
}
@Test(dependsOnMethods = "test")
public void testMaxPartitionLimitation() throws Exception {
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
// Change the cluster level config so no assignment can be done
clusterConfig.setMaxPartitionsPerInstance(1);
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
try {
String limitedResourceName = null;
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_replica);
if (i == 1) {
// The limited resource has additional limitation.
// The other resources could have been assigned in theory if the WAGED rebalancer were
// not used.
// However, with the WAGED rebalancer, this restricted resource will block the other ones.
limitedResourceName = db;
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
idealState.setMaxPartitionsPerInstance(1);
_gSetupTool.getClusterManagementTool()
.setResourceIdealState(CLUSTER_NAME, db, idealState);
}
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
Thread.sleep(300);
// Since the WAGED rebalancer need to finish rebalancing every resources, the initial
// assignment won't show.
Assert.assertFalse(TestHelper.verify(() -> _allDBs.stream().anyMatch(db -> {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
return ev != null && !ev.getPartitionSet().isEmpty();
}), 2000));
// Remove the cluster level limitation
clusterConfig.setMaxPartitionsPerInstance(-1);
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
Thread.sleep(300);
// Since the WAGED rebalancer need to finish rebalancing every resources, the assignment won't
// show even removed cluster level restriction
Assert.assertFalse(TestHelper.verify(() -> _allDBs.stream().anyMatch(db -> {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
return ev != null && !ev.getPartitionSet().isEmpty();
}), 2000));
// Remove the resource level limitation
IdealState idealState = _gSetupTool.getClusterManagementTool()
.getResourceIdealState(CLUSTER_NAME, limitedResourceName);
idealState.setMaxPartitionsPerInstance(Integer.MAX_VALUE);
_gSetupTool.getClusterManagementTool()
.setResourceIdealState(CLUSTER_NAME, limitedResourceName, idealState);
validate(_replica);
} finally {
// recover the config change
clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setMaxPartitionsPerInstance(-1);
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
}
}
@Test(dependsOnMethods = "test")
public void testNewInstances() throws InterruptedException {
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setGlobalRebalancePreference(ImmutableMap
.of(ClusterConfig.GlobalRebalancePreferenceKey.EVENNESS, 0,
ClusterConfig.GlobalRebalancePreferenceKey.LESS_MOVEMENT, 10));
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
validate(_replica);
String newNodeName = "newNode-" + TestHelper.getTestMethodName() + "_" + START_PORT;
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, newNodeName);
try {
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, newNodeName);
participant.syncStart();
validate(_replica);
Assert.assertFalse(_allDBs.stream().anyMatch(db -> {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
for (String partition : ev.getPartitionSet()) {
if (ev.getStateMap(partition).containsKey(newNodeName)) {
return true;
}
}
return false;
}));
clusterConfig.setGlobalRebalancePreference(ClusterConfig.DEFAULT_GLOBAL_REBALANCE_PREFERENCE);
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
validate(_replica);
Assert.assertTrue(_allDBs.stream().anyMatch(db -> {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
for (String partition : ev.getPartitionSet()) {
if (ev.getStateMap(partition).containsKey(newNodeName)) {
return true;
}
}
return false;
}));
} finally {
if (participant != null && participant.isConnected()) {
participant.syncStop();
}
}
}
/**
* The stateful WAGED rebalancer will be reset while the controller regains the leadership.
* This test is to verify if the reset has been done and the rebalancer has forgotten any previous
* status after leadership switched.
*/
@Test(dependsOnMethods = "test")
public void testRebalancerReset() throws Exception {
// Configure the rebalance preference so as to trigger more partition movements for evenness.
// This is to ensure the controller will try to move something if the rebalancer has been reset.
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setGlobalRebalancePreference(ImmutableMap
.of(ClusterConfig.GlobalRebalancePreferenceKey.EVENNESS, 10,
ClusterConfig.GlobalRebalancePreferenceKey.LESS_MOVEMENT, 0));
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
validate(_replica);
// Adding one more resource. Since it is added after the other resources, the assignment is
// impacted because of the other resources' assignment.
String moreDB = "More-Test-DB";
createResourceWithWagedRebalance(CLUSTER_NAME, moreDB,
BuiltInStateModelDefinitions.MasterSlave.name(), PARTITIONS, _replica, _replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, moreDB, _replica);
_allDBs.add(moreDB);
validate(_replica);
ExternalView oldEV =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, moreDB);
_controller.handleNewSession();
// Trigger a rebalance to test if the rebalancer calculate with empty cache states.
RebalanceScheduler.invokeRebalance(_controller.getHelixDataAccessor(), moreDB);
// After reset done, the rebalancer will try to rebalance all the partitions since it has
// forgotten the previous state.
validate(_replica);
ExternalView newEV =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, moreDB);
// To verify that the controller has moved some partitions.
Assert.assertFalse(newEV.equals(oldEV));
}
@Test(dependsOnMethods = "test")
public void testRecreateSameResource() throws InterruptedException {
String dbName = "Test-DB-" + TestHelper.getTestMethodName();
createResourceWithWagedRebalance(CLUSTER_NAME, dbName,
BuiltInStateModelDefinitions.MasterSlave.name(), PARTITIONS, _replica, _replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, _replica);
_allDBs.add(dbName);
// waiting for the DBs being dropped.
validate(_replica);
// Record the current Ideal State and Resource Config for recreating.
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
// Drop preserved the DB.
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, dbName);
_allDBs.remove(dbName);
// waiting for the DBs being dropped.
validate(_replica);
// Recreate the DB.
_gSetupTool.getClusterManagementTool().addResource(CLUSTER_NAME, dbName, is);
_allDBs.add(dbName);
// waiting for the DBs to be recreated.
validate(_replica);
}
private void validate(int expectedReplica) {
HelixClusterVerifier _clusterVerifier =
new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
.setDeactivatedNodeAwareness(true).setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
try {
Assert.assertTrue(_clusterVerifier.verify(5000));
} finally {
_clusterVerifier.close();
}
for (String db : _allDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
validateIsolation(is, ev, expectedReplica);
}
}
/**
* Validate each partition is different instances and with necessary tagged instances.
*/
private void validateIsolation(IdealState is, ExternalView ev, int expectedReplica) {
String tag = is.getInstanceGroupTag();
for (String partition : is.getPartitionSet()) {
Map<String, String> assignmentMap = ev.getRecord().getMapField(partition);
Set<String> instancesInEV = assignmentMap.keySet();
Assert.assertEquals(instancesInEV.size(), expectedReplica);
for (String instance : instancesInEV) {
if (tag != null) {
InstanceConfig config =
_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, instance);
Assert.assertTrue(config.containsTag(tag));
}
}
}
}
@AfterMethod
public void afterMethod() throws Exception {
for (String db : _allDBs) {
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, db);
}
// waiting for all DB be dropped.
ZkHelixClusterVerifier _clusterVerifier =
new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
.setDeactivatedNodeAwareness(true).setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
try {
Assert.assertTrue(_clusterVerifier.verifyByPolling());
_allDBs.clear();
} finally {
_clusterVerifier.close();
}
// Verify the DBs are all removed and the persisted assignment records are cleaned up.
Assert.assertEquals(
_gSetupTool.getClusterManagementTool().getResourcesInCluster(CLUSTER_NAME).size(), 0);
Assert.assertTrue(_assignmentMetadataStore.getBestPossibleAssignment().isEmpty());
Assert.assertTrue(_assignmentMetadataStore.getBaseline().isEmpty());
}
@AfterClass
public void afterClass() throws Exception {
if (_controller != null && _controller.isConnected()) {
_controller.syncStop();
}
for (MockParticipantManager p : _participants) {
if (p != null && p.isConnected()) {
p.syncStop();
}
}
deleteCluster(CLUSTER_NAME);
}
}
| 9,539 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/WagedRebalancer/TestWagedNodeSwap.java
|
package org.apache.helix.integration.rebalancer.WagedRebalancer;
/*
* 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.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.apache.helix.ConfigAccessor;
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.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.HelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestWagedNodeSwap extends ZkTestBase {
final int NUM_NODE = 6;
final int NUM_ZONE = 3;
protected static final int START_PORT = 12918;
protected static final int _PARTITIONS = 20;
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected ClusterControllerManager _controller;
protected HelixClusterVerifier _clusterVerifier;
List<MockParticipantManager> _participants = new ArrayList<>();
Set<String> _allDBs = new HashSet<>();
int _replica = 3;
String[] _testModels = { BuiltInStateModelDefinitions.OnlineOffline.name(),
BuiltInStateModelDefinitions.MasterSlave.name(),
BuiltInStateModelDefinitions.LeaderStandby.name()
};
@BeforeClass
public void beforeClass() throws Exception {
_gSetupTool.addCluster(CLUSTER_NAME, true);
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setTopology("/zone/instance");
clusterConfig.setFaultZoneType("zone");
clusterConfig.setDelayRebalaceEnabled(true);
// Set a long enough time to ensure delayed rebalance is activate
clusterConfig.setRebalanceDelayTime(3000000);
// TODO remove this setup once issue https://github.com/apache/helix/issues/532 is fixed
Map<ClusterConfig.GlobalRebalancePreferenceKey, Integer> preference = new HashMap<>();
preference.put(ClusterConfig.GlobalRebalancePreferenceKey.EVENNESS, 0);
preference.put(ClusterConfig.GlobalRebalancePreferenceKey.LESS_MOVEMENT, 10);
clusterConfig.setGlobalRebalancePreference(preference);
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
Set<String> nodes = new HashSet<>();
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
String zone = "zone-" + i % NUM_ZONE;
String domain = String.format("zone=%s,instance=%s", zone, storageNodeName);
InstanceConfig instanceConfig =
configAccessor.getInstanceConfig(CLUSTER_NAME, storageNodeName);
instanceConfig.setDomain(domain);
_gSetupTool.getClusterManagementTool()
.setInstanceConfig(CLUSTER_NAME, storageNodeName, instanceConfig);
nodes.add(storageNodeName);
}
// start dummy participants
for (String node : nodes) {
MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
enableTopologyAwareRebalance(_gZkClient, CLUSTER_NAME, true);
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, _PARTITIONS, _replica,
_replica - 1);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
_clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME).setResources(_allDBs)
.build();
Assert.assertTrue(_clusterVerifier.verify(5000));
}
@AfterClass
public void afterClass() throws Exception {
_controller.syncStop();
for (MockParticipantManager p : _participants) {
p.syncStop();
}
deleteCluster(CLUSTER_NAME);
}
@Test
public void testNodeSwap() throws Exception {
Map<String, ExternalView> record = new HashMap<>();
for (String db : _allDBs) {
record.put(db,
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db));
}
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
// Randomize the test by selecting random node
Random ran = new Random(System.currentTimeMillis());
// 1. disable an old node
MockParticipantManager oldParticipant = _participants.get(ran.nextInt(_participants.size()));
String oldParticipantName = oldParticipant.getInstanceName();
final InstanceConfig instanceConfig =
_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, oldParticipantName);
instanceConfig.setInstanceEnabled(false);
_gSetupTool.getClusterManagementTool()
.setInstanceConfig(CLUSTER_NAME, oldParticipantName, instanceConfig);
Assert.assertTrue(_clusterVerifier.verify(10000));
// 2. then entering maintenance mode and remove it from topology
_gSetupTool.getClusterManagementTool()
.manuallyEnableMaintenanceMode(CLUSTER_NAME, true, "NodeSwap", Collections.emptyMap());
oldParticipant.syncStop();
_participants.remove(oldParticipant);
Thread.sleep(2000);
_gSetupTool.getClusterManagementTool().dropInstance(CLUSTER_NAME, instanceConfig);
// 3. create new participant with same topology
String newParticipantName = "RandomParticipant_" + START_PORT;
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, newParticipantName);
InstanceConfig newConfig = configAccessor.getInstanceConfig(CLUSTER_NAME, newParticipantName);
String zone = instanceConfig.getDomainAsMap().get("zone");
String domain = String.format("zone=%s,instance=%s", zone, newParticipantName);
newConfig.setDomain(domain);
_gSetupTool.getClusterManagementTool()
.setInstanceConfig(CLUSTER_NAME, newParticipantName, newConfig);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, newParticipantName);
participant.syncStart();
_participants.add(0, participant);
// 4. exit maintenance mode and rebalance
_gSetupTool.getClusterManagementTool()
.manuallyEnableMaintenanceMode(CLUSTER_NAME, false, "NodeSwapDone", Collections.emptyMap());
Assert.assertTrue(_clusterVerifier.verify(5000));
// Since only one node temporary down, the same partitions will be moved to the newly added node.
for (String db : _allDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
ExternalView oldEv = record.get(db);
for (String partition : ev.getPartitionSet()) {
Map<String, String> stateMap = ev.getStateMap(partition);
Map<String, String> oldStateMap = oldEv.getStateMap(partition);
Assert.assertTrue(oldStateMap != null && stateMap != null);
Assert.assertEquals(stateMap.size(), _replica);
// Note the WAGED rebalanacer won't ensure the same state, because moving the top states
// back to the replaced node might be unnecessary and causing overhead.
Set<String> instanceSet = new HashSet<>(stateMap.keySet());
if (instanceSet.remove(newParticipantName)) {
instanceSet.add(oldParticipantName);
}
Assert.assertEquals(oldStateMap.keySet(), instanceSet);
}
}
}
@Test(dependsOnMethods = "testNodeSwap")
public void testFaultZoneSwap() throws Exception {
Map<String, ExternalView> record = new HashMap<>();
for (String db : _allDBs) {
record.put(db,
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db));
}
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
// Randomize the test by selecting random zone
Random ran = new Random(System.currentTimeMillis());
String randZoneStr = "zone-" + ran.nextInt(NUM_ZONE);
// 1. disable a whole fault zone
Map<String, InstanceConfig> removedInstanceConfigMap = new HashMap<>();
for (MockParticipantManager participant : _participants) {
String instanceName = participant.getInstanceName();
InstanceConfig instanceConfig =
_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, instanceName);
if (instanceConfig.getDomainAsMap().get("zone").equals(randZoneStr)) {
instanceConfig.setInstanceEnabled(false);
_gSetupTool.getClusterManagementTool()
.setInstanceConfig(CLUSTER_NAME, instanceName, instanceConfig);
removedInstanceConfigMap.put(instanceName, instanceConfig);
}
}
Assert.assertTrue(_clusterVerifier.verify(10000));
// 2. then entering maintenance mode and remove all the zone-0 nodes from topology
_gSetupTool.getClusterManagementTool()
.manuallyEnableMaintenanceMode(CLUSTER_NAME, true, "NodeSwap", Collections.emptyMap());
Iterator<MockParticipantManager> iter = _participants.iterator();
while(iter.hasNext()) {
MockParticipantManager participant = iter.next();
String instanceName = participant.getInstanceName();
if (removedInstanceConfigMap.containsKey(instanceName)) {
participant.syncStop();
iter.remove();
Thread.sleep(1000);
_gSetupTool.getClusterManagementTool()
.dropInstance(CLUSTER_NAME, removedInstanceConfigMap.get(instanceName));
}
}
// 3. create new participants with same topology
Set<String> newInstanceNames = new HashSet<>();
for (int i = 0; i < removedInstanceConfigMap.size(); i++) {
String newParticipantName = "NewParticipant_" + (START_PORT + i++);
newInstanceNames.add(newParticipantName);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, newParticipantName);
InstanceConfig newConfig = configAccessor.getInstanceConfig(CLUSTER_NAME, newParticipantName);
String domain = String.format("zone=" + randZoneStr + ",instance=%s", newParticipantName);
newConfig.setDomain(domain);
_gSetupTool.getClusterManagementTool()
.setInstanceConfig(CLUSTER_NAME, newParticipantName, newConfig);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, newParticipantName);
participant.syncStart();
_participants.add(participant);
}
// 4. exit maintenance mode and rebalance
_gSetupTool.getClusterManagementTool()
.manuallyEnableMaintenanceMode(CLUSTER_NAME, false, "NodeSwapDone", Collections.emptyMap());
Assert.assertTrue(_clusterVerifier.verify(5000));
for (String db : _allDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
ExternalView oldEv = record.get(db);
for (String partition : ev.getPartitionSet()) {
Map<String, String> stateMap = ev.getStateMap(partition);
Map<String, String> oldStateMap = oldEv.getStateMap(partition);
Assert.assertTrue(oldStateMap != null && stateMap != null);
Assert.assertEquals(stateMap.size(), _replica);
Set<String> instanceSet = new HashSet<>(stateMap.keySet());
instanceSet.removeAll(oldStateMap.keySet());
// All the different instances in the new mapping are the newly added instance
Assert.assertTrue(newInstanceNames.containsAll(instanceSet));
instanceSet = new HashSet<>(oldStateMap.keySet());
instanceSet.removeAll(stateMap.keySet());
// All the different instances in the old mapping are the removed instance
Assert.assertTrue(removedInstanceConfigMap.keySet().containsAll(instanceSet));
}
}
}
}
| 9,540 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/WagedRebalancer/TestWagedExpandCluster.java
|
package org.apache.helix.integration.rebalancer.WagedRebalancer;
/*
* 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.HashMap;
import java.util.Map;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.integration.rebalancer.PartitionMigration.TestPartitionMigrationBase;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestWagedExpandCluster extends TestPartitionMigrationBase {
Map<String, IdealState> _resourceMap;
@BeforeClass
public void beforeClass()
throws Exception {
super.beforeClass();
_resourceMap = createTestDBs(1000000);
// TODO remove this sleep after fix https://github.com/apache/helix/issues/526
Thread.sleep(1000);
_migrationVerifier = new MigrationStateVerifier(_resourceMap, _manager);
}
protected Map<String, IdealState> createTestDBs(long delayTime) {
Map<String, IdealState> idealStateMap = new HashMap<>();
int i = 0;
for (String stateModel : TestStateModels) {
String db = "Test-DB-" + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, _PARTITIONS, _replica,
_minActiveReplica);
_testDBs.add(db);
}
for (String db : _testDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
idealStateMap.put(db, is);
}
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setDelayRebalaceEnabled(true);
clusterConfig.setRebalanceDelayTime(delayTime);
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
return idealStateMap;
}
@Test
public void testClusterExpansion()
throws Exception {
Assert.assertTrue(_clusterVerifier.verifyByPolling());
_migrationVerifier.start();
// expand cluster by adding instance one by one
int numNodes = _participants.size();
for (int i = numNodes; i < numNodes + NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
MockParticipantManager participant = createAndStartParticipant(storageNodeName);
_participants.add(participant);
Thread.sleep(50);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
Assert.assertFalse(_migrationVerifier.hasLessReplica());
Assert.assertFalse(_migrationVerifier.hasMoreReplica());
_migrationVerifier.stop();
}
@Test(dependsOnMethods = {"testClusterExpansion"})
public void testClusterExpansionByEnableInstance()
throws Exception {
Assert.assertTrue(_clusterVerifier.verifyByPolling());
_migrationVerifier.reset();
_migrationVerifier.start();
int numNodes = _participants.size();
// add new instances with all disabled
for (int i = numNodes; i < numNodes + NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
InstanceConfig config = InstanceConfig.toInstanceConfig(storageNodeName);
config.setInstanceEnabled(false);
config.getRecord().getSimpleFields()
.remove(InstanceConfig.InstanceConfigProperty.HELIX_ENABLED_TIMESTAMP.name());
_gSetupTool.getClusterManagementTool().addInstance(CLUSTER_NAME, config);
// start dummy participants
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, storageNodeName);
participant.syncStart();
_participants.add(participant);
}
// enable new instance one by one
for (int i = numNodes; i < numNodes + NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, storageNodeName, true);
Thread.sleep(100);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
Assert.assertFalse(_migrationVerifier.hasLessReplica());
_migrationVerifier.stop();
}
@Test(dependsOnMethods = {"testClusterExpansion", "testClusterExpansionByEnableInstance"})
public void testClusterShrink()
throws Exception {
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setDelayRebalaceEnabled(false);
clusterConfig.setRebalanceDelayTime(0);
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
_migrationVerifier.reset();
_migrationVerifier.start();
// remove instance one by one
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
MockParticipantManager participant = _participants.get(i);
participant.syncStop();
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, storageNodeName, false);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
Assert.assertFalse(_migrationVerifier.hasLessMinActiveReplica());
Assert.assertFalse(_migrationVerifier.hasMoreReplica());
_migrationVerifier.stop();
}
}
| 9,541 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/WagedRebalancer/TestDelayedWagedRebalanceWithRackaware.java
|
package org.apache.helix.integration.rebalancer.WagedRebalancer;
/*
* 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.HashMap;
import java.util.Map;
import org.apache.helix.TestHelper;
import org.apache.helix.integration.rebalancer.DelayedAutoRebalancer.TestDelayedAutoRebalanceWithRackaware;
import org.apache.helix.model.ExternalView;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Inherit TestDelayedAutoRebalanceWithRackaware to ensure the test logic is the same.
*/
public class TestDelayedWagedRebalanceWithRackaware extends TestDelayedAutoRebalanceWithRackaware {
// create test DBs, wait it converged and return externalviews
protected Map<String, ExternalView> createTestDBs(long delayTime)
throws InterruptedException {
Map<String, ExternalView> externalViews = new HashMap<>();
int i = 0;
for (String stateModel : TestStateModels) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_minActiveReplica);
_testDBs.add(db);
}
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
externalViews.put(db, ev);
}
return externalViews;
}
@Test
public void testDelayedPartitionMovement() {
// Waged Rebalancer takes cluster level delay config only. Skip this test.
}
@Test
public void testDisableDelayRebalanceInResource() {
// Waged Rebalancer takes cluster level delay config only. Skip this test.
}
@Test(dependsOnMethods = {"testDelayedPartitionMovement"})
public void testDelayedPartitionMovementWithClusterConfigedDelay()
throws Exception {
super.testDelayedPartitionMovementWithClusterConfigedDelay();
}
@Test(dependsOnMethods = {"testDelayedPartitionMovementWithClusterConfigedDelay"})
public void testMinimalActiveReplicaMaintain()
throws Exception {
super.testMinimalActiveReplicaMaintain();
}
@Test(dependsOnMethods = {"testMinimalActiveReplicaMaintain"})
public void testPartitionMovementAfterDelayTime()
throws Exception {
super.testPartitionMovementAfterDelayTime();
}
@Test(dependsOnMethods = {"testDisableDelayRebalanceInResource"})
public void testDisableDelayRebalanceInCluster()
throws Exception {
super.testDisableDelayRebalanceInCluster();
}
@Test(dependsOnMethods = {"testDisableDelayRebalanceInCluster"})
public void testDisableDelayRebalanceInInstance()
throws Exception {
super.testDisableDelayRebalanceInInstance();
}
}
| 9,542 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/WagedRebalancer/TestDelayedWagedRebalance.java
|
package org.apache.helix.integration.rebalancer.WagedRebalancer;
/*
* 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.HashMap;
import java.util.Map;
import org.apache.helix.TestHelper;
import org.apache.helix.integration.rebalancer.DelayedAutoRebalancer.TestDelayedAutoRebalance;
import org.apache.helix.model.ExternalView;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Inherit TestDelayedAutoRebalance to ensure the test logic is the same.
*/
public class TestDelayedWagedRebalance extends TestDelayedAutoRebalance {
// create test DBs, wait it converged and return externalviews
protected Map<String, ExternalView> createTestDBs(long delayTime) throws InterruptedException {
Map<String, ExternalView> externalViews = new HashMap<>();
int i = 0;
for (String stateModel : TestStateModels) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_minActiveReplica);
_testDBs.add(db);
}
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
externalViews.put(db, ev);
}
return externalViews;
}
@Test
public void testDelayedPartitionMovement() {
// Waged Rebalancer takes cluster level delay config only. Skip this test.
}
@Test
public void testDisableDelayRebalanceInResource() {
// Waged Rebalancer takes cluster level delay config only. Skip this test.
}
@Test(dependsOnMethods = { "testDelayedPartitionMovement" })
public void testDelayedPartitionMovementWithClusterConfigedDelay() throws Exception {
super.testDelayedPartitionMovementWithClusterConfigedDelay();
}
@Test(dependsOnMethods = { "testDelayedPartitionMovementWithClusterConfigedDelay" })
public void testMinimalActiveReplicaMaintain() throws Exception {
super.testMinimalActiveReplicaMaintain();
}
@Test(dependsOnMethods = { "testMinimalActiveReplicaMaintain" })
public void testPartitionMovementAfterDelayTime() throws Exception {
super.testPartitionMovementAfterDelayTime();
}
@Test(dependsOnMethods = { "testDisableDelayRebalanceInResource" })
public void testDisableDelayRebalanceInCluster() throws Exception {
super.testDisableDelayRebalanceInCluster();
}
@Test(dependsOnMethods = { "testDisableDelayRebalanceInCluster" })
public void testDisableDelayRebalanceInInstance() throws Exception {
super.testDisableDelayRebalanceInInstance();
}
@Test(dependsOnMethods = {"testDisableDelayRebalanceInInstance"})
public void testOnDemandRebalance() throws Exception {
super.testOnDemandRebalance();
}
@Test(dependsOnMethods = {"testOnDemandRebalance"})
public void testExpiredOnDemandRebalanceTimestamp() throws Exception {
super.testExpiredOnDemandRebalanceTimestamp();
}
@Test(dependsOnMethods = {"testExpiredOnDemandRebalanceTimestamp"})
public void testOnDemandRebalanceAfterDelayRebalanceHappen() throws Exception {
super.testOnDemandRebalanceAfterDelayRebalanceHappen();
}
}
| 9,543 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/WagedRebalancer/TestMixedModeWagedRebalance.java
|
package org.apache.helix.integration.rebalancer.WagedRebalancer;
/*
* 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 org.apache.helix.integration.rebalancer.TestMixedModeAutoRebalance;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
public class TestMixedModeWagedRebalance extends TestMixedModeAutoRebalance {
private final String CLASS_NAME = getShortClassName();
private final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
@DataProvider(name = "stateModels")
public static Object[][] stateModels() {
return new Object[][] { { BuiltInStateModelDefinitions.MasterSlave.name(), true, null },
{ BuiltInStateModelDefinitions.OnlineOffline.name(), true, null },
{ BuiltInStateModelDefinitions.LeaderStandby.name(), true, null },
{ BuiltInStateModelDefinitions.MasterSlave.name(), false, null },
{ BuiltInStateModelDefinitions.OnlineOffline.name(), false, null },
{ BuiltInStateModelDefinitions.LeaderStandby.name(), false, null }
};
}
protected void createResource(String dbName, String stateModel, int numPartition, int replica,
boolean delayEnabled, String rebalanceStrategy) {
if (delayEnabled) {
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, 200);
createResourceWithWagedRebalance(CLUSTER_NAME, dbName, stateModel, numPartition, replica,
replica - 1);
} else {
createResourceWithWagedRebalance(CLUSTER_NAME, dbName, stateModel, numPartition, replica,
replica);
}
}
@AfterMethod
public void afterMethod() {
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, -1);
}
}
| 9,544 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/WagedRebalancer/TestWagedClusterExpansion.java
|
package org.apache.helix.integration.rebalancer.WagedRebalancer;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional warnrmation
* 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.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableMap;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.NotificationContext;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.rebalancer.waged.AssignmentMetadataStore;
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.ZkBucketDataAccessor;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.Message;
import org.apache.helix.model.ResourceAssignment;
import org.apache.helix.model.ResourceConfig;
import org.apache.helix.participant.StateMachineEngine;
import org.apache.helix.participant.statemachine.StateModel;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.apache.helix.participant.statemachine.StateModelInfo;
import org.apache.helix.participant.statemachine.Transition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* This test case is specially targeting for n - n+1 issue.
* Waged is constraint-based algorithm. The end-state of calculated ideal-state will
* always satisfy hard-constraint.
* The issue is in order to reach the ideal-state, we need to do intermediate
* state-transitions.
* During this phase, hard-constraints are not satisfied.
* This test case is trying to mimic this by having a very tightly constraint
* cluster and increasing the weight for some resource and checking if
* intermediate state satisfies the need or not.
*/
public class TestWagedClusterExpansion extends ZkTestBase {
protected final int NUM_NODE = 6;
protected static final int START_PORT = 13000;
protected static final int PARTITIONS = 10;
protected static final String CLASS_NAME = TestWagedClusterExpansion.class.getSimpleName();
protected static final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected ClusterControllerManager _controller;
protected AssignmentMetadataStore _assignmentMetadataStore;
List<MockParticipantManager> _participants = new ArrayList<>();
List<String> _nodes = new ArrayList<>();
private final Set<String> _allDBs = new HashSet<>();
private final int _replica = 3;
private final int INSTANCE_CAPACITY = 100;
private final int DEFAULT_PARTITION_CAPACITY = 6;
private final int INCREASED_PARTITION_CAPACITY = 10;
private final int REDUCED_INSTANCE_CAPACITY = 98;
private final int DEFAULT_DELAY = 500; // 0.5 second
private final String _testCapacityKey = "TestCapacityKey";
private final String _resourceChanged = "Test-WagedDB-0";
private final Map<String, IdealState> _prevIdealState = new HashMap<>();
private static final Logger LOG = LoggerFactory.getLogger(CLASS_NAME);
// mock delay master-slave state model
@StateModelInfo(initialState = "OFFLINE", states = {
"MASTER", "SLAVE", "ERROR"
})
public static class WagedMasterSlaveModel extends StateModel {
private static final Logger LOG = LoggerFactory.getLogger(WagedMasterSlaveModel.class);
private final long _delay;
public WagedMasterSlaveModel(long delay) {
_delay = delay;
}
@Transition(to = "SLAVE", from = "OFFLINE")
public void onBecomeSlaveFromOffline(Message message, NotificationContext context) {
if (_delay > 0) {
try {
Thread.currentThread().sleep(_delay);
} catch (InterruptedException e) {
// ignore
}
}
LOG.info("Become SLAVE from OFFLINE");
}
@Transition(to = "MASTER", from = "SLAVE")
public void onBecomeMasterFromSlave(Message message, NotificationContext context)
throws InterruptedException {
LOG.info("Become MASTER from SLAVE");
}
@Transition(to = "SLAVE", from = "MASTER")
public void onBecomeSlaveFromMaster(Message message, NotificationContext context) {
LOG.info("Become Slave from Master");
}
@Transition(to = "OFFLINE", from = "SLAVE")
public void onBecomeOfflineFromSlave(Message message, NotificationContext context) {
if (_delay > 0) {
try {
Thread.currentThread().sleep(_delay);
} catch (InterruptedException e) {
// ignore
}
}
LOG.info("Become OFFLINE from SLAVE");
}
@Transition(to = "DROPPED", from = "OFFLINE")
public void onBecomeDroppedFromOffline(Message message, NotificationContext context) {
if (_delay > 0) {
try {
Thread.currentThread().sleep(_delay);
} catch (InterruptedException e) {
// ignore
}
}
LOG.info("Become DROPPED FROM OFFLINE");
}
}
public static class WagedDelayMSStateModelFactory extends StateModelFactory<WagedMasterSlaveModel> {
private long _delay;
@Override
public WagedMasterSlaveModel createNewStateModel(String resourceName,
String partitionKey) {
WagedMasterSlaveModel model = new WagedMasterSlaveModel(_delay);
return model;
}
public WagedDelayMSStateModelFactory setDelay(long delay) {
_delay = delay;
return this;
}
}
@BeforeClass
public void beforeClass() throws Exception {
LOG.info("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
// create 6 node cluster
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
_nodes.add(storageNodeName);
}
// ST downward message will get delayed by 5sec.
startParticipants(DEFAULT_DELAY);
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
_assignmentMetadataStore =
new AssignmentMetadataStore(new ZkBucketDataAccessor(ZK_ADDR), CLUSTER_NAME) {
public Map<String, ResourceAssignment> getBaseline() {
// Ensure this metadata store always read from the ZK without using cache.
super.reset();
return super.getBaseline();
}
public synchronized Map<String, ResourceAssignment> getBestPossibleAssignment() {
// Ensure this metadata store always read from the ZK without using cache.
super.reset();
return super.getBestPossibleAssignment();
}
};
// Set test instance capacity and partition weights
HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
ClusterConfig clusterConfig =
dataAccessor.getProperty(dataAccessor.keyBuilder().clusterConfig());
clusterConfig.setInstanceCapacityKeys(Collections.singletonList(_testCapacityKey));
clusterConfig.setDefaultInstanceCapacityMap(Collections.singletonMap(_testCapacityKey, INSTANCE_CAPACITY));
clusterConfig.setDefaultPartitionWeightMap(Collections.singletonMap(_testCapacityKey, DEFAULT_PARTITION_CAPACITY));
dataAccessor.setProperty(dataAccessor.keyBuilder().clusterConfig(), clusterConfig);
// Create 3 resources with 10 partitions each.
for (int i = 0; i < 3; i++) {
String db = "Test-WagedDB-" + i;
createResourceWithWagedRebalance(CLUSTER_NAME, db, BuiltInStateModelDefinitions.MasterSlave.name(),
PARTITIONS, _replica, _replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
}
private void startParticipants(int delay) {
// start dummy participants
for (String node : _nodes) {
MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
StateMachineEngine stateMach = participant.getStateMachineEngine();
TestWagedClusterExpansion.WagedDelayMSStateModelFactory delayFactory =
new TestWagedClusterExpansion.WagedDelayMSStateModelFactory().setDelay(delay);
stateMach.registerStateModelFactory("MasterSlave", delayFactory);
participant.syncStart();
_participants.add(participant);
}
}
// This test case, first adds a new instance which will cause STs.
// Next, it will try to increase the default weight for one resource.
@Test
public void testIncreaseResourcePartitionWeight() throws Exception {
// For this test, let us record our initial prevIdealState.
for (String db : _allDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
_prevIdealState.put(db, is);
}
// Let us add one more instance
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + NUM_NODE);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
_nodes.add(storageNodeName);
// Start the participant.
MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, storageNodeName);
StateMachineEngine stateMach = participant.getStateMachineEngine();
TestWagedClusterExpansion.WagedDelayMSStateModelFactory delayFactory =
new TestWagedClusterExpansion.WagedDelayMSStateModelFactory().setDelay(DEFAULT_DELAY);
stateMach.registerStateModelFactory("MasterSlave", delayFactory);
participant.syncStart();
_participants.add(participant);
// Check modified time for external view of the first resource.
// if pipeline is run, then external view would be persisted.
waitForPipeline(100, 3000);
LOG.info("After adding the new instance");
validateIdealState(false /* afterWeightChange */);
// Update the weight for one of the resource.
HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
String db = _resourceChanged;
ResourceConfig resourceConfig = dataAccessor.getProperty(dataAccessor.keyBuilder().resourceConfig(db));
if (resourceConfig == null) {
resourceConfig = new ResourceConfig(db);
}
Map<String, Integer> capacityDataMap = ImmutableMap.of(_testCapacityKey, INCREASED_PARTITION_CAPACITY);
resourceConfig.setPartitionCapacityMap(
Collections.singletonMap(ResourceConfig.DEFAULT_PARTITION_KEY, capacityDataMap));
dataAccessor.setProperty(dataAccessor.keyBuilder().resourceConfig(db), resourceConfig);
// Make sure pipeline is run.
waitForPipeline(100, 10000); // 10 sec. max timeout.
LOG.info("After changing resource partition weight");
validateIdealState(true /* afterWeightChange */);
waitForPipeline(100, 3000); // this is for ZK to sync up.
}
// This test case reduces the capacity of one of the instance.
@Test (dependsOnMethods = "testIncreaseResourcePartitionWeight")
public void testReduceInstanceCapacity() throws Exception {
// Reduce capacity for one of the instance
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + NUM_NODE);
HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
String db = _resourceChanged;
InstanceConfig config = dataAccessor.getProperty(dataAccessor.keyBuilder().instanceConfig(storageNodeName));
if (config == null) {
config = new InstanceConfig(storageNodeName);
}
Map<String, Integer> capacityDataMap = ImmutableMap.of(_testCapacityKey, REDUCED_INSTANCE_CAPACITY);
config.setInstanceCapacityMap(capacityDataMap);
dataAccessor.setProperty(dataAccessor.keyBuilder().instanceConfig(storageNodeName), config);
// Make sure pipeline is run.
waitForPipeline(100, 10000); // 10 sec. max timeout.
LOG.info("After changing instance capacity");
validateIdealState(true);
waitForPipeline(100, 3000); // this is for ZK to sync up.
}
@AfterClass
public void afterClass() throws Exception {
try {
if (_controller != null && _controller.isConnected()) {
_controller.syncStop();
}
for (MockParticipantManager p : _participants) {
if (p != null && p.isConnected()) {
p.syncStop();
}
}
deleteCluster(CLUSTER_NAME);
} catch (Exception e) {
LOG.info("After class throwing exception, {}", e);
}
}
private void waitForPipeline(long stepSleep, long maxTimeout) {
// Check modified time for external view of the first resource.
// if pipeline is run, then external view would be persisted.
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime < maxTimeout) {
String db = _allDBs.iterator().next();
long modifiedTime = _gSetupTool.getClusterManagementTool().
getResourceExternalView(CLUSTER_NAME, db).getRecord().getModifiedTime();
if (modifiedTime - startTime > maxTimeout) {
break;
}
try {
Thread.currentThread().sleep(stepSleep);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
private void validateIdealState(boolean afterWeightChange) {
// Calculate the instance to partition mapping based on previous and new ideal state.
Map<String, Set<String>> instanceToPartitionMap = new HashMap<>();
for (String db : _allDBs) {
IdealState newIdealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
for (String partition : newIdealState.getPartitionSet()) {
Map<String, String> assignmentMap = newIdealState.getRecord().getMapField(partition);
List<String> preferenceList = newIdealState.getRecord().getListField(partition);
for (String instance : assignmentMap.keySet()) {
if (!preferenceList.contains(instance)) {
LOG.error("Instance: " + instance + " is not in preference list for partition: " + partition);
}
if (!instanceToPartitionMap.containsKey(instance)) {
instanceToPartitionMap.put(instance, new HashSet<>());
}
instanceToPartitionMap.get(instance).add(partition);
}
}
}
// Now, let us validate the instance to partition mapping.
for (String instance : instanceToPartitionMap.keySet()) {
int usedInstanceCapacity = 0;
for (String partition : instanceToPartitionMap.get(instance)) {
LOG.info("\tPartition: " + partition);
if (afterWeightChange && partition.startsWith(_resourceChanged)) {
usedInstanceCapacity += INCREASED_PARTITION_CAPACITY;
} else {
usedInstanceCapacity += DEFAULT_PARTITION_CAPACITY;
}
}
LOG.error("\tInstance: " + instance + " used capacity: " + usedInstanceCapacity);
// For now, this has to be disabled as this test case is negative scenario.
if (usedInstanceCapacity > INSTANCE_CAPACITY) {
LOG.error(instanceToPartitionMap.get(instance).toString());
}
Assert.assertTrue(usedInstanceCapacity <= INSTANCE_CAPACITY);
}
}
}
| 9,545 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/WagedRebalancer/TestWagedRebalanceFaultZone.java
|
package org.apache.helix.integration.rebalancer.WagedRebalancer;
/*
* 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.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.helix.ConfigAccessor;
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.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestWagedRebalanceFaultZone extends ZkTestBase {
protected final int NUM_NODE = 6;
protected static final int START_PORT = 12918;
protected static final int PARTITIONS = 20;
protected static final int ZONES = 3;
protected static final int TAGS = 2;
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected ClusterControllerManager _controller;
List<MockParticipantManager> _participants = new ArrayList<>();
Map<String, String> _nodeToZoneMap = new HashMap<>();
Map<String, String> _nodeToTagMap = new HashMap<>();
List<String> _nodes = new ArrayList<>();
Set<String> _allDBs = new HashSet<>();
int _replica = 3;
String[] _testModels = {
BuiltInStateModelDefinitions.OnlineOffline.name(),
BuiltInStateModelDefinitions.MasterSlave.name(),
BuiltInStateModelDefinitions.LeaderStandby.name()
};
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
addInstanceConfig(storageNodeName, i, ZONES, TAGS);
}
// start dummy participants
for (String node : _nodes) {
MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
enableTopologyAwareRebalance(_gZkClient, CLUSTER_NAME, true);
}
protected void addInstanceConfig(String storageNodeName, int seqNo, int zoneCount, int tagCount) {
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
String zone = "zone-" + seqNo % zoneCount;
String tag = "tag-" + seqNo % tagCount;
_gSetupTool.getClusterManagementTool().setInstanceZoneId(CLUSTER_NAME, storageNodeName, zone);
_gSetupTool.getClusterManagementTool().addInstanceTag(CLUSTER_NAME, storageNodeName, tag);
_nodeToZoneMap.put(storageNodeName, zone);
_nodeToTagMap.put(storageNodeName, tag);
_nodes.add(storageNodeName);
}
@Test
public void testZoneIsolation() throws Exception {
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-testZoneIsolation" + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
Thread.sleep(300);
validate(_replica);
}
@Test
public void testZoneIsolationWithInstanceTag() throws Exception {
Set<String> tags = new HashSet<String>(_nodeToTagMap.values());
int i = 0;
for (String tag : tags) {
String db = "Test-DB-testZoneIsolationWithInstanceTag" + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db,
BuiltInStateModelDefinitions.MasterSlave.name(), PARTITIONS, _replica, _replica);
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
is.setInstanceGroupTag(tag);
_gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, db, is);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
Thread.sleep(300);
validate(_replica);
}
@Test(dependsOnMethods = { "testZoneIsolation", "testZoneIsolationWithInstanceTag" })
public void testLackEnoughLiveRacks() throws Exception {
// shutdown participants within one zone
String zone = _nodeToZoneMap.values().iterator().next();
for (int i = 0; i < _participants.size(); i++) {
MockParticipantManager p = _participants.get(i);
if (_nodeToZoneMap.get(p.getInstanceName()).equals(zone)) {
p.syncStop();
}
}
int j = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-testLackEnoughLiveRacks" + j++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
Thread.sleep(300);
validate(2);
// restart the participants within the zone
for (int i = 0; i < _participants.size(); i++) {
MockParticipantManager p = _participants.get(i);
if (_nodeToZoneMap.get(p.getInstanceName()).equals(zone)) {
MockParticipantManager newNode =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, p.getInstanceName());
_participants.set(i, newNode);
newNode.syncStart();
}
}
Thread.sleep(300);
// Verify if the partitions get assigned
validate(_replica);
}
@Test(dependsOnMethods = { "testLackEnoughLiveRacks" })
public void testLackEnoughRacks() throws Exception {
// shutdown participants within one zone
String zone = _nodeToZoneMap.values().iterator().next();
for (int i = 0; i < _participants.size(); i++) {
MockParticipantManager p = _participants.get(i);
if (_nodeToZoneMap.get(p.getInstanceName()).equals(zone)) {
p.syncStop();
_gSetupTool.getClusterManagementTool()
.enableInstance(CLUSTER_NAME, p.getInstanceName(), false);
Thread.sleep(50);
_gSetupTool.dropInstanceFromCluster(CLUSTER_NAME, p.getInstanceName());
}
}
int j = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-testLackEnoughRacks" + j++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
Thread.sleep(300);
validate(2);
// Create new participants within the zone
int nodeCount = _participants.size();
for (int i = 0; i < nodeCount; i++) {
MockParticipantManager p = _participants.get(i);
if (_nodeToZoneMap.get(p.getInstanceName()).equals(zone)) {
String replaceNodeName = p.getInstanceName() + "-replacement_" + START_PORT;
addInstanceConfig(replaceNodeName, i, ZONES, TAGS);
MockParticipantManager newNode =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, replaceNodeName);
_participants.set(i, newNode);
newNode.syncStart();
}
}
Thread.sleep(300);
// Verify if the partitions get assigned
validate(_replica);
}
@Test(dependsOnMethods = { "testZoneIsolation", "testZoneIsolationWithInstanceTag" })
public void testAddZone() throws Exception {
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-testAddZone" + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_replica);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
Thread.sleep(300);
validate(_replica);
// Create new participants within the a new zone
Set<MockParticipantManager> newNodes = new HashSet<>();
Map<String, Integer> newNodeReplicaCount = new HashMap<>();
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
try {
// Configure the preference so as to allow movements.
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
Map<ClusterConfig.GlobalRebalancePreferenceKey, Integer> preference = new HashMap<>();
preference.put(ClusterConfig.GlobalRebalancePreferenceKey.EVENNESS, 10);
preference.put(ClusterConfig.GlobalRebalancePreferenceKey.LESS_MOVEMENT, 0);
clusterConfig.setGlobalRebalancePreference(preference);
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
int nodeCount = 2;
for (int j = 0; j < nodeCount; j++) {
String newNodeName = "new-zone-node-" + j + "_" + START_PORT;
// Add all new node to the new zone
addInstanceConfig(newNodeName, j, ZONES + 1, TAGS);
MockParticipantManager newNode =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, newNodeName);
newNode.syncStart();
newNodes.add(newNode);
newNodeReplicaCount.put(newNodeName, 0);
}
Thread.sleep(300);
validate(_replica);
// The new zone nodes shall have some assignments
for (String db : _allDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
validateZoneAndTagIsolation(is, ev, _replica);
for (String partition : ev.getPartitionSet()) {
Map<String, String> stateMap = ev.getStateMap(partition);
for (String node : stateMap.keySet()) {
if (newNodeReplicaCount.containsKey(node)) {
newNodeReplicaCount.computeIfPresent(node, (nodeName, replicaCount) -> replicaCount + 1);
}
}
}
}
Assert.assertTrue(newNodeReplicaCount.values().stream().allMatch(count -> count > 0));
} finally {
// Revert the preference
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
Map<ClusterConfig.GlobalRebalancePreferenceKey, Integer> preference = new HashMap<>();
preference.put(ClusterConfig.GlobalRebalancePreferenceKey.EVENNESS, 1);
preference.put(ClusterConfig.GlobalRebalancePreferenceKey.LESS_MOVEMENT, 1);
clusterConfig.setGlobalRebalancePreference(preference);
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
// Stop the new nodes
for (MockParticipantManager p : newNodes) {
if (p != null && p.isConnected()) {
p.syncStop();
}
}
}
}
private void validate(int expectedReplica) {
ZkHelixClusterVerifier _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _allDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
validateZoneAndTagIsolation(is, ev, expectedReplica);
}
}
/**
* Validate instances for each partition is on different zone and with necessary tagged instances.
*/
private void validateZoneAndTagIsolation(IdealState is, ExternalView ev, int expectedReplica) {
String tag = is.getInstanceGroupTag();
for (String partition : is.getPartitionSet()) {
Set<String> assignedZones = new HashSet<String>();
Map<String, String> assignmentMap = ev.getRecord().getMapField(partition);
Set<String> instancesInEV = assignmentMap.keySet();
// TODO: preference List is not persisted in IS.
// Assert.assertEquals(instancesInEV, instancesInIs);
for (String instance : instancesInEV) {
assignedZones.add(_nodeToZoneMap.get(instance));
if (tag != null) {
InstanceConfig config =
_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, instance);
Assert.assertTrue(config.containsTag(tag));
}
}
Assert.assertEquals(assignedZones.size(), expectedReplica);
}
}
@AfterMethod
public void afterMethod() throws Exception {
for (String db : _allDBs) {
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, db);
}
_allDBs.clear();
// waiting for all DB be dropped.
ZkHelixClusterVerifier _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
}
@AfterClass
public void afterClass() throws Exception {
/*
* shutdown order: 1) disconnect the controller 2) disconnect participants
*/
if (_controller != null && _controller.isConnected()) {
_controller.syncStop();
}
for (MockParticipantManager p : _participants) {
if (p != null && p.isConnected()) {
p.syncStop();
}
}
deleteCluster(CLUSTER_NAME);
System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,546 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/DelayedAutoRebalancer/TestDelayedAutoRebalance.java
|
package org.apache.helix.integration.rebalancer.DelayedAutoRebalancer;
/*
* 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.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.rebalancer.strategy.CrushRebalanceStrategy;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestDelayedAutoRebalance extends ZkTestBase {
static final int NUM_NODE = 5;
protected static final int START_PORT = 12918;
protected static final int PARTITIONS = 5;
// TODO: remove this wait time once we have a better way to determine if the rebalance has been
// TODO: done as a reaction of the test operations.
protected static final int DEFAULT_REBALANCE_PROCESSING_WAIT_TIME = TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME;
protected static final String OFFLINE_NODE = "offline";
protected static final String DISABLED_NODE = "disabled";
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected ClusterControllerManager _controller;
protected List<MockParticipantManager> _participants = new ArrayList<>();
protected int _replica = 3;
protected int _minActiveReplica = _replica - 1;
protected ZkHelixClusterVerifier _clusterVerifier;
protected List<String> _testDBs = new ArrayList<>();
protected String _testingCondition = OFFLINE_NODE;
protected ConfigAccessor _configAccessor;
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
// start dummy participants
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, storageNodeName);
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
_clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
_testingCondition = OFFLINE_NODE;
}
protected String[] TestStateModels = {
BuiltInStateModelDefinitions.MasterSlave.name(),
BuiltInStateModelDefinitions.OnlineOffline.name(),
BuiltInStateModelDefinitions.LeaderStandby.name()
};
/**
* The partition movement should be delayed (not happen immediately) after one single node goes offline.
* Delay is enabled by default, delay time is set in IdealState.
* @throws Exception
*/
@Test
public void testDelayedPartitionMovement() throws Exception {
Map<String, ExternalView> externalViewsBefore = createTestDBs(1000000);
validateDelayedMovements(externalViewsBefore);
}
@Test(dependsOnMethods = {"testDelayedPartitionMovement"})
public void testDelayedPartitionMovementWithClusterConfigedDelay() throws Exception {
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, 1000000);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
validateDelayedMovements(externalViewsBefore);
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, -1);
}
/**
* Test when two nodes go offline, the minimal active replica should be maintained.
* @throws Exception
*/
@Test(dependsOnMethods = {"testDelayedPartitionMovement"})
public void testMinimalActiveReplicaMaintain() throws Exception {
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, 1000000);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
validateDelayedMovements(externalViewsBefore);
// bring down another node, the minimal active replica for each partition should be maintained.
_participants.get(3).syncStop();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
}
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, -1);
}
/**
* The partition should be moved to other nodes after the delay time
*/
@Test (dependsOnMethods = {"testMinimalActiveReplicaMaintain"})
public void testPartitionMovementAfterDelayTime() throws Exception {
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
long delay = 4000;
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, delay);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
validateDelayedMovements(externalViewsBefore);
Thread.sleep(delay);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// after delay time, it should maintain required number of replicas.
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _replica, NUM_NODE);
}
}
@Test (dependsOnMethods = {"testMinimalActiveReplicaMaintain"})
public void testDisableDelayRebalanceInResource() throws Exception {
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, 1000000);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
validateDelayedMovements(externalViewsBefore);
// disable delay rebalance for one db, partition should be moved immediately
String testDb = _testDBs.get(0);
IdealState idealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(
CLUSTER_NAME, testDb);
idealState.setDelayRebalanceEnabled(false);
_gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, testDb, idealState);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// once delay rebalance is disabled, it should maintain required number of replicas for that db.
// replica for other dbs should not be moved.
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
if (db.equals(testDb)) {
validateMinActiveAndTopStateReplica(idealState, ev, _replica, NUM_NODE);
} else {
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
validateNoPartitionMove(is, externalViewsBefore.get(db), ev,
_participants.get(0).getInstanceName(), false);
}
}
}
@Test (dependsOnMethods = {"testDisableDelayRebalanceInResource"})
public void testDisableDelayRebalanceInCluster() throws Exception {
enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, true);
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, 1000000);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
validateDelayedMovements(externalViewsBefore);
// disable delay rebalance for the entire cluster.
enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, false);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _replica, NUM_NODE);
}
enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, true);
}
@Test (dependsOnMethods = {"testDisableDelayRebalanceInCluster"})
public void testDisableDelayRebalanceInInstance() throws Exception {
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, 1000000);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
validateDelayedMovements(externalViewsBefore);
String disabledInstanceName = _participants.get(0).getInstanceName();
enableDelayRebalanceInInstance(_gZkClient, CLUSTER_NAME, disabledInstanceName, false);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
Map<String, List<String>> preferenceLists = is.getPreferenceLists();
for (List<String> instances : preferenceLists.values()) {
Assert.assertFalse(instances.contains(disabledInstanceName));
}
}
enableDelayRebalanceInInstance(_gZkClient, CLUSTER_NAME, disabledInstanceName, true);
}
@Test(dependsOnMethods = {"testDisableDelayRebalanceInInstance"})
public void testOnDemandRebalance() throws Exception {
enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, true);
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, 1000000);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
boolean isDisabled = _testingCondition.equals(DISABLED_NODE);
if (isDisabled) {
// disable one node and make sure no partition movement
validateDelayedMovementsOnDisabledNode(externalViewsBefore);
} else {
// stop one node and make sure no partition movement
validateDelayedMovements(externalViewsBefore);
}
// trigger an on-demand rebalance and partitions on the offline/disabled node should move
validateMovementAfterOnDemandRebalance(externalViewsBefore, null,true, isDisabled);
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, -1);
setLastOnDemandRebalanceTimeInCluster(_gZkClient, CLUSTER_NAME, -1);
}
@Test(dependsOnMethods = {"testOnDemandRebalance"})
public void testExpiredOnDemandRebalanceTimestamp() throws Exception {
enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, true);
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, 1000000);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
boolean isDisabled = _testingCondition.equals(DISABLED_NODE);
if (isDisabled) {
// disable one node and make sure no partition movement
validateDelayedMovementsOnDisabledNode(externalViewsBefore);
} else {
// stop one node and make sure no partition movement
validateDelayedMovements(externalViewsBefore);
}
// trigger an on-demand rebalance and partitions on the offline/disabled node shouldn't move
// because the last on-demand timestamp is expired.
validateMovementAfterOnDemandRebalance(externalViewsBefore, 1L, false, isDisabled);
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, -1);
setLastOnDemandRebalanceTimeInCluster(_gZkClient, CLUSTER_NAME, -1);
}
@Test(dependsOnMethods = {"testExpiredOnDemandRebalanceTimestamp"})
public void testOnDemandRebalanceAfterDelayRebalanceHappen() throws Exception {
long delay = 4000;
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, delay);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
boolean isDisabled = _testingCondition.equals(DISABLED_NODE);
if (isDisabled) {
// disable one node and make sure no partition movement
validateDelayedMovementsOnDisabledNode(externalViewsBefore);
} else {
// stop one node and make sure no partition movement
validateDelayedMovements(externalViewsBefore);
}
Thread.sleep(delay);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// after delay time, it should maintain required number of replicas
externalViewsBefore = validatePartitionMovement(externalViewsBefore, true, isDisabled);
// trigger an on-demand rebalance and partitions on the offline/disabled node shouldn't move
// because the last on-demand timestamp is expired.
validateMovementAfterOnDemandRebalance(externalViewsBefore, null,false, isDisabled);
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, -1);
setLastOnDemandRebalanceTimeInCluster(_gZkClient, CLUSTER_NAME, -1);
}
@AfterMethod
public void afterTest() throws InterruptedException {
// delete all DBs create in last test
for (String db : _testDBs) {
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, db);
}
_testDBs.clear();
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
}
@BeforeMethod
public void beforeTest() {
// restart any participant that has been disconnected from last test.
for (int i = 0; i < _participants.size(); i++) {
if (!_participants.get(i).isConnected()) {
_participants.set(i, new MockParticipantManager(ZK_ADDR, CLUSTER_NAME,
_participants.get(i).getInstanceName()));
_participants.get(i).syncStart();
}
}
}
// create test DBs, wait it converged and return externalviews
protected Map<String, ExternalView> createTestDBs(long delayTime) throws InterruptedException {
Map<String, ExternalView> externalViews = new HashMap<String, ExternalView>();
int i = 0;
for (String stateModel : TestStateModels) {
String db = "Test-DB-" + i++;
createResourceWithDelayedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_minActiveReplica, delayTime, CrushRebalanceStrategy.class.getName());
_testDBs.add(db);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
externalViews.put(db, ev);
}
return externalViews;
}
protected void validateNoPartitionMove(IdealState is, ExternalView evBefore, ExternalView evAfter,
String offlineInstance, boolean disabled) {
for (String partition : is.getPartitionSet()) {
Map<String, String> assignmentsBefore = evBefore.getRecord().getMapField(partition);
Map<String, String> assignmentsAfter = evAfter.getRecord().getMapField(partition);
Set<String> instancesBefore = new HashSet<String>(assignmentsBefore.keySet());
Set<String> instancesAfter = new HashSet<String>(assignmentsAfter.keySet());
if (disabled) {
// the offline node is disabled
Assert.assertEquals(instancesBefore, instancesAfter, String.format(
"%s has been moved to new instances, before: %s, after: %s, disabled instance: %s",
partition, assignmentsBefore.toString(), assignmentsAfter.toString(), offlineInstance));
if (instancesAfter.contains(offlineInstance)) {
Assert.assertEquals(assignmentsAfter.get(offlineInstance), "OFFLINE");
}
} else {
// the offline node actually went offline.
instancesBefore.remove(offlineInstance);
Assert.assertEquals(instancesBefore, instancesAfter, String.format(
"%s has been moved to new instances, before: %s, after: %s, offline instance: %s",
partition, assignmentsBefore.toString(), assignmentsAfter.toString(), offlineInstance));
}
}
}
protected void validateMovementAfterOnDemandRebalance(
Map<String, ExternalView> externalViewsBefore, Long lastOnDemandTime, boolean isPartitionMoved,
boolean isDisabled) {
if (lastOnDemandTime == null) {
_gSetupTool.getClusterManagementTool().onDemandRebalance(CLUSTER_NAME);
} else {
setLastOnDemandRebalanceTimeInCluster(_gZkClient, CLUSTER_NAME, lastOnDemandTime);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
validatePartitionMovement(externalViewsBefore, isPartitionMoved, isDisabled);
}
protected Map<String, ExternalView> validatePartitionMovement(
Map<String, ExternalView> externalViewsBefore, boolean isPartitionMoved, boolean isDisabled) {
Map<String, ExternalView> externalViewAfter = new HashMap<>();
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
if (isPartitionMoved) {
validateMinActiveAndTopStateReplica(is, ev, _replica, NUM_NODE);
validateNoPartitionOnInstance(is, externalViewsBefore.get(db), ev,
_participants.get(0).getInstanceName());
} else {
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
validateNoPartitionMove(is, externalViewsBefore.get(db), ev,
_participants.get(0).getInstanceName(), isDisabled);
}
externalViewAfter.put(db, ev);
}
return externalViewAfter;
}
protected void validateNoPartitionOnInstance(IdealState is, ExternalView evBefore,
ExternalView evAfter, String instanceName) {
for (String partition : is.getPartitionSet()) {
Map<String, String> assignmentsBefore = evBefore.getRecord().getMapField(partition);
Map<String, String> assignmentsAfter = evAfter.getRecord().getMapField(partition);
Set<String> instancesAfter = new HashSet<String>(assignmentsAfter.keySet());
// the offline/disabled instance shouldn't have a partition assignment after rebalance
Assert.assertFalse(instancesAfter.contains(instanceName), String.format(
"%s is still on the instance after rebalance, before: %s, after: %s, instance: %s",
partition, assignmentsBefore.toString(), assignmentsAfter.toString(), instanceName));
}
}
private void validateDelayedMovements(Map<String, ExternalView> externalViewsBefore)
throws InterruptedException {
_participants.get(0).syncStop();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
validateNoPartitionMove(is, externalViewsBefore.get(db), ev, _participants.get(0).getInstanceName(), false);
}
}
protected void enableInstance(String instance, boolean enabled) {
// Disable one node, no partition should be moved.
long currentTime = System.currentTimeMillis();
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, instance, enabled);
InstanceConfig instanceConfig = _configAccessor.getInstanceConfig(CLUSTER_NAME, instance);
Assert.assertEquals(instanceConfig.getInstanceEnabled(), enabled);
Assert.assertTrue(instanceConfig.getInstanceEnabledTime() >= currentTime);
Assert.assertTrue(instanceConfig.getInstanceEnabledTime() <= currentTime + 100);
}
protected void validateDelayedMovementsOnDisabledNode(Map<String, ExternalView> externalViewsBefore)
throws Exception {
enableInstance(_participants.get(0).getInstanceName(), false);
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
validatePartitionMovement(externalViewsBefore, false, true);
}
@AfterClass
public void afterClass() throws Exception {
if (_clusterVerifier != null) {
_clusterVerifier.close();
}
/*
shutdown order: 1) disconnect the controller 2) disconnect participants
*/
_controller.syncStop();
for (MockParticipantManager participant : _participants) {
participant.syncStop();
}
deleteCluster(CLUSTER_NAME);
System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,547 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/DelayedAutoRebalancer/TestDelayedAutoRebalanceWithDisabledInstance.java
|
package org.apache.helix.integration.rebalancer.DelayedAutoRebalancer;
/*
* 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.Map;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestDelayedAutoRebalanceWithDisabledInstance extends TestDelayedAutoRebalance {
@BeforeClass
public void beforeClass() throws Exception {
super.beforeClass();
_configAccessor = new ConfigAccessor(_gZkClient);
_testingCondition = DISABLED_NODE;
}
/**
* The partition movement should be delayed (not happen immediately) after one single node is disabled.
* Delay is enabled by default, delay time is set in IdealState.
* @throws Exception
*/
@Test
@Override
public void testDelayedPartitionMovement() throws Exception {
Map<String, ExternalView> externalViewsBefore = createTestDBs(1000000);
// Disable one node, no partition should be moved.
String instance = _participants.get(0).getInstanceName();
enableInstance(instance, false);
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
validateNoPartitionMove(is, externalViewsBefore.get(db), ev, instance, true);
}
}
@Test(dependsOnMethods = {"testDelayedPartitionMovement"})
@Override
public void testDelayedPartitionMovementWithClusterConfigedDelay() throws Exception {
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, 1000000);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
// Disable one node, no partition should be moved.
String instance = _participants.get(0).getInstanceName();
enableInstance(instance, false);
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
validateNoPartitionMove(is, externalViewsBefore.get(db), ev,
_participants.get(0).getInstanceName(), true);
}
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, -1);
}
/**
* Test when two nodes were disabled, the minimal active replica should be maintained.
* @throws Exception
*/
@Test(dependsOnMethods = {"testDelayedPartitionMovement"})
@Override
public void testMinimalActiveReplicaMaintain() throws Exception {
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, 1000000);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
// disable one node, no partition should be moved.
enableInstance(_participants.get(0).getInstanceName(), false);
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
validateNoPartitionMove(is, externalViewsBefore.get(db), ev,
_participants.get(0).getInstanceName(), true);
}
// disable another node, the minimal active replica for each partition should be maintained.
enableInstance(_participants.get(3).getInstanceName(), false);
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
}
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, -1);
}
/**
* Test when one node is disable while another node is offline, the minimal active replica should be maintained.
* @throws Exception
*/
@Test(dependsOnMethods = {"testDelayedPartitionMovement"})
public void testMinimalActiveReplicaMaintainWithOneOffline() throws Exception {
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, 1000000);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
// disable one node, no partition should be moved.
enableInstance(_participants.get(0).getInstanceName(), false);
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
validateNoPartitionMove(is, externalViewsBefore.get(db), ev,
_participants.get(0).getInstanceName(), true);
}
// bring down another node, the minimal active replica for each partition should be maintained.
_participants.get(3).syncStop();
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
}
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, -1);
}
/**
* The partititon should be moved to other nodes after the delay time
*/
@Test (dependsOnMethods = {"testMinimalActiveReplicaMaintain"})
@Override
public void testPartitionMovementAfterDelayTime() throws Exception {
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
long delay = 10000;
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, delay);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
// disable one node, no partition should be moved.
enableInstance(_participants.get(0).getInstanceName(), false);
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
validateNoPartitionMove(is, externalViewsBefore.get(db), ev,
_participants.get(0).getInstanceName(), true);
}
Thread.sleep(delay + DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// after delay time, it should maintain required number of replicas.
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _replica, NUM_NODE);
}
}
@Test (dependsOnMethods = {"testMinimalActiveReplicaMaintain"})
@Override
public void testDisableDelayRebalanceInResource() throws Exception {
Map<String, ExternalView> externalViewsBefore = createTestDBs(1000000);
// disable one node, no partition should be moved.
enableInstance(_participants.get(0).getInstanceName(), false);
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
validateNoPartitionMove(is, externalViewsBefore.get(db), ev,
_participants.get(0).getInstanceName(), true);
}
// disable delay rebalance for one db, partition should be moved immediately
String testDb = _testDBs.get(0);
IdealState idealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(
CLUSTER_NAME, testDb);
idealState.setDelayRebalanceEnabled(false);
_gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, testDb, idealState);
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// once delay rebalance is disabled, it should maintain required number of replicas for that db.
// replica for other dbs should not be moved.
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
if (db.equals(testDb)) {
validateMinActiveAndTopStateReplica(idealState, ev, _replica, NUM_NODE);
} else {
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
validateNoPartitionMove(is, externalViewsBefore.get(db), ev,
_participants.get(0).getInstanceName(), true);
}
}
}
@Test (dependsOnMethods = {"testDisableDelayRebalanceInResource"})
@Override
public void testDisableDelayRebalanceInCluster() throws Exception {
enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, true);
setDelayTimeInCluster(_gZkClient, CLUSTER_NAME, 1000000);
Map<String, ExternalView> externalViewsBefore = createTestDBs(-1);
// disable one node, no partition should be moved.
enableInstance(_participants.get(0).getInstanceName(), false);
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _minActiveReplica, NUM_NODE);
validateNoPartitionMove(is, externalViewsBefore.get(db), ev,
_participants.get(0).getInstanceName(), true);
}
// disable delay rebalance for the entire cluster.
enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, false);
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(
CLUSTER_NAME, db);
validateMinActiveAndTopStateReplica(is, ev, _replica, NUM_NODE);
}
enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, true);
}
@Test (dependsOnMethods = {"testDisableDelayRebalanceInCluster"})
public void testDisableDelayRebalanceInInstance() throws Exception {
super.testDisableDelayRebalanceInInstance();
}
@Test(dependsOnMethods = {"testDisableDelayRebalanceInInstance"})
public void testOnDemandRebalance() throws Exception {
super.testOnDemandRebalance();
}
@Test(dependsOnMethods = {"testOnDemandRebalance"})
public void testExpiredOnDemandRebalanceTimestamp() throws Exception {
super.testExpiredOnDemandRebalanceTimestamp();
}
@Test(dependsOnMethods = {"testExpiredOnDemandRebalanceTimestamp"})
public void testOnDemandRebalanceAfterDelayRebalanceHappen() throws Exception {
super.testOnDemandRebalanceAfterDelayRebalanceHappen();
}
@BeforeMethod
public void beforeTest() {
// restart any participant that has been disconnected from last test.
for (int i = 0; i < _participants.size(); i++) {
if (!_participants.get(i).isConnected()) {
_participants.set(i, new MockParticipantManager(ZK_ADDR, CLUSTER_NAME,
_participants.get(i).getInstanceName()));
_participants.get(i).syncStart();
}
enableInstance(_participants.get(i).getInstanceName(), true);
}
}
}
| 9,548 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/DelayedAutoRebalancer/TestDelayedAutoRebalanceWithRackaware.java
|
package org.apache.helix.integration.rebalancer.DelayedAutoRebalancer;
/*
* 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.TestHelper;
import org.apache.helix.controller.rebalancer.strategy.CrushRebalanceStrategy;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.IdealState;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestDelayedAutoRebalanceWithRackaware extends TestDelayedAutoRebalance {
static final int NUM_NODE = 9;
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
String zone = "zone-" + i % 3;
_gSetupTool.getClusterManagementTool().setInstanceZoneId(CLUSTER_NAME, storageNodeName, zone);
// start dummy participants
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, storageNodeName);
participant.syncStart();
_participants.add(participant);
}
enableTopologyAwareRebalance(_gZkClient, CLUSTER_NAME, true);
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
_clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
}
@Override
protected IdealState createResourceWithDelayedRebalance(String clusterName, String db,
String stateModel, int numPartition, int replica, int minActiveReplica, long delay) {
return createResourceWithDelayedRebalance(clusterName, db, stateModel, numPartition, replica,
minActiveReplica, delay, CrushRebalanceStrategy.class.getName());
}
@Test
public void testDelayedPartitionMovement() throws Exception {
super.testDelayedPartitionMovement();
}
@Test(dependsOnMethods = {"testDelayedPartitionMovement"})
public void testDelayedPartitionMovementWithClusterConfigedDelay() throws Exception {
super.testDelayedPartitionMovementWithClusterConfigedDelay();
}
/**
* Test when two nodes go offline, the minimal active replica should be maintained.
* @throws Exception
*/
@Test(dependsOnMethods = {"testDelayedPartitionMovement"})
public void testMinimalActiveReplicaMaintain() throws Exception {
super.testMinimalActiveReplicaMaintain();
}
/**
* The partititon should be moved to other nodes after the delay time
*/
@Test (dependsOnMethods = {"testMinimalActiveReplicaMaintain"})
public void testPartitionMovementAfterDelayTime() throws Exception {
super.testPartitionMovementAfterDelayTime();
}
@Test (dependsOnMethods = {"testMinimalActiveReplicaMaintain"})
public void testDisableDelayRebalanceInResource() throws Exception {
super.testDisableDelayRebalanceInResource();
}
@Test (dependsOnMethods = {"testDisableDelayRebalanceInResource"})
public void testDisableDelayRebalanceInCluster() throws Exception {
super.testDisableDelayRebalanceInCluster();
}
@Test (dependsOnMethods = {"testDisableDelayRebalanceInCluster"})
public void testDisableDelayRebalanceInInstance() throws Exception {
super.testDisableDelayRebalanceInInstance();
}
@Test(dependsOnMethods = {"testDisableDelayRebalanceInInstance"})
public void testOnDemandRebalance() throws Exception {
super.testOnDemandRebalance();
}
@Test(dependsOnMethods = {"testOnDemandRebalance"})
public void testExpiredOnDemandRebalanceTimestamp() throws Exception {
super.testExpiredOnDemandRebalanceTimestamp();
}
@Test(dependsOnMethods = {"testExpiredOnDemandRebalanceTimestamp"})
public void testOnDemandRebalanceAfterDelayRebalanceHappen() throws Exception {
super.testOnDemandRebalanceAfterDelayRebalanceHappen();
}
}
| 9,549 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/PartitionMigration/TestExpandCluster.java
|
package org.apache.helix.integration.rebalancer.PartitionMigration;
/*
* 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.Map;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestExpandCluster extends TestPartitionMigrationBase {
Map<String, IdealState> _resourceMap;
@BeforeClass
public void beforeClass() throws Exception {
super.beforeClass();
_resourceMap = createTestDBs(1000000);
// TODO remove this sleep after fix https://github.com/apache/helix/issues/526
Thread.sleep(1000);
_migrationVerifier = new MigrationStateVerifier(_resourceMap, _manager);
}
@Test
public void testClusterExpansion() throws Exception {
Assert.assertTrue(_clusterVerifier.verifyByPolling());
_migrationVerifier.start();
// expand cluster by adding instance one by one
int numNodes = _participants.size();
for (int i = numNodes; i < numNodes + NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
MockParticipantManager participant = createAndStartParticipant(storageNodeName);
_participants.add(participant);
Thread.sleep(50);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
Assert.assertFalse(_migrationVerifier.hasLessReplica());
Assert.assertFalse(_migrationVerifier.hasMoreReplica());
_migrationVerifier.stop();
}
@Test (dependsOnMethods = {"testClusterExpansion"})
public void testClusterExpansionByEnableInstance() throws Exception {
Assert.assertTrue(_clusterVerifier.verifyByPolling());
_migrationVerifier.reset();
_migrationVerifier.start();
int numNodes = _participants.size();
// add new instances with all disabled
for (int i = numNodes; i < numNodes + NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
InstanceConfig config = InstanceConfig.toInstanceConfig(storageNodeName);
config.setInstanceEnabled(false);
config.getRecord().getSimpleFields()
.remove(InstanceConfig.InstanceConfigProperty.HELIX_ENABLED_TIMESTAMP.name());
_gSetupTool.getClusterManagementTool().addInstance(CLUSTER_NAME, config);
// start dummy participants
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, storageNodeName);
participant.syncStart();
_participants.add(participant);
}
// enable new instance one by one
for (int i = numNodes; i < numNodes + NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, storageNodeName, true);
Thread.sleep(100);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
Assert.assertFalse(_migrationVerifier.hasLessReplica());
_migrationVerifier.stop();
}
@Test(dependsOnMethods = {"testClusterExpansion", "testClusterExpansionByEnableInstance"})
public void testClusterShrink() throws Exception {
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setDelayRebalaceEnabled(false);
clusterConfig.setRebalanceDelayTime(0);
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
_migrationVerifier.reset();
_migrationVerifier.start();
// remove instance one by one
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
MockParticipantManager participant = _participants.get(i);
participant.syncStop();
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, storageNodeName, false);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
Assert.assertFalse(_migrationVerifier.hasLessMinActiveReplica());
Assert.assertFalse(_migrationVerifier.hasMoreReplica());
_migrationVerifier.stop();
}
}
| 9,550 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/PartitionMigration/TestPartitionMigrationBase.java
|
package org.apache.helix.integration.rebalancer.PartitionMigration;
/*
* 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.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.NotificationContext;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.api.listeners.ExternalViewChangeListener;
import org.apache.helix.api.listeners.IdealStateChangeListener;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.rebalancer.strategy.CrushRebalanceStrategy;
import org.apache.helix.integration.DelayedTransitionBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
public class TestPartitionMigrationBase extends ZkTestBase {
protected final int NUM_NODE = 6;
protected static final int START_PORT = 12918;
protected static final int _PARTITIONS = 50;
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected ClusterControllerManager _controller;
protected List<MockParticipantManager> _participants = new ArrayList<>();
protected int _replica = 3;
protected int _minActiveReplica = _replica - 1;
protected ZkHelixClusterVerifier _clusterVerifier;
protected List<String> _testDBs = new ArrayList<>();
protected MigrationStateVerifier _migrationVerifier;
protected HelixManager _manager;
protected ConfigAccessor _configAccessor;
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
MockParticipantManager participant = createAndStartParticipant(storageNodeName);
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
_clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
enablePersistIntermediateAssignment(_gZkClient, CLUSTER_NAME, true);
_manager = HelixManagerFactory
.getZKHelixManager(CLUSTER_NAME, "admin", InstanceType.ADMINISTRATOR, ZK_ADDR);
_manager.connect();
_configAccessor = new ConfigAccessor(_gZkClient);
}
protected MockParticipantManager createAndStartParticipant(String instancename) {
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, instancename);
// start dummy participants
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instancename, 10);
participant.setTransition(new DelayedTransitionBase(10));
participant.syncStart();
return participant;
}
protected String[] TestStateModels = {
BuiltInStateModelDefinitions.MasterSlave.name(),
BuiltInStateModelDefinitions.OnlineOffline.name(),
BuiltInStateModelDefinitions.LeaderStandby.name()
};
protected Map<String, IdealState> createTestDBs(long delayTime) throws InterruptedException {
Map<String, IdealState> idealStateMap = new HashMap<>();
int i = 0;
for (String stateModel : TestStateModels) {
String db = "Test-DB-" + i++;
createResourceWithDelayedRebalance(CLUSTER_NAME, db, stateModel, _PARTITIONS, _replica, _minActiveReplica,
-1, CrushRebalanceStrategy.class.getName());
_testDBs.add(db);
}
for (String db : _testDBs) {
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
idealStateMap.put(db, is);
}
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setDelayRebalaceEnabled(true);
clusterConfig.setRebalanceDelayTime(delayTime);
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
return idealStateMap;
}
protected class MigrationStateVerifier implements IdealStateChangeListener, ExternalViewChangeListener {
static final int EXTRA_REPLICA = 1;
boolean _hasMoreReplica = false;
boolean _hasLessReplica = false;
boolean _hasMinActiveReplica = false;
HelixManager _manager;
boolean trackEnabled = false;
Map<String, IdealState> _resourceMap;
public MigrationStateVerifier(Map<String, IdealState> resourceMap, HelixManager manager) {
_resourceMap = resourceMap;
_manager = manager;
}
// start tracking changes
public void start() throws Exception {
trackEnabled = true;
_manager.addIdealStateChangeListener(this);
_manager.addExternalViewChangeListener(this);
}
// stop tracking changes
public void stop() {
trackEnabled = false;
PropertyKey.Builder keyBuilder = _manager.getHelixDataAccessor().keyBuilder();
_manager.removeListener(keyBuilder.idealStates(), this);
_manager.removeListener(keyBuilder.externalViews(), this);
}
@Override
public void onIdealStateChange(List<IdealState> idealStates, NotificationContext changeContext)
throws InterruptedException {
if (!trackEnabled) {
return;
}
for (IdealState is : idealStates) {
int replica = is.getReplicaCount(NUM_NODE);
for (String p : is.getPartitionSet()) {
Map<String, String> stateMap = is.getRecord().getMapField(p);
verifyPartitionCount(is.getResourceName(), p, stateMap, replica, "IS",
is.getMinActiveReplicas());
}
}
}
@Override
public void onExternalViewChange(List<ExternalView> externalViewList,
NotificationContext changeContext) {
if (!trackEnabled) {
return;
}
for (ExternalView ev : externalViewList) {
IdealState is = _resourceMap.get(ev.getResourceName());
if (is == null) {
continue;
}
int replica = is.getReplicaCount(NUM_NODE);
for (String p : is.getPartitionSet()) {
Map<String, String> stateMap = ev.getStateMap(p);
verifyPartitionCount(is.getResourceName(), p, stateMap, replica, "EV",
is.getMinActiveReplicas());
}
}
}
private void verifyPartitionCount(String resource, String partition,
Map<String, String> stateMap, int replica, String warningPrefix, int minActiveReplica) {
if (stateMap.size() < replica) {
// System.out.println(
// "resource " + resource + ", partition " + partition + " has " + stateMap.size()
// + " replicas in " + warningPrefix);
_hasLessReplica = true;
}
if (stateMap.size() > replica + EXTRA_REPLICA) {
// System.out.println(
// "resource " + resource + ", partition " + partition + " has " + stateMap.size()
// + " replicas in " + warningPrefix);
// _hasMoreReplica = true;
}
if (stateMap.size() < minActiveReplica) {
// System.out.println(
// "resource " + resource + ", partition " + partition + " has " + stateMap.size()
// + " min active replicas in " + warningPrefix);
_hasMinActiveReplica = true;
}
}
public boolean hasMoreReplica() {
return _hasMoreReplica;
}
public boolean hasLessReplica() {
return _hasLessReplica;
}
public boolean hasLessMinActiveReplica() {
return _hasMinActiveReplica;
}
public void reset() {
_hasMoreReplica = false;
_hasLessReplica = false;
}
}
@AfterClass
public void afterClass() throws Exception {
/**
* shutdown order: 1) disconnect the controller 2) disconnect participants
*/
_controller.syncStop();
for (MockParticipantManager participant : _participants) {
participant.syncStop();
}
_manager.disconnect();
deleteCluster(CLUSTER_NAME);
System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,551 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/PartitionMigration/TestWagedRebalancerMigration.java
|
package org.apache.helix.integration.rebalancer.PartitionMigration;
/*
* 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.Collections;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.TestHelper;
import org.apache.helix.controller.rebalancer.strategy.CrushRebalanceStrategy;
import org.apache.helix.controller.rebalancer.waged.WagedRebalancer;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.IdealState;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestWagedRebalancerMigration extends TestPartitionMigrationBase {
ConfigAccessor _configAccessor;
@BeforeClass
public void beforeClass()
throws Exception {
super.beforeClass();
_configAccessor = new ConfigAccessor(_gZkClient);
}
@DataProvider(name = "stateModels")
public static Object[][] stateModels() {
return new Object[][] { { BuiltInStateModelDefinitions.MasterSlave.name(), true },
{ BuiltInStateModelDefinitions.OnlineOffline.name(), true },
{ BuiltInStateModelDefinitions.LeaderStandby.name(), true },
{ BuiltInStateModelDefinitions.MasterSlave.name(), false },
{ BuiltInStateModelDefinitions.OnlineOffline.name(), false },
{ BuiltInStateModelDefinitions.LeaderStandby.name(), false },
};
}
// TODO check the movements in between
@Test(dataProvider = "stateModels")
public void testMigrateToWagedRebalancerWhileExpandCluster(String stateModel,
boolean delayEnabled)
throws Exception {
String db = "Test-DB-" + stateModel;
if (delayEnabled) {
createResourceWithDelayedRebalance(CLUSTER_NAME, db, stateModel, _PARTITIONS, _replica,
_replica - 1, 3000000, CrushRebalanceStrategy.class.getName());
} else {
createResourceWithDelayedRebalance(CLUSTER_NAME, db, stateModel, _PARTITIONS, _replica,
_replica, 0, CrushRebalanceStrategy.class.getName());
}
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
ClusterConfig config = _configAccessor.getClusterConfig(CLUSTER_NAME);
config.setDelayRebalaceEnabled(delayEnabled);
config.setRebalanceDelayTime(3000000);
_configAccessor.setClusterConfig(CLUSTER_NAME, config);
// add new instance to the cluster
int numNodes = _participants.size();
for (int i = numNodes; i < numNodes + NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
MockParticipantManager participant = createAndStartParticipant(storageNodeName);
_participants.add(participant);
Thread.sleep(100);
}
ZkHelixClusterVerifier clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(clusterVerifier.verifyByPolling());
_migrationVerifier =
new MigrationStateVerifier(Collections.singletonMap(db, idealState), _manager);
_migrationVerifier.reset();
_migrationVerifier.start();
IdealState currentIdealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
currentIdealState.setRebalancerClassName(WagedRebalancer.class.getName());
_gSetupTool.getClusterManagementTool()
.setResourceIdealState(CLUSTER_NAME, db, currentIdealState);
Assert.assertTrue(clusterVerifier.verifyByPolling());
Assert.assertFalse(_migrationVerifier.hasLessReplica());
Assert.assertFalse(_migrationVerifier.hasMoreReplica());
_migrationVerifier.stop();
}
}
| 9,552 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/PartitionMigration/TestFullAutoMigration.java
|
package org.apache.helix.integration.rebalancer.PartitionMigration;
/*
* 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.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.controller.rebalancer.strategy.CrushRebalanceStrategy;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.ResourceConfig;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestFullAutoMigration extends TestPartitionMigrationBase {
ConfigAccessor _configAccessor;
@BeforeClass
public void beforeClass() throws Exception {
super.beforeClass();
_configAccessor = new ConfigAccessor(_gZkClient);
}
@DataProvider(name = "stateModels")
public static Object [][] stateModels() {
return new Object[][] { { BuiltInStateModelDefinitions.MasterSlave.name(), true},
{BuiltInStateModelDefinitions.OnlineOffline.name(), true},
{BuiltInStateModelDefinitions.LeaderStandby.name(), true},
{BuiltInStateModelDefinitions.MasterSlave.name(), false},
{BuiltInStateModelDefinitions.OnlineOffline.name(), false},
{BuiltInStateModelDefinitions.LeaderStandby.name(), false},
};
}
@Test(dataProvider = "stateModels")
public void testMigrateToFullAutoWhileExpandCluster(
String stateModel, boolean delayEnabled) throws Exception {
String db = "Test-DB-" + stateModel;
if (delayEnabled) {
createResourceWithDelayedRebalance(CLUSTER_NAME, db, stateModel, _PARTITIONS, _replica,
_replica - 1, 200000, CrushRebalanceStrategy.class.getName());
} else {
createResourceWithDelayedRebalance(CLUSTER_NAME, db, stateModel, _PARTITIONS, _replica,
_replica, 0, CrushRebalanceStrategy.class.getName());
}
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
Map<String, List<String>> userDefinedPreferenceLists = idealState.getPreferenceLists();
List<String> userDefinedPartitions = new ArrayList<>();
for (String partition : userDefinedPreferenceLists.keySet()) {
List<String> preferenceList = new ArrayList<>();
for (int k = _replica; k > 0; k--) {
String instance = _participants.get(k).getInstanceName();
preferenceList.add(instance);
}
userDefinedPreferenceLists.put(partition, preferenceList);
userDefinedPartitions.add(partition);
}
ResourceConfig resourceConfig =
new ResourceConfig.Builder(db).setPreferenceLists(userDefinedPreferenceLists).build();
_configAccessor.setResourceConfig(CLUSTER_NAME, db, resourceConfig);
// add new instance to the cluster
int numNodes = _participants.size();
for (int i = numNodes; i < numNodes + NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
MockParticipantManager participant = createAndStartParticipant(storageNodeName);
_participants.add(participant);
Thread.sleep(50);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
_migrationVerifier =
new MigrationStateVerifier(Collections.singletonMap(db, idealState), _manager);
_migrationVerifier.reset();
_migrationVerifier.start();
while (userDefinedPartitions.size() > 0) {
removePartitionFromUserDefinedList(db, userDefinedPartitions);
Thread.sleep(50);
}
Assert.assertTrue(_clusterVerifier.verifyByPolling());
Assert.assertFalse(_migrationVerifier.hasLessReplica());
Assert.assertFalse(_migrationVerifier.hasMoreReplica());
_migrationVerifier.stop();
}
private void removePartitionFromUserDefinedList(String db, List<String> userDefinedPartitions) {
ResourceConfig resourceConfig = _configAccessor.getResourceConfig(CLUSTER_NAME, db);
Map<String, List<String>> lists = resourceConfig.getPreferenceLists();
lists.remove(userDefinedPartitions.get(0));
resourceConfig.setPreferenceLists(lists);
userDefinedPartitions.remove(0);
_configAccessor.setResourceConfig(CLUSTER_NAME, db, resourceConfig);
}
// create test DBs, wait it converged and return externalviews
protected Map<String, IdealState> createTestDBs(long delayTime) throws InterruptedException {
Map<String, IdealState> idealStateMap = new HashMap<>();
int i = 0;
for (String stateModel : TestStateModels) {
String db = "Test-DB-" + i++;
createResourceWithDelayedRebalance(CLUSTER_NAME, db, stateModel, _PARTITIONS, _replica, _minActiveReplica,
delayTime);
_testDBs.add(db);
}
Thread.sleep(100);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
idealStateMap.put(db, is);
}
return idealStateMap;
}
}
| 9,553 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestCrushAutoRebalance.java
|
package org.apache.helix.integration.rebalancer.CrushRebalancers;
/*
* 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.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.helix.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.controller.rebalancer.strategy.CrushRebalanceStrategy;
import org.apache.helix.controller.rebalancer.strategy.MultiRoundCrushRebalanceStrategy;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestCrushAutoRebalance extends ZkTestBase {
private final int NUM_NODE = 6;
protected static final int START_PORT = 12918;
protected static final int _PARTITIONS = 20;
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected ClusterControllerManager _controller;
List<MockParticipantManager> _participants = new ArrayList<>();
Map<String, String> _nodeToZoneMap = new HashMap<>();
Map<String, String> _nodeToTagMap = new HashMap<>();
List<String> _nodes = new ArrayList<>();
Set<String> _allDBs = new HashSet<>();
int _replica = 3;
String[] _testModels = {
BuiltInStateModelDefinitions.OnlineOffline.name(),
BuiltInStateModelDefinitions.MasterSlave.name(),
BuiltInStateModelDefinitions.LeaderStandby.name()
};
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
String zone = "zone-" + i % 3;
String tag = "tag-" + i % 2;
_gSetupTool.getClusterManagementTool().setInstanceZoneId(CLUSTER_NAME, storageNodeName, zone);
_gSetupTool.getClusterManagementTool().addInstanceTag(CLUSTER_NAME, storageNodeName, tag);
_nodeToZoneMap.put(storageNodeName, zone);
_nodeToTagMap.put(storageNodeName, tag);
_nodes.add(storageNodeName);
}
// start dummy participants
for (String node : _nodes) {
MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
enableTopologyAwareRebalance(_gZkClient, CLUSTER_NAME, true);
}
@DataProvider(name = "rebalanceStrategies")
public static Object[][] rebalanceStrategies() {
return new String[][] {
{
"CrushRebalanceStrategy", CrushRebalanceStrategy.class.getName()
}, {
"MultiRoundCrushRebalanceStrategy", MultiRoundCrushRebalanceStrategy.class.getName()
}, {
"CrushEdRebalanceStrategy", CrushEdRebalanceStrategy.class.getName()
}
};
}
@Test(dataProvider = "rebalanceStrategies")
public void testZoneIsolation(String rebalanceStrategyName, String rebalanceStrategyClass)
throws Exception {
System.out.println("testZoneIsolation " + rebalanceStrategyName);
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + rebalanceStrategyName + "-" + i++;
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db, _PARTITIONS, stateModel,
RebalanceMode.FULL_AUTO + "", rebalanceStrategyClass);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
ZkHelixClusterVerifier _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _allDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
validateZoneAndTagIsolation(is, ev, _replica);
}
}
@Test(dataProvider = "rebalanceStrategies")
public void testZoneIsolationWithInstanceTag(String rebalanceStrategyName,
String rebalanceStrategyClass) throws Exception {
Set<String> tags = new HashSet<String>(_nodeToTagMap.values());
int i = 0;
for (String tag : tags) {
String db = "Test-DB-Tag-" + rebalanceStrategyName + "-" + i++;
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db, _PARTITIONS,
BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.FULL_AUTO + "",
rebalanceStrategyClass);
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
is.setInstanceGroupTag(tag);
_gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, db, is);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
ZkHelixClusterVerifier _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _allDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
validateZoneAndTagIsolation(is, ev, _replica);
}
}
@Test(dependsOnMethods = {
"testZoneIsolation", "testZoneIsolationWithInstanceTag"
})
public void testLackEnoughLiveRacks() throws Exception {
System.out.println("TestLackEnoughInstances");
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
// shutdown participants within one zone
String zone = _nodeToZoneMap.values().iterator().next();
for (int i = 0; i < _participants.size(); i++) {
MockParticipantManager p = _participants.get(i);
if (_nodeToZoneMap.get(p.getInstanceName()).equals(zone)) {
p.syncStop();
}
}
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-CrushRebalanceStrategy-" + i++;
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db, _PARTITIONS, stateModel,
RebalanceMode.FULL_AUTO + "", CrushRebalanceStrategy.class.getName());
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
ZkHelixClusterVerifier _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _allDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
validateZoneAndTagIsolation(is, ev, 2);
}
}
@Test(dependsOnMethods = {
"testLackEnoughLiveRacks"
})
public void testLackEnoughRacks() throws Exception {
System.out.println("TestLackEnoughInstances ");
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
// shutdown participants within one zone
String zone = _nodeToZoneMap.values().iterator().next();
for (int i = 0; i < _participants.size(); i++) {
MockParticipantManager p = _participants.get(i);
if (_nodeToZoneMap.get(p.getInstanceName()).equals(zone)) {
p.syncStop();
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, p.getInstanceName(),
false);
Thread.sleep(50);
_gSetupTool.dropInstanceFromCluster(CLUSTER_NAME, p.getInstanceName());
}
}
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-CrushRebalanceStrategy-" + i++;
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db, _PARTITIONS, stateModel,
RebalanceMode.FULL_AUTO + "", CrushRebalanceStrategy.class.getName());
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
ZkHelixClusterVerifier _clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _allDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
validateZoneAndTagIsolation(is, ev, 2);
}
}
@AfterMethod
public void afterMethod() throws Exception {
for (String db : _allDBs) {
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, db);
}
_allDBs.clear();
// waiting for all DB be dropped.
Thread.sleep(100);
}
/**
* Validate instances for each partition is on different zone and with necessary tagged instances.
*/
private void validateZoneAndTagIsolation(IdealState is, ExternalView ev, int expectedReplica) {
String tag = is.getInstanceGroupTag();
for (String partition : is.getPartitionSet()) {
Set<String> assignedZones = new HashSet<String>();
Map<String, String> assignmentMap = ev.getRecord().getMapField(partition);
Set<String> instancesInEV = assignmentMap.keySet();
// TODO: preference List is not persisted in IS.
// Assert.assertEquals(instancesInEV, instancesInIs);
for (String instance : instancesInEV) {
assignedZones.add(_nodeToZoneMap.get(instance));
if (tag != null) {
InstanceConfig config =
_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, instance);
Assert.assertTrue(config.containsTag(tag));
}
}
Assert.assertEquals(assignedZones.size(), expectedReplica);
}
}
@Test()
public void testAddZone() throws Exception {
// TODO
}
@Test()
public void testAddNodes() throws Exception {
// TODO
}
@Test()
public void testNodeFailure() throws Exception {
// TODO
}
@AfterClass
public void afterClass() throws Exception {
/*
* shutdown order: 1) disconnect the controller 2) disconnect participants
*/
if (_controller != null && _controller.isConnected()) {
_controller.syncStop();
}
for (MockParticipantManager p : _participants) {
if (p != null && p.isConnected()) {
p.syncStop();
}
}
deleteCluster(CLUSTER_NAME);
System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,554 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestCrushAutoRebalanceTopoplogyAwareDisabled.java
|
package org.apache.helix.integration.rebalancer.CrushRebalancers;
/*
* 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.common.ZkTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestCrushAutoRebalanceTopoplogyAwareDisabled extends TestCrushAutoRebalanceNonRack {
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (TestCrushAutoRebalanceNonRack.START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
_nodes.add(storageNodeName);
String tag = "tag-" + i % 2;
_gSetupTool.getClusterManagementTool().addInstanceTag(CLUSTER_NAME, storageNodeName, tag);
_nodeToTagMap.put(storageNodeName, tag);
}
// start dummy participants
for (String node : _nodes) {
MockParticipantManager participant =
new MockParticipantManager(ZkTestBase.ZK_ADDR, CLUSTER_NAME, node);
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZkTestBase.ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
enablePersistBestPossibleAssignment(ZkTestBase._gZkClient, CLUSTER_NAME, true);
}
@Test(dataProvider = "rebalanceStrategies")
public void test(String rebalanceStrategyName,
String rebalanceStrategyClass) throws Exception {
super.test(rebalanceStrategyName, rebalanceStrategyClass);
}
@Test(dataProvider = "rebalanceStrategies", dependsOnMethods = "test")
public void testWithInstanceTag(
String rebalanceStrategyName, String rebalanceStrategyClass) throws Exception {
super.testWithInstanceTag(rebalanceStrategyName, rebalanceStrategyClass);
}
@Test(dataProvider = "rebalanceStrategies", dependsOnMethods = { "test", "testWithInstanceTag"
})
public void testLackEnoughLiveInstances(String rebalanceStrategyName,
String rebalanceStrategyClass) throws Exception {
super.testLackEnoughLiveInstances(rebalanceStrategyName, rebalanceStrategyClass);
}
@Test(dataProvider = "rebalanceStrategies", dependsOnMethods = { "test", "testWithInstanceTag"
})
public void testLackEnoughInstances(String rebalanceStrategyName,
String rebalanceStrategyClass) throws Exception {
super.testLackEnoughInstances(rebalanceStrategyName, rebalanceStrategyClass);
}
}
| 9,555 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestNodeSwap.java
|
package org.apache.helix.integration.rebalancer.CrushRebalancers;
/*
* 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.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.controller.rebalancer.strategy.CrushRebalanceStrategy;
import org.apache.helix.controller.rebalancer.strategy.MultiRoundCrushRebalanceStrategy;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.tools.ClusterVerifiers.HelixClusterVerifier;
import org.apache.helix.tools.ClusterVerifiers.StrictMatchExternalViewVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestNodeSwap extends ZkTestBase {
final int NUM_NODE = 6;
protected static final int START_PORT = 12918;
protected static final int _PARTITIONS = 20;
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected ClusterControllerManager _controller;
List<MockParticipantManager> _participants = new ArrayList<>();
Set<String> _allDBs = new HashSet<>();
int _replica = 3;
String[] _testModels = {
BuiltInStateModelDefinitions.OnlineOffline.name(),
BuiltInStateModelDefinitions.MasterSlave.name(),
BuiltInStateModelDefinitions.LeaderStandby.name()
};
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setTopology("/zone/instance");
clusterConfig.setFaultZoneType("zone");
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
Set<String> nodes = new HashSet<>();
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
String zone = "zone-" + i % 3;
String domain = String.format("zone=%s,instance=%s", zone, storageNodeName);
InstanceConfig instanceConfig =
configAccessor.getInstanceConfig(CLUSTER_NAME, storageNodeName);
instanceConfig.setDomain(domain);
_gSetupTool.getClusterManagementTool().setInstanceConfig(CLUSTER_NAME, storageNodeName,
instanceConfig);
nodes.add(storageNodeName);
}
// start dummy participants
for (String node : nodes) {
MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
enableTopologyAwareRebalance(_gZkClient, CLUSTER_NAME, true);
}
@AfterClass
public void afterClass() throws Exception {
_controller.syncStop();
for (MockParticipantManager p : _participants) {
p.syncStop();
}
deleteCluster(CLUSTER_NAME);
}
@DataProvider(name = "rebalanceStrategies")
public static Object[][] rebalanceStrategies() {
return new String[][] {
{
"CrushRebalanceStrategy", CrushRebalanceStrategy.class.getName()
}, {
"MultiRoundCrushRebalanceStrategy", MultiRoundCrushRebalanceStrategy.class.getName()
}, {
"CrushEdRebalanceStrategy", CrushEdRebalanceStrategy.class.getName()
}
};
}
@Test(dataProvider = "rebalanceStrategies")
public void testNodeSwap(String rebalanceStrategyName, String rebalanceStrategyClass)
throws Exception {
System.out.println("Test testNodeSwap for " + rebalanceStrategyName);
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + rebalanceStrategyName + "-" + i++;
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db, _PARTITIONS, stateModel,
IdealState.RebalanceMode.FULL_AUTO + "", rebalanceStrategyClass);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
HelixClusterVerifier _clusterVerifier =
new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
.setDeactivatedNodeAwareness(true).setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verify(5000));
Map<String, ExternalView> record = new HashMap<>();
for (String db : _allDBs) {
record.put(db,
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db));
}
// swap a node and rebalance for new distribution
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
// 1. disable and remove an old node
MockParticipantManager oldParticipant = _participants.get(0);
String oldParticipantName = oldParticipant.getInstanceName();
final InstanceConfig instanceConfig =
_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, oldParticipantName);
// disable the node first
instanceConfig.setInstanceEnabled(false);
_gSetupTool.getClusterManagementTool().setInstanceConfig(CLUSTER_NAME, oldParticipantName,
instanceConfig);
Assert.assertTrue(_clusterVerifier.verify(10000));
// then remove it from topology
oldParticipant.syncStop();
Thread.sleep(2000);
_gSetupTool.getClusterManagementTool().dropInstance(CLUSTER_NAME, instanceConfig);
// 2. create new participant with same topology
String newParticipantName = "RandomParticipant-" + rebalanceStrategyName + "_" + START_PORT;
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, newParticipantName);
InstanceConfig newConfig = configAccessor.getInstanceConfig(CLUSTER_NAME, newParticipantName);
newConfig.setDomain(instanceConfig.getDomainAsString());
_gSetupTool.getClusterManagementTool().setInstanceConfig(CLUSTER_NAME, newParticipantName,
newConfig);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, newParticipantName);
participant.syncStart();
_participants.add(0, participant);
_clusterVerifier.close();
_clusterVerifier = new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
.setDeactivatedNodeAwareness(true).setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
try {
Assert.assertTrue(_clusterVerifier.verify(5000));
} finally {
_clusterVerifier.close();
}
for (String db : _allDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
ExternalView oldEv = record.get(db);
for (String partition : ev.getPartitionSet()) {
Map<String, String> stateMap = ev.getStateMap(partition);
Map<String, String> oldStateMap = oldEv.getStateMap(partition);
Assert.assertTrue(oldStateMap != null && stateMap != null);
for (String instance : stateMap.keySet()) {
String topoName = instance;
if (instance.equals(newParticipantName)) {
topoName = oldParticipantName;
}
Assert.assertEquals(stateMap.get(instance), oldStateMap.get(topoName));
}
}
}
}
}
| 9,556 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestCrushAutoRebalanceNonRack.java
|
package org.apache.helix.integration.rebalancer.CrushRebalancers;
/*
* 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.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.TestHelper;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.controller.rebalancer.strategy.CrushRebalanceStrategy;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
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.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.tools.ClusterVerifiers.HelixClusterVerifier;
import org.apache.helix.tools.ClusterVerifiers.StrictMatchExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.apache.helix.util.InstanceValidationUtil;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestCrushAutoRebalanceNonRack extends ZkStandAloneCMTestBase {
final int NUM_NODE = 6;
protected static final int START_PORT = 12918;
protected static final int _PARTITIONS = 20;
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected ClusterControllerManager _controller;
List<MockParticipantManager> _participants = new ArrayList<>();
Map<String, String> _nodeToTagMap = new HashMap<>();
List<String> _nodes = new ArrayList<>();
private Set<String> _allDBs = new HashSet<>();
private int _replica = 3;
private static String[] _testModels = {
BuiltInStateModelDefinitions.OnlineOffline.name(),
BuiltInStateModelDefinitions.MasterSlave.name(),
BuiltInStateModelDefinitions.LeaderStandby.name()
};
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
_gSetupTool.addCluster(CLUSTER_NAME, true);
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ClusterConfig clusterConfig = configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setTopology("/instance");
clusterConfig.setFaultZoneType("instance");
configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
for (int i = 0; i < NUM_NODE; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
_nodes.add(storageNodeName);
String tag = "tag-" + i % 2;
_gSetupTool.getClusterManagementTool().addInstanceTag(CLUSTER_NAME, storageNodeName, tag);
_nodeToTagMap.put(storageNodeName, tag);
InstanceConfig instanceConfig =
configAccessor.getInstanceConfig(CLUSTER_NAME, storageNodeName);
instanceConfig.setDomain("instance=" + storageNodeName);
configAccessor.setInstanceConfig(CLUSTER_NAME, storageNodeName, instanceConfig);
}
// start dummy participants
for (String node : _nodes) {
MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
participant.syncStart();
_participants.add(participant);
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
}
@AfterClass
public void afterClass() throws Exception {
if (_controller != null && _controller.isConnected()) {
_controller.syncStop();
}
for (MockParticipantManager p : _participants) {
if (p != null && p.isConnected()) {
p.syncStop();
}
}
deleteCluster(CLUSTER_NAME);
super.afterClass();
}
@DataProvider(name = "rebalanceStrategies")
public static String[][] rebalanceStrategies() {
return new String[][] {
{
"CrushRebalanceStrategy", CrushRebalanceStrategy.class.getName()
}, {
"CrushEdRebalanceStrategy", CrushEdRebalanceStrategy.class.getName()
}
};
}
@Test(dataProvider = "rebalanceStrategies", enabled = true)
public void test(String rebalanceStrategyName, String rebalanceStrategyClass) throws Exception {
System.out.println("Test " + rebalanceStrategyName);
int i = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + rebalanceStrategyName + "-" + i++;
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db, _PARTITIONS, stateModel,
RebalanceMode.FULL_AUTO + "", rebalanceStrategyClass);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
HelixClusterVerifier _clusterVerifier =
new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
.setDeactivatedNodeAwareness(true).setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
try {
Assert.assertTrue(_clusterVerifier.verify(5000));
} finally {
_clusterVerifier.close();
}
for (String db : _allDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
validateIsolation(is, ev, _replica);
}
}
@Test(dataProvider = "rebalanceStrategies", enabled = true, dependsOnMethods = "test")
public void testWithInstanceTag(String rebalanceStrategyName, String rebalanceStrategyClass)
throws Exception {
Set<String> tags = new HashSet<String>(_nodeToTagMap.values());
int i = 3;
for (String tag : tags) {
String db = "Test-DB-" + rebalanceStrategyName + "-" + i++;
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db, _PARTITIONS,
BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.FULL_AUTO + "",
rebalanceStrategyClass);
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
is.setInstanceGroupTag(tag);
_gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, db, is);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
HelixClusterVerifier _clusterVerifier =
new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
.setDeactivatedNodeAwareness(true).setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
try {
Assert.assertTrue(_clusterVerifier.verify(5000));
} finally {
_clusterVerifier.close();
}
for (String db : _allDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
validateIsolation(is, ev, _replica);
}
}
@Test(dataProvider = "rebalanceStrategies", enabled = true, dependsOnMethods = {
"testWithInstanceTag"
})
public void testLackEnoughLiveInstances(String rebalanceStrategyName,
String rebalanceStrategyClass) throws Exception {
System.out.println("TestLackEnoughLiveInstances " + rebalanceStrategyName);
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
// shutdown participants, keep only two left
for (int i = 2; i < _participants.size(); i++) {
_participants.get(i).syncStop();
}
int j = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + rebalanceStrategyName + "-" + j++;
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db, _PARTITIONS, stateModel,
RebalanceMode.FULL_AUTO + "", rebalanceStrategyClass);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
HelixClusterVerifier _clusterVerifier =
new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
.setDeactivatedNodeAwareness(true).setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
try {
Assert.assertTrue(_clusterVerifier.verify(5000));
} finally {
_clusterVerifier.close();
}
for (String db : _allDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
validateIsolation(is, ev, 2);
}
for (int i = 2; i < _participants.size(); i++) {
MockParticipantManager p = _participants.get(i);
MockParticipantManager newNode =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, p.getInstanceName());
_participants.set(i, newNode);
newNode.syncStart(); }
}
@Test(dataProvider = "rebalanceStrategies", enabled = true, dependsOnMethods = {
"testLackEnoughLiveInstances"
})
public void testLackEnoughInstances(String rebalanceStrategyName, String rebalanceStrategyClass)
throws Exception {
System.out.println("TestLackEnoughInstances " + rebalanceStrategyName);
enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
// Drop instance from admin tools and controller sending message to the same instance are
// fundamentally async. The race condition can also happen in production. For now we stabilize
// the test by disable controller and re-enable controller to eliminate this race condition as
// a workaround. New design is needed to fundamentally resolve the expose issue.
_controller.syncStop();
// shutdown participants, keep only two left
HelixDataAccessor helixDataAccessor =
new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
for (int i = 2; i < _participants.size(); i++) {
MockParticipantManager p = _participants.get(i);
p.syncStop();
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, p.getInstanceName(),
false);
Assert.assertTrue(TestHelper.verify(() -> {
_gSetupTool.getClusterManagementTool()
.enableInstance(CLUSTER_NAME, p.getInstanceName(), false);
return !InstanceValidationUtil.isEnabled(helixDataAccessor, p.getInstanceName())
&& !InstanceValidationUtil.isAlive(helixDataAccessor, p.getInstanceName());
}, TestHelper.WAIT_DURATION), "Instance should be disabled and offline");
_gSetupTool.dropInstanceFromCluster(CLUSTER_NAME, p.getInstanceName());
}
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
int j = 0;
for (String stateModel : _testModels) {
String db = "Test-DB-" + rebalanceStrategyName + "-" + j++;
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db, _PARTITIONS, stateModel,
RebalanceMode.FULL_AUTO + "", rebalanceStrategyClass);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
_allDBs.add(db);
}
ZkHelixClusterVerifier _clusterVerifier =
new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
.setDeactivatedNodeAwareness(true).setResources(_allDBs)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
try {
Assert.assertTrue(_clusterVerifier.verifyByPolling());
} finally {
_clusterVerifier.close();
}
for (String db : _allDBs) {
IdealState is =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
validateIsolation(is, ev, 2);
}
// recover test environment
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
for (int i = 2; i < _participants.size(); i++) {
String storageNodeName = _participants.get(i).getInstanceName();
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
InstanceConfig instanceConfig =
configAccessor.getInstanceConfig(CLUSTER_NAME, storageNodeName);
instanceConfig.setDomain("instance=" + storageNodeName);
configAccessor.setInstanceConfig(CLUSTER_NAME, storageNodeName, instanceConfig);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, storageNodeName);
participant.syncStart();
_participants.set(i, participant);
}
}
/**
* Validate each partition is different instances and with necessary tagged instances.
*/
private void validateIsolation(IdealState is, ExternalView ev, int expectedReplica) {
String tag = is.getInstanceGroupTag();
for (String partition : is.getPartitionSet()) {
Map<String, String> assignmentMap = ev.getRecord().getMapField(partition);
Set<String> instancesInEV = assignmentMap.keySet();
Assert.assertEquals(instancesInEV.size(), expectedReplica);
for (String instance : instancesInEV) {
if (tag != null) {
InstanceConfig config =
_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, instance);
Assert.assertTrue(config.containsTag(tag));
}
}
}
}
@AfterMethod
public void afterMethod() throws Exception {
for (String db : _allDBs) {
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, db);
}
_allDBs.clear();
// waiting for all DB be dropped.
Thread.sleep(200L);
}
}
| 9,557 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestCustomizedStateUpdate.java
|
package org.apache.helix.integration.paticipant;
/*
* 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.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.customizedstate.CustomizedStateProvider;
import org.apache.helix.customizedstate.CustomizedStateProviderFactory;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.model.CustomizedState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestCustomizedStateUpdate extends ZkStandAloneCMTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestCustomizedStateUpdate.class);
private final String CUSTOMIZE_STATE_NAME = "testState1";
private final String PARTITION_NAME1 = "testPartition1";
private final String PARTITION_NAME2 = "testPartition2";
private final String RESOURCE_NAME = "testResource1";
private final String PARTITION_STATE = "partitionState";
private static CustomizedStateProvider _mockProvider;
private PropertyKey _propertyKey;
private HelixDataAccessor _dataAccessor;
@BeforeClass
public void beforeClass() throws Exception {
super.beforeClass();
_participants[0].connect();
_mockProvider = CustomizedStateProviderFactory.getInstance()
.buildCustomizedStateProvider(_manager, _participants[0].getInstanceName());
_dataAccessor = _manager.getHelixDataAccessor();
_propertyKey = _dataAccessor.keyBuilder()
.customizedStates(_participants[0].getInstanceName(), CUSTOMIZE_STATE_NAME);
}
@BeforeMethod
public void beforeMethod() {
_dataAccessor.removeProperty(_propertyKey);
CustomizedState customizedStates = _dataAccessor.getProperty(_propertyKey);
Assert.assertNull(customizedStates);
}
@Test
public void testUpdateCustomizedState() {
// test adding customized state for a partition
Map<String, String> customizedStateMap = new HashMap<>();
customizedStateMap.put("PREVIOUS_STATE", "STARTED");
customizedStateMap.put("CURRENT_STATE", "END_OF_PUSH_RECEIVED");
_mockProvider.updateCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1,
customizedStateMap);
CustomizedState customizedState =
_mockProvider.getCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME);
Assert.assertNotNull(customizedState);
Assert.assertEquals(customizedState.getId(), RESOURCE_NAME);
Map<String, Map<String, String>> mapView = customizedState.getRecord().getMapFields();
Assert.assertEquals(mapView.keySet().size(), 1);
Assert.assertEquals(mapView.keySet().iterator().next(), PARTITION_NAME1);
// Updated 2 fields + START_TIME field is automatically updated for monitoring
Assert.assertEquals(mapView.get(PARTITION_NAME1).keySet().size(), 3);
Assert.assertEquals(mapView.get(PARTITION_NAME1).get("PREVIOUS_STATE"), "STARTED");
Assert.assertEquals(mapView.get(PARTITION_NAME1).get("CURRENT_STATE"), "END_OF_PUSH_RECEIVED");
// test partial update customized state for previous partition
Map<String, String> stateMap1 = new HashMap<>();
stateMap1.put("PREVIOUS_STATE", "END_OF_PUSH_RECEIVED");
_mockProvider
.updateCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1, stateMap1);
customizedState = _mockProvider.getCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME);
Assert.assertNotNull(customizedState);
Assert.assertEquals(customizedState.getId(), RESOURCE_NAME);
mapView = customizedState.getRecord().getMapFields();
Assert.assertEquals(mapView.keySet().size(), 1);
Assert.assertEquals(mapView.keySet().iterator().next(), PARTITION_NAME1);
Assert.assertEquals(mapView.get(PARTITION_NAME1).keySet().size(), 3);
Assert.assertEquals(mapView.get(PARTITION_NAME1).get("PREVIOUS_STATE"), "END_OF_PUSH_RECEIVED");
Assert.assertEquals(mapView.get(PARTITION_NAME1).get("CURRENT_STATE"), "END_OF_PUSH_RECEIVED");
// test full update customized state for previous partition
stateMap1 = new HashMap<>();
stateMap1.put("PREVIOUS_STATE", "END_OF_PUSH_RECEIVED");
stateMap1.put("CURRENT_STATE", "COMPLETED");
_mockProvider
.updateCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1, stateMap1);
customizedState = _mockProvider.getCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME);
Assert.assertNotNull(customizedState);
Assert.assertEquals(customizedState.getId(), RESOURCE_NAME);
mapView = customizedState.getRecord().getMapFields();
Assert.assertEquals(mapView.keySet().size(), 1);
Assert.assertEquals(mapView.keySet().iterator().next(), PARTITION_NAME1);
Assert.assertEquals(mapView.get(PARTITION_NAME1).keySet().size(), 3);
Assert.assertEquals(mapView.get(PARTITION_NAME1).get("PREVIOUS_STATE"), "END_OF_PUSH_RECEIVED");
Assert.assertEquals(mapView.get(PARTITION_NAME1).get("CURRENT_STATE"), "COMPLETED");
// test adding adding customized state for a new partition in the same resource
Map<String, String> stateMap2 = new HashMap<>();
stateMap2.put("PREVIOUS_STATE", "STARTED");
stateMap2.put("CURRENT_STATE", "END_OF_PUSH_RECEIVED");
_mockProvider
.updateCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME2, stateMap2);
customizedState = _mockProvider.getCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME);
Assert.assertNotNull(customizedState);
Assert.assertEquals(customizedState.getId(), RESOURCE_NAME);
mapView = customizedState.getRecord().getMapFields();
Assert.assertEquals(mapView.keySet().size(), 2);
Assert.assertEqualsNoOrder(mapView.keySet().toArray(),
new String[] { PARTITION_NAME1, PARTITION_NAME2 });
Map<String, String> partitionMap1 = _mockProvider
.getPerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1);
Assert.assertEquals(partitionMap1.keySet().size(), 3);
Assert.assertEquals(partitionMap1.get("PREVIOUS_STATE"), "END_OF_PUSH_RECEIVED");
Assert.assertEquals(partitionMap1.get("CURRENT_STATE"), "COMPLETED");
Map<String, String> partitionMap2 = _mockProvider
.getPerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME2);
Assert.assertEquals(partitionMap2.keySet().size(), 3);
Assert.assertEquals(partitionMap2.get("PREVIOUS_STATE"), "STARTED");
Assert.assertEquals(partitionMap2.get("CURRENT_STATE"), "END_OF_PUSH_RECEIVED");
// test delete customized state for a partition
_mockProvider
.deletePerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1);
customizedState = _mockProvider.getCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME);
Assert.assertNotNull(customizedState);
Assert.assertEquals(customizedState.getId(), RESOURCE_NAME);
mapView = customizedState.getRecord().getMapFields();
Assert.assertEquals(mapView.keySet().size(), 1);
Assert.assertEquals(mapView.keySet().iterator().next(), PARTITION_NAME2);
_mockProvider
.deletePerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME2);
customizedState = _mockProvider.getCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME);
Assert.assertNull(customizedState);
}
@Test
public void testUpdateSinglePartitionCustomizedState() {
_mockProvider.updateCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1,
PARTITION_STATE);
// get customized state
CustomizedState customizedState =
_mockProvider.getCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME);
// START_TIME field is automatically updated for monitoring
Assert.assertEquals(
customizedState.getPartitionStateMap(CustomizedState.CustomizedStateProperty.CURRENT_STATE)
.size(), 1);
Map<String, String> map = new HashMap<>();
map.put(PARTITION_NAME1, null);
Assert.assertEquals(customizedState
.getPartitionStateMap(CustomizedState.CustomizedStateProperty.PREVIOUS_STATE), map);
Assert.assertEquals(
customizedState.getPartitionStateMap(CustomizedState.CustomizedStateProperty.START_TIME).size(),
1);
Assert.assertEquals(
customizedState.getPartitionStateMap(CustomizedState.CustomizedStateProperty.END_TIME),
map);
Assert.assertEquals(customizedState.getState(PARTITION_NAME1), PARTITION_STATE);
Assert.assertNull(customizedState.getState(PARTITION_NAME2));
Assert.assertTrue(customizedState.isValid());
// get per partition customized state
map = new HashMap<>();
map.put(CustomizedState.CustomizedStateProperty.CURRENT_STATE.name(), PARTITION_STATE);
Map<String, String> partitionCustomizedState = _mockProvider
.getPerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1);
partitionCustomizedState.remove(CustomizedState.CustomizedStateProperty.START_TIME.name());
Assert.assertEquals(partitionCustomizedState, map);
Assert.assertNull(_mockProvider
.getPerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME2));
}
@Test
public void testUpdateSinglePartitionCustomizedStateWithNullField() {
_mockProvider
.updateCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1, (String) null);
// get customized state
CustomizedState customizedState =
_mockProvider.getCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME);
Map<String, String> map = new HashMap<>();
map.put(PARTITION_NAME1, null);
Assert.assertEquals(
customizedState.getPartitionStateMap(CustomizedState.CustomizedStateProperty.CURRENT_STATE),
map);
Assert.assertEquals(customizedState.getState(PARTITION_NAME1), null);
Assert.assertTrue(customizedState.isValid());
// get per partition customized state
map = new HashMap<>();
map.put(CustomizedState.CustomizedStateProperty.CURRENT_STATE.name(), null);
Map<String, String> partitionCustomizedState = _mockProvider
.getPerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1);
partitionCustomizedState.remove(CustomizedState.CustomizedStateProperty.START_TIME.name());
Assert.assertEquals(partitionCustomizedState, map);
Assert.assertNull(_mockProvider
.getPerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME2));
}
@Test
public void testUpdateCustomizedStateWithEmptyMap() {
_mockProvider.updateCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1,
new HashMap<>());
// get customized state
CustomizedState customizedState =
_mockProvider.getCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME);
Assert.assertNull(customizedState.getState(PARTITION_NAME1));
Map<String, String> partitionStateMap =
customizedState.getPartitionStateMap(CustomizedState.CustomizedStateProperty.CURRENT_STATE);
Assert.assertNotNull(partitionStateMap);
Assert.assertTrue(partitionStateMap.containsKey(PARTITION_NAME1));
Assert.assertNull(partitionStateMap.get(PARTITION_NAME1));
Assert.assertNull(customizedState.getState(PARTITION_NAME1));
Assert.assertFalse(partitionStateMap.containsKey(PARTITION_NAME2));
Assert.assertTrue(customizedState.isValid());
// get per partition customized state
Map<String, String> partitionCustomizedState = _mockProvider
.getPerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1);
// START_TIME field is automatically updated for monitoring
Assert.assertEquals(partitionCustomizedState.size(), 1);
Assert.assertNull(_mockProvider
.getPerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME2));
}
@Test
public void testDeleteNonExistingPerPartitionCustomizedState() {
_mockProvider.updateCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1,
PARTITION_STATE);
_mockProvider
.deletePerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME2);
Assert.assertNotNull(_mockProvider
.getPerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME1));
Assert.assertNull(_mockProvider
.getPerPartitionCustomizedState(CUSTOMIZE_STATE_NAME, RESOURCE_NAME, PARTITION_NAME2));
}
@Test
public void testSimultaneousUpdateCustomizedState() {
List<Callable<Boolean>> threads = new ArrayList<>();
int threadCount = 10;
for (int i = 0; i < threadCount; i++) {
threads.add(new TestSimultaneousUpdate());
}
Map<String, Boolean> resultMap = TestHelper.startThreadsConcurrently(threads, 1000);
Assert.assertEquals(resultMap.size(), threadCount);
Boolean[] results = new Boolean[threadCount];
Arrays.fill(results, true);
Assert.assertEqualsNoOrder(resultMap.values().toArray(), results);
}
private static class TestSimultaneousUpdate implements Callable<Boolean> {
private Random rand = new Random();
@Override
public Boolean call() {
String customizedStateName = "testState";
String resourceName = "resource" + String.valueOf(rand.nextInt(10));
String partitionName = "partition" + String.valueOf(rand.nextInt(10));
String partitionState = "Updated";
try {
_mockProvider.updateCustomizedState(customizedStateName, resourceName, partitionName,
partitionState);
} catch (Exception e) {
return false;
}
Map<String, String> states = _mockProvider
.getPerPartitionCustomizedState(customizedStateName, resourceName, partitionName);
if (states == null) {
return false;
}
return states.get(CustomizedState.CustomizedStateProperty.CURRENT_STATE.name())
.equals(partitionState);
}
}
}
| 9,558 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestInstanceCurrentState.java
|
package org.apache.helix.integration.paticipant;
/*
* 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 org.apache.helix.HelixDataAccessor;
import org.apache.helix.integration.task.TaskTestBase;
import org.apache.helix.integration.task.WorkflowGenerator;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.LiveInstance;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestInstanceCurrentState extends TaskTestBase {
private long _testStartTime;
@BeforeClass
public void beforeClass() throws Exception {
_testStartTime = System.currentTimeMillis();
setSingleTestEnvironment();
super.beforeClass();
}
@Test public void testAddedFieldsInCurrentState() {
String instanceName = PARTICIPANT_PREFIX + "_" + _startPort;
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
LiveInstance liveInstance =
accessor.getProperty(accessor.keyBuilder().liveInstance(instanceName));
CurrentState currentState = accessor.getProperty(accessor.keyBuilder()
.currentState(instanceName, liveInstance.getEphemeralOwner(), WorkflowGenerator.DEFAULT_TGT_DB));
// Test start time should happen after test start time
Assert.assertTrue(
currentState.getStartTime(WorkflowGenerator.DEFAULT_TGT_DB + "_0") >= _testStartTime);
// Test end time is always larger than start time
Assert.assertTrue(
currentState.getEndTime(WorkflowGenerator.DEFAULT_TGT_DB + "_0") >= currentState
.getStartTime(WorkflowGenerator.DEFAULT_TGT_DB + "_0"));
// Final state is MASTER, so SLAVE will be the previous state
Assert.assertEquals(currentState.getPreviousState(WorkflowGenerator.DEFAULT_TGT_DB + "_0"),
"SLAVE");
}
}
| 9,559 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestNonOfflineInitState.java
|
package org.apache.helix.integration.paticipant;
/*
* 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.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.mock.participant.MockBootstrapModelFactory;
import org.apache.helix.participant.StateMachineEngine;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestNonOfflineInitState extends ZkTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestNonOfflineInitState.class);
@Test
public void testNonOfflineInitState() throws Exception {
System.out.println("START testNonOfflineInitState at " + new Date(System.currentTimeMillis()));
String clusterName = getShortClassName();
setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
10, // partitions per resource
5, // number of nodes
1, // replicas
"Bootstrap", true); // do rebalance
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
// start participants
MockParticipantManager[] participants = new MockParticipantManager[5];
for (int i = 0; i < 5; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
// add a state model with non-OFFLINE initial state
StateMachineEngine stateMach = participants[i].getStateMachineEngine();
MockBootstrapModelFactory bootstrapFactory = new MockBootstrapModelFactory();
stateMach.registerStateModelFactory("Bootstrap", bootstrapFactory);
participants[i].syncStart();
}
boolean result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// clean up
controller.syncStop();
for (int i = 0; i < 5; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END testNonOfflineInitState at " + new Date(System.currentTimeMillis()));
}
private static void setupCluster(String clusterName, String ZkAddr, int startPort,
String participantNamePrefix, String resourceNamePrefix, int resourceNb, int partitionNb,
int nodesNb, int replica, String stateModelDef, boolean doRebalance) throws Exception {
_gSetupTool.addCluster(clusterName, true);
_gSetupTool.addStateModelDef(clusterName, "Bootstrap",
TestHelper.generateStateModelDefForBootstrap());
for (int i = 0; i < nodesNb; i++) {
int port = startPort + i;
_gSetupTool.addInstanceToCluster(clusterName, participantNamePrefix + "_" + port);
}
for (int i = 0; i < resourceNb; i++) {
String dbName = resourceNamePrefix + i;
_gSetupTool.addResourceToCluster(clusterName, dbName, partitionNb, stateModelDef);
if (doRebalance) {
_gSetupTool.rebalanceStorageCluster(clusterName, dbName, replica);
}
}
}
}
| 9,560 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestInstanceHistory.java
|
package org.apache.helix.integration.paticipant;
/*
* 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.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.PropertyKey;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.model.ParticipantHistory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestInstanceHistory extends ZkStandAloneCMTestBase {
@Test()
public void testInstanceHistory() throws Exception {
HelixManager manager = HelixManagerFactory
.getZKHelixManager(CLUSTER_NAME, "admin", InstanceType.ADMINISTRATOR, ZK_ADDR);
manager.connect();
PropertyKey.Builder keyBuilder = new PropertyKey.Builder(CLUSTER_NAME);
PropertyKey propertyKey = keyBuilder.participantHistory(_participants[0].getInstanceName());
ParticipantHistory history = manager.getHelixDataAccessor().getProperty(propertyKey);
Assert.assertNotNull(history);
List<String> list = history.getRecord().getListField("HISTORY");
Assert.assertEquals(list.size(), 1);
Assert.assertTrue(list.get(0).contains("SESSION=" + _participants[0].getSessionId()));
Assert.assertTrue(list.get(0).contains("VERSION=" + _participants[0].getVersion()));
String hostname;
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException ex) {
hostname = "UnknownHostname";
}
Assert
.assertTrue(list.get(0).contains("HOST=" + hostname));
Assert.assertTrue(list.get(0).contains("TIME="));
Assert.assertTrue(list.get(0).contains("DATE="));
for (int i = 0; i <= 22; i++) {
_participants[0].disconnect();
_participants[0].connect();
}
history = manager.getHelixDataAccessor().getProperty(propertyKey);
Assert.assertNotNull(history);
list = history.getRecord().getListField("HISTORY");
Assert.assertEquals(list.size(), 20);
list = history.getRecord().getListField("OFFLINE");
Assert.assertEquals(list.size(), 20);
manager.disconnect();
}
}
| 9,561 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestRestartParticipant.java
|
package org.apache.helix.integration.paticipant;
/*
* 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 java.util.concurrent.atomic.AtomicReference;
import org.apache.helix.NotificationContext;
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.mock.participant.MockTransition;
import org.apache.helix.model.Message;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestRestartParticipant extends ZkTestBase {
public class KillOtherTransition extends MockTransition {
final AtomicReference<MockParticipantManager> _other;
public KillOtherTransition(MockParticipantManager other) {
_other = new AtomicReference<MockParticipantManager>(other);
}
@Override
public void doTransition(Message message, NotificationContext context) {
MockParticipantManager other = _other.getAndSet(null);
if (other != null) {
System.err.println("Kill " + other.getInstanceName()
+ ". Interrupted exceptions are IGNORABLE");
other.syncStop();
}
}
}
@Test()
public void testRestartParticipant() throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
System.out.println("START testRestartParticipant at " + new Date(System.currentTimeMillis()));
String clusterName = getShortClassName();
MockParticipantManager[] participants = new MockParticipantManager[5];
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
10, // partitions per resource
5, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
// start participants
for (int i = 0; i < 5; i++) {
String instanceName = "localhost_" + (12918 + i);
if (i == 4) {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].setTransition(new KillOtherTransition(participants[0]));
} else {
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
}
participants[i].syncStart();
}
boolean result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// restart
Thread.sleep(500);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, participants[0].getClusterName(),
participants[0].getInstanceName());
System.err.println("Restart " + participant.getInstanceName());
participant.syncStart();
result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// clean up
controller.syncStop();
for (int i = 0; i < 5; i++) {
participants[i].syncStop();
}
participant.syncStop();
deleteCluster(clusterName);
System.out.println("START testRestartParticipant at " + new Date(System.currentTimeMillis()));
}
}
| 9,562 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestStateTransitionTimeoutWithResource.java
|
package org.apache.helix.integration.paticipant;
/*
* 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.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.NotificationContext;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.api.config.RebalanceConfig;
import org.apache.helix.api.config.StateTransitionTimeoutConfig;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.messaging.handling.MessageHandler.ErrorCode;
import org.apache.helix.mock.participant.MockMSStateModel;
import org.apache.helix.mock.participant.MockTransition;
import org.apache.helix.mock.participant.SleepTransition;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.Message;
import org.apache.helix.model.ResourceConfig;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.apache.helix.participant.statemachine.StateModelInfo;
import org.apache.helix.participant.statemachine.StateTransitionError;
import org.apache.helix.participant.statemachine.Transition;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.MasterNbInExtViewVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestStateTransitionTimeoutWithResource extends ZkStandAloneCMTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestStateTransitionTimeout.class);
private Map<String, SleepStateModelFactory> _factories;
private ConfigAccessor _configAccessor;
@Override
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
for (int i = 0; i < NODE_NR; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
}
_manager = HelixManagerFactory
.getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR);
_manager.connect();
_configAccessor = new ConfigAccessor(_gZkClient);
String controllerName = CONTROLLER_PREFIX + "_0";
_controller =
new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
boolean result =
ClusterStateVerifier
.verifyByZkCallback(new MasterNbInExtViewVerifier(ZK_ADDR, CLUSTER_NAME));
Assert.assertTrue(result);
}
@StateModelInfo(initialState = "OFFLINE", states = {
"MASTER", "SLAVE", "ERROR"
})
public static class TimeOutStateModel extends MockMSStateModel {
boolean _sleep = false;
StateTransitionError _error;
int _errorCallcount = 0;
public TimeOutStateModel(MockTransition transition, boolean sleep) {
super(transition);
_sleep = sleep;
}
@Transition(to = "MASTER", from = "SLAVE")
public void onBecomeMasterFromSlave(Message message, NotificationContext context)
throws InterruptedException {
LOG.info("Become MASTER from SLAVE");
if (_transition != null && _sleep) {
_transition.doTransition(message, context);
}
}
@Override
public void rollbackOnError(Message message, NotificationContext context,
StateTransitionError error) {
_error = error;
_errorCallcount++;
}
}
public static class SleepStateModelFactory extends StateModelFactory<TimeOutStateModel> {
Set<String> partitionsToSleep = new HashSet<String>();
int _sleepTime;
public SleepStateModelFactory(int sleepTime) {
_sleepTime = sleepTime;
}
public void setPartitions(Collection<String> partitions) {
partitionsToSleep.addAll(partitions);
}
public void addPartition(String partition) {
partitionsToSleep.add(partition);
}
@Override
public TimeOutStateModel createNewStateModel(String resource, String stateUnitKey) {
return new TimeOutStateModel(new SleepTransition(_sleepTime),
partitionsToSleep.contains(stateUnitKey));
}
}
@Test
public void testStateTransitionTimeOut() throws Exception {
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL);
_gSetupTool.getClusterManagementTool().enableResource(CLUSTER_NAME, TEST_DB, false);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, 3);
// Set the timeout values
StateTransitionTimeoutConfig stateTransitionTimeoutConfig =
new StateTransitionTimeoutConfig(new ZNRecord(TEST_DB));
stateTransitionTimeoutConfig.setStateTransitionTimeout("SLAVE", "MASTER", 300);
ResourceConfig resourceConfig = new ResourceConfig.Builder(TEST_DB)
.setStateTransitionTimeoutConfig(stateTransitionTimeoutConfig)
.setRebalanceConfig(new RebalanceConfig(new ZNRecord(TEST_DB)))
.setNumPartitions(_PARTITIONS).setHelixEnabled(false).build();
_configAccessor.setResourceConfig(CLUSTER_NAME, TEST_DB, resourceConfig);
setParticipants(TEST_DB);
_gSetupTool.getClusterManagementTool().enableResource(CLUSTER_NAME, TEST_DB, true);
boolean result =
ClusterStateVerifier
.verifyByPolling(new MasterNbInExtViewVerifier(ZK_ADDR, CLUSTER_NAME));
Assert.assertTrue(result);
TestHelper.verify(() -> verify(TEST_DB), 5000);
Assert.assertTrue(verify(TEST_DB));
}
@Test
public void testStateTransitionTimeoutByClusterLevel() throws Exception {
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB + 1, _PARTITIONS, STATE_MODEL);
_gSetupTool.getClusterManagementTool().enableResource(CLUSTER_NAME, TEST_DB + 1, false);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB + 1, 3);
StateTransitionTimeoutConfig stateTransitionTimeoutConfig =
new StateTransitionTimeoutConfig(new ZNRecord(TEST_DB + 1));
stateTransitionTimeoutConfig.setStateTransitionTimeout("SLAVE", "MASTER", 300);
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.setStateTransitionTimeoutConfig(stateTransitionTimeoutConfig);
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
setParticipants(TEST_DB + 1);
_gSetupTool.getClusterManagementTool().enableResource(CLUSTER_NAME, TEST_DB + 1, true);
boolean result =
ClusterStateVerifier
.verifyByPolling(new MasterNbInExtViewVerifier(ZK_ADDR, CLUSTER_NAME));
Assert.assertTrue(result);
TestHelper.verify(() -> verify(TEST_DB + 1), 5000);
Assert.assertTrue(verify(TEST_DB + 1));
}
private boolean verify(String dbName) {
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
ExternalView ev = accessor.getProperty(accessor.keyBuilder().externalView(dbName));
for (String p : idealState.getPartitionSet()) {
String idealMaster = idealState.getPreferenceList(p).get(0);
if(!ev.getStateMap(p).get(idealMaster).equals("ERROR")) {
return false;
}
TimeOutStateModel model = _factories.get(idealMaster).getStateModel(dbName, p);
if (model._errorCallcount != 1 || model._error.getCode() != ErrorCode.TIMEOUT) {
return false;
}
}
return true;
}
private void setParticipants(String dbName) throws InterruptedException {
_factories = new HashMap<>();
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
for (int i = 0; i < NODE_NR; i++) {
if (_participants[i] != null) {
_participants[i].syncStop();
}
Thread.sleep(1000);
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
SleepStateModelFactory factory = new SleepStateModelFactory(1000);
_factories.put(instanceName, factory);
for (String p : idealState.getPartitionSet()) {
if (idealState.getPreferenceList(p).get(0).equals(instanceName)) {
factory.addPartition(p);
}
}
_participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
_participants[i].getStateMachineEngine().registerStateModelFactory("MasterSlave", factory);
_participants[i].syncStart();
}
}
}
| 9,563 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestNodeOfflineTimeStamp.java
|
package org.apache.helix.integration.paticipant;
/*
* 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 org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.model.ParticipantHistory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestNodeOfflineTimeStamp extends ZkStandAloneCMTestBase {
@Test
public void testNodeShutdown() throws Exception {
for (MockParticipantManager participant : _participants) {
ParticipantHistory history = getInstanceHistory(participant.getInstanceName());
Assert.assertNotNull(history);
Assert.assertEquals(history.getLastOfflineTime(), ParticipantHistory.ONLINE);
}
long shutdownTime = System.currentTimeMillis();
_participants[0].syncStop();
ParticipantHistory history = getInstanceHistory(_participants[0].getInstanceName());
long recordTime = history.getLastOfflineTime();
Assert.assertTrue(Math.abs(shutdownTime - recordTime) <= 500L);
_participants[0].reset();
// Make it long enough to reduce the potential racing condition that cluster data cache report
// instance offline is actually after instance comes back
Thread.sleep(500);
_participants[0].syncStart();
Thread.sleep(50);
history = getInstanceHistory(_participants[0].getInstanceName());
Assert.assertEquals(history.getLastOfflineTime(), ParticipantHistory.ONLINE);
}
private ParticipantHistory getInstanceHistory(String instance) {
HelixDataAccessor accessor = _manager.getHelixDataAccessor();
PropertyKey propertyKey = accessor.keyBuilder().participantHistory(instance);
return accessor.getProperty(propertyKey);
}
}
| 9,564 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestInstanceAutoJoin.java
|
package org.apache.helix.integration.paticipant;
import java.util.Collections;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixException;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerProperty;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.api.cloud.CloudInstanceInformation;
import org.apache.helix.cloud.constants.CloudProvider;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.manager.zk.ZKHelixManager;
import org.apache.helix.model.CloudConfig;
import org.apache.helix.model.ConfigScope;
import org.apache.helix.model.HelixConfigScope;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.builder.ConfigScopeBuilder;
import org.apache.helix.model.builder.HelixConfigScopeBuilder;
import org.testng.Assert;
import org.testng.annotations.Test;
/*
* 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.
*/
public class TestInstanceAutoJoin extends ZkStandAloneCMTestBase {
String db2 = TEST_DB + "2";
String db3 = TEST_DB + "3";
@Test
public void testInstanceAutoJoin() throws Exception {
HelixManager manager = _participants[0];
HelixDataAccessor accessor = manager.getHelixDataAccessor();
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db2, 60, "OnlineOffline",
RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName());
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db2, 1);
String instance2 = "localhost_279699";
// StartCMResult result = TestHelper.startDummyProcess(ZK_ADDR, CLUSTER_NAME, instance2);
MockParticipantManager newParticipant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instance2);
newParticipant.syncStart();
Thread.sleep(500);
// Assert.assertFalse(result._thread.isAlive());
Assert.assertNull(manager.getHelixDataAccessor().getProperty(accessor.keyBuilder().liveInstance(instance2)));
ConfigScope scope = new ConfigScopeBuilder().forCluster(CLUSTER_NAME).build();
manager.getConfigAccessor().set(scope, ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN, "true");
newParticipant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instance2);
newParticipant.syncStart();
Thread.sleep(500);
// Assert.assertTrue(result._thread.isAlive() || result2._thread.isAlive());
for (int i = 0; i < 20; i++) {
if (null == manager.getHelixDataAccessor()
.getProperty(accessor.keyBuilder().liveInstance(instance2))) {
Thread.sleep(100);
} else {
break;
}
}
Assert.assertNotNull(
manager.getHelixDataAccessor().getProperty(accessor.keyBuilder().liveInstance(instance2)));
newParticipant.syncStop();
}
/**
* Test auto join with a defaultInstanceConfig.
* @throws Exception
*/
@Test(dependsOnMethods = "testInstanceAutoJoin")
public void testAutoJoinWithDefaultInstanceConfig() throws Exception {
HelixManager manager = _participants[0];
HelixDataAccessor accessor = manager.getHelixDataAccessor();
String instance3 = "localhost_279700";
// Enable cluster auto join.
HelixConfigScope scope =
new HelixConfigScopeBuilder(HelixConfigScope.ConfigScopeProperty.CLUSTER).forCluster(
CLUSTER_NAME).build();
manager.getConfigAccessor().set(scope, ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN, "true");
// Create and start a new participant with default instance config.
InstanceConfig.Builder defaultInstanceConfig =
new InstanceConfig.Builder().setInstanceEnabled(false).addTag("foo");
MockParticipantManager autoParticipant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instance3, 10, null,
new HelixManagerProperty.Builder().setDefaultInstanceConfigBuilder(
defaultInstanceConfig).build());
autoParticipant.syncStart();
Assert.assertTrue(TestHelper.verify(() -> {
// Check that live instance is added and instance config is populated with correct fields.
if (manager.getHelixDataAccessor().getProperty(accessor.keyBuilder().liveInstance(instance3))
== null) {
return false;
}
InstanceConfig composedInstanceConfig =
manager.getConfigAccessor().getInstanceConfig(CLUSTER_NAME, instance3);
return !composedInstanceConfig.getInstanceEnabled() && composedInstanceConfig.getTags()
.contains("foo");
}, 2000));
autoParticipant.syncStop();
}
@Test(dependsOnMethods = "testInstanceAutoJoin")
public void testAutoRegistration() throws Exception {
// Create CloudConfig object and add to config
CloudConfig.Builder cloudConfigBuilder = new CloudConfig.Builder();
cloudConfigBuilder.setCloudEnabled(true);
cloudConfigBuilder.setCloudProvider(CloudProvider.AZURE);
CloudConfig cloudConfig = cloudConfigBuilder.build();
HelixManager manager = _participants[0];
HelixDataAccessor accessor = manager.getHelixDataAccessor();
_gSetupTool.addResourceToCluster(CLUSTER_NAME, db3, 60, "OnlineOffline", RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName());
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db3, 1);
String instance4 = "localhost_279701";
ConfigScope scope = new ConfigScopeBuilder().forCluster(CLUSTER_NAME).build();
manager.getConfigAccessor().set(scope, ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN, "true");
// Write the CloudConfig to Zookeeper
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
accessor.setProperty(keyBuilder.cloudConfig(), cloudConfig);
MockParticipantManager autoParticipant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instance4);
autoParticipant.syncStart();
// if the test is run in cloud environment, auto registration will succeed and live instance
// will be added, otherwise, auto registration will fail and instance config will not be
// populated. An exception will be thrown.
try {
manager.getConfigAccessor().getInstanceConfig(CLUSTER_NAME, instance4);
Assert.assertTrue(TestHelper.verify(() -> {
if (null == manager.getHelixDataAccessor()
.getProperty(accessor.keyBuilder().liveInstance(instance4))) {
return false;
}
return true;
}, 2000));
} catch (HelixException e) {
Assert.assertNull(manager.getHelixDataAccessor()
.getProperty(accessor.keyBuilder().liveInstance(instance4)));
}
autoParticipant.syncStop();
}
/**
* Test auto registration with customized cloud info processor specified with fully qualified
* class name.
* @throws Exception
*/
@Test(dependsOnMethods = "testAutoRegistration")
public void testAutoRegistrationCustomizedFullyQualifiedInfoProcessorPath() throws Exception {
HelixManager manager = _participants[0];
HelixDataAccessor accessor = manager.getHelixDataAccessor();
String instance5 = "localhost_279702";
// Enable cluster auto join.
HelixConfigScope scope =
new HelixConfigScopeBuilder(HelixConfigScope.ConfigScopeProperty.CLUSTER).forCluster(
CLUSTER_NAME).build();
manager.getConfigAccessor().set(scope, ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN, "true");
// Create CloudConfig object for CUSTOM cloud provider.
CloudConfig cloudConfig =
new CloudConfig.Builder().setCloudEnabled(true).setCloudProvider(CloudProvider.CUSTOMIZED)
.setCloudInfoProcessorPackageName("org.apache.helix.integration.paticipant")
.setCloudInfoProcessorName("CustomCloudInstanceInformationProcessor")
.setCloudInfoSources(Collections.singletonList("https://cloud.com")).build();
// Update CloudConfig to Zookeeper.
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
accessor.setProperty(keyBuilder.cloudConfig(), cloudConfig);
// Create and start a new participant.
MockParticipantManager autoParticipant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instance5);
autoParticipant.syncStart();
Assert.assertTrue(TestHelper.verify(() -> {
// Check that live instance is added and instance config is populated with correct domain.
return null != manager.getHelixDataAccessor()
.getProperty(accessor.keyBuilder().liveInstance(instance5)) && manager.getConfigAccessor()
.getInstanceConfig(CLUSTER_NAME, instance5).getDomainAsString().equals(
CustomCloudInstanceInformation._cloudInstanceInfo.get(
CloudInstanceInformation.CloudInstanceField.FAULT_DOMAIN.name()))
&& manager.getConfigAccessor().getInstanceConfig(CLUSTER_NAME, instance5)
.getInstanceInfoMap().equals(CustomCloudInstanceInformation._cloudInstanceInfo);
}, 2000));
autoParticipant.syncStop();
}
}
| 9,565 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestStateTransitionTimeout.java
|
package org.apache.helix.integration.paticipant;
/*
* 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.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.NotificationContext;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.TestHelper;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.messaging.handling.MessageHandler.ErrorCode;
import org.apache.helix.mock.participant.MockMSStateModel;
import org.apache.helix.mock.participant.MockTransition;
import org.apache.helix.mock.participant.SleepTransition;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.Message;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.apache.helix.participant.statemachine.StateModelInfo;
import org.apache.helix.participant.statemachine.StateTransitionError;
import org.apache.helix.participant.statemachine.Transition;
import org.apache.helix.tools.ClusterSetup;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.MasterNbInExtViewVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestStateTransitionTimeout extends ZkStandAloneCMTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestStateTransitionTimeout.class);
@Override
@BeforeClass
public void beforeClass() throws Exception {
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL);
for (int i = 0; i < NODE_NR; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
}
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, 3);
// Set the timeout values
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, TEST_DB);
String stateTransition = "SLAVE" + "-" + "MASTER" + "_" + Message.Attributes.TIMEOUT;
idealState.getRecord().setSimpleField(stateTransition, "300");
String command =
"-zkSvr " + ZK_ADDR + " -addResourceProperty " + CLUSTER_NAME + " " + TEST_DB + " "
+ stateTransition + " 200";
ClusterSetup.processCommandLineArgs(command.split(" "));
}
@StateModelInfo(initialState = "OFFLINE", states = {
"MASTER", "SLAVE", "ERROR"
})
public static class TimeOutStateModel extends MockMSStateModel {
boolean _sleep = false;
StateTransitionError _error;
int _errorCallcount = 0;
public TimeOutStateModel(MockTransition transition, boolean sleep) {
super(transition);
_sleep = sleep;
}
@Transition(to = "MASTER", from = "SLAVE")
public void onBecomeMasterFromSlave(Message message, NotificationContext context)
throws InterruptedException {
LOG.info("Become MASTER from SLAVE");
if (_transition != null && _sleep) {
_transition.doTransition(message, context);
}
}
@Override
public void rollbackOnError(Message message, NotificationContext context,
StateTransitionError error) {
_error = error;
_errorCallcount++;
}
}
public static class SleepStateModelFactory extends StateModelFactory<TimeOutStateModel> {
Set<String> partitionsToSleep = new HashSet<String>();
int _sleepTime;
public SleepStateModelFactory(int sleepTime) {
_sleepTime = sleepTime;
}
public void setPartitions(Collection<String> partitions) {
partitionsToSleep.addAll(partitions);
}
public void addPartition(String partition) {
partitionsToSleep.add(partition);
}
@Override
public TimeOutStateModel createNewStateModel(String resource, String stateUnitKey) {
return new TimeOutStateModel(new SleepTransition(_sleepTime),
partitionsToSleep.contains(stateUnitKey));
}
}
@Test
public void testStateTransitionTimeOut() throws Exception {
Map<String, SleepStateModelFactory> factories = new HashMap<String, SleepStateModelFactory>();
IdealState idealState =
_gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, TEST_DB);
for (int i = 0; i < NODE_NR; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
SleepStateModelFactory factory = new SleepStateModelFactory(1000);
factories.put(instanceName, factory);
for (String p : idealState.getPartitionSet()) {
if (idealState.getPreferenceList(p).get(0).equals(instanceName)) {
factory.addPartition(p);
}
}
_participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
_participants[i].getStateMachineEngine().registerStateModelFactory("MasterSlave", factory);
_participants[i].syncStart();
}
String controllerName = CONTROLLER_PREFIX + "_0";
_controller =
new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
boolean result =
ClusterStateVerifier
.verifyByPolling(new MasterNbInExtViewVerifier(ZK_ADDR, CLUSTER_NAME));
Assert.assertTrue(result);
HelixDataAccessor accessor = _participants[0].getHelixDataAccessor();
TestHelper.verify(() -> verify(accessor, idealState, factories), 5000);
Assert.assertTrue(verify(accessor, idealState, factories));
}
private boolean verify(HelixDataAccessor accessor, IdealState idealState,
Map<String, SleepStateModelFactory> factoryMap) {
Builder kb = accessor.keyBuilder();
ExternalView ev = accessor.getProperty(kb.externalView(TEST_DB));
for (String p : idealState.getPartitionSet()) {
String idealMaster = idealState.getPreferenceList(p).get(0);
if (!ev.getStateMap(p).get(idealMaster).equals("ERROR")) {
return false;
}
TimeOutStateModel model = factoryMap.get(idealMaster).getStateModel(TEST_DB, p);
if (model._errorCallcount != 1 || model._error.getCode() != ErrorCode.TIMEOUT) {
return false;
}
}
return true;
}
}
| 9,566 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestParticipantErrorMessage.java
|
package org.apache.helix.integration.paticipant;
/*
* 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.UUID;
import org.apache.helix.Criteria;
import org.apache.helix.InstanceType;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.manager.zk.DefaultParticipantErrorMessageHandlerFactory;
import org.apache.helix.manager.zk.DefaultParticipantErrorMessageHandlerFactory.ActionOnError;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.Message;
import org.apache.helix.model.Message.MessageType;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestParticipantErrorMessage extends ZkStandAloneCMTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestParticipantErrorMessage.class);
@Test()
public void TestParticipantErrorMessageSend() {
String participant1 = "localhost_" + START_PORT;
String participant2 = "localhost_" + (START_PORT + 1);
Message errorMessage1 =
new Message(MessageType.PARTICIPANT_ERROR_REPORT, UUID.randomUUID().toString());
errorMessage1.setTgtSessionId("*");
errorMessage1.getRecord().setSimpleField(
DefaultParticipantErrorMessageHandlerFactory.ACTIONKEY,
ActionOnError.DISABLE_INSTANCE.toString());
Criteria recipientCriteria = new Criteria();
recipientCriteria.setRecipientInstanceType(InstanceType.CONTROLLER);
recipientCriteria.setSessionSpecific(false);
_participants[0].getMessagingService().send(recipientCriteria,
errorMessage1);
Message errorMessage2 =
new Message(MessageType.PARTICIPANT_ERROR_REPORT, UUID.randomUUID().toString());
errorMessage2.setTgtSessionId("*");
errorMessage2.setResourceName("TestDB");
errorMessage2.setPartitionName("TestDB_14");
errorMessage2.getRecord().setSimpleField(
DefaultParticipantErrorMessageHandlerFactory.ACTIONKEY,
ActionOnError.DISABLE_PARTITION.toString());
Criteria recipientCriteria2 = new Criteria();
recipientCriteria2.setRecipientInstanceType(InstanceType.CONTROLLER);
recipientCriteria2.setSessionSpecific(false);
_participants[1].getMessagingService().send(recipientCriteria2,
errorMessage2);
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
LOG.error("Interrupted sleep", e);
}
boolean result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
CLUSTER_NAME));
Assert.assertTrue(result);
Builder kb = _participants[1].getHelixDataAccessor().keyBuilder();
ExternalView externalView =
_participants[1].getHelixDataAccessor().getProperty(
kb.externalView("TestDB"));
for (String partitionName : externalView.getRecord().getMapFields().keySet()) {
for (String hostName : externalView.getRecord().getMapField(partitionName).keySet()) {
if (hostName.equals(participant1)) {
Assert.assertTrue(externalView.getRecord().getMapField(partitionName).get(hostName)
.equalsIgnoreCase("OFFLINE"));
}
}
}
Assert.assertTrue(externalView.getRecord().getMapField("TestDB_14").get(participant2)
.equalsIgnoreCase("OFFLINE"));
}
}
| 9,567 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/CustomCloudInstanceInformation.java
|
package org.apache.helix.integration.paticipant;
/*
* 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 com.google.common.collect.ImmutableMap;
import org.apache.helix.api.cloud.CloudInstanceInformation;
import org.apache.helix.api.cloud.CloudInstanceInformationV2;
/**
* This is a custom implementation of CloudInstanceInformation. It is used to test the functionality
* of Helix node auto-registration.
*/
public class CustomCloudInstanceInformation implements CloudInstanceInformationV2 {
public static final ImmutableMap<String, String> _cloudInstanceInfo =
ImmutableMap.of(CloudInstanceInformation.CloudInstanceField.FAULT_DOMAIN.name(),
"mz=0, host=localhost, container=containerId", "MAINTENANCE_ZONE", "0", "INSTANCE_NAME",
"localhost_something");
public CustomCloudInstanceInformation() {
}
@Override
public String get(String key) {
return _cloudInstanceInfo.get(key);
}
@Override
public ImmutableMap<String, String> getAll() {
return _cloudInstanceInfo;
}
}
| 9,568 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestParticipantFreeze.java
|
package org.apache.helix.integration.paticipant;
/*
* 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.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkTestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.ClusterManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.messaging.DefaultMessagingService;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.Message;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.util.MessageUtil;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestParticipantFreeze extends ZkTestBase {
private HelixManager _manager;
private HelixDataAccessor _accessor;
private PropertyKey.Builder _keyBuilder;
private String _clusterName;
private int _numNodes;
private String _resourceName;
private String _instanceName;
private MockParticipantManager[] _participants;
// current states in participant[0]
private List<CurrentState> _originCurStates;
private String _originSession;
@BeforeClass
public void beforeClass() throws Exception {
_clusterName = "CLUSTER_" + TestHelper.getTestClassName();
_numNodes = 3;
_resourceName = "TestDB";
_participants = new MockParticipantManager[_numNodes];
TestHelper.setupCluster(_clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
_resourceName, // resource name prefix
1, // resources
1, // partitions per resource
_numNodes, // number of nodes
3, // replicas
"MasterSlave", true);
_manager = HelixManagerFactory
.getZKHelixManager(_clusterName, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR);
_manager.connect();
_accessor = _manager.getHelixDataAccessor();
_keyBuilder = _accessor.keyBuilder();
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
controller.syncStart();
// start participants
for (int i = 0; i < _numNodes; i++) {
String instanceName = "localhost_" + (12918 + i);
_participants[i] = new MockParticipantManager(ZK_ADDR, _clusterName, instanceName);
_participants[i].syncStart();
}
_instanceName = _participants[0].getInstanceName();
Assert.assertTrue(ClusterStateVerifier.verifyByZkCallback(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName)));
// We just need controller to rebalance the cluster once to get current states.
controller.syncStop();
_originSession = _participants[0].getSessionId();
_originCurStates =
_accessor.getChildValues(_keyBuilder.currentStates(_instanceName, _originSession), false);
}
@AfterClass
public void afterClass() {
_manager.disconnect();
Arrays.stream(_participants).forEach(ClusterManager::syncStop);
deleteCluster(_clusterName);
}
/*
* Live instance is not frozen and does not have a frozen status field
*/
@Test
public void testNormalLiveInstanceStatus() {
LiveInstance liveInstance = _accessor.getProperty(_keyBuilder.liveInstance(_instanceName));
Assert.assertEquals(liveInstance.getStatus(), LiveInstance.LiveInstanceStatus.NORMAL);
Assert.assertNull(
liveInstance.getRecord().getSimpleField(LiveInstance.LiveInstanceProperty.STATUS.name()));
}
@Test(dependsOnMethods = "testNormalLiveInstanceStatus")
public void testFreezeParticipant() throws Exception {
freezeParticipant(_participants[0]);
}
// Simulates instance is restarted and the in-memory status is gone.
// When instance comes back alive, it'll reset state model, carry over
// and set current state to init state.
@Test(dependsOnMethods = "testFreezeParticipant")
public void testRestartParticipantWhenFrozen() throws Exception {
String instanceName = _participants[1].getInstanceName();
List<CurrentState> originCurStates = _accessor
.getChildValues(_keyBuilder.currentStates(instanceName, _participants[1].getSessionId()),
false);
String oldSession = _participants[1].getSessionId();
freezeParticipant(_participants[1]);
// Restart participants[1]
_participants[1].syncStop();
_participants[1] = new MockParticipantManager(ZK_ADDR, _participants[1].getClusterName(),
instanceName);
_participants[1].syncStart();
Assert.assertTrue(TestHelper.verify(() ->
_gZkClient.exists(_keyBuilder.liveInstance(instanceName).getPath()),
TestHelper.WAIT_DURATION));
LiveInstance liveInstance = _accessor.getProperty(_keyBuilder.liveInstance(instanceName));
// New live instance ephemeral node
Assert.assertEquals(liveInstance.getEphemeralOwner(), _participants[1].getSessionId());
// Status is not frozen because controller is not running, no freeze message sent.
verifyLiveInstanceStatus(_participants[1], LiveInstance.LiveInstanceStatus.NORMAL);
// Old session current state is deleted because of current state carry-over
Assert.assertTrue(TestHelper.verify(
() -> !_gZkClient.exists(_keyBuilder.currentStates(instanceName, oldSession).getPath()),
TestHelper.WAIT_DURATION));
// Current states are set to init states (OFFLINE)
List<CurrentState> curStates = _accessor
.getChildValues(_keyBuilder.currentStates(instanceName, _participants[1].getSessionId()),
false);
Assert.assertEquals(curStates.size(), 1);
Assert.assertTrue(TestHelper.verify(() -> {
for (CurrentState cs : originCurStates) {
String stateModelDefRef = cs.getStateModelDefRef();
for (String partition : cs.getPartitionStateMap().keySet()) {
StateModelDefinition stateModelDef =
_accessor.getProperty(_keyBuilder.stateModelDef(stateModelDefRef));
String initState = stateModelDef.getInitialState();
if (!initState.equals(curStates.get(0).getPartitionStateMap().get(partition))) {
return false;
}
}
}
return true;
}, TestHelper.WAIT_DURATION));
}
// Simulates session expires but in-memory status is still kept.
// No state model reset or current state carry-over
@Test(dependsOnMethods = "testRestartParticipantWhenFrozen")
public void testHandleNewSessionWhenFrozen() throws Exception {
// there are current states for the resource
Assert.assertFalse(_originCurStates.isEmpty());
ZkTestHelper.expireSession(_participants[0].getZkClient());
String currentSession = _participants[0].getSessionId();
Assert.assertFalse(_originSession.equals(currentSession));
Assert.assertTrue(TestHelper.verify(() ->
_gZkClient.exists(_keyBuilder.liveInstance(_instanceName).getPath()),
TestHelper.WAIT_DURATION));
LiveInstance liveInstance = _accessor.getProperty(_keyBuilder.liveInstance(_instanceName));
// New live instance ephemeral node with FROZEN status
Assert.assertFalse(_originSession.equals(liveInstance.getEphemeralOwner()));
Assert.assertEquals(liveInstance.getStatus(), LiveInstance.LiveInstanceStatus.FROZEN);
// New session path does not exist since no current state carry over for the current session.
Assert.assertFalse(
_gZkClient.exists(_keyBuilder.currentStates(_instanceName, currentSession).getPath()));
// Old session CS still exist.
Assert.assertTrue(
_gZkClient.exists(_keyBuilder.currentStates(_instanceName, _originSession).getPath()));
}
@Test(dependsOnMethods = "testHandleNewSessionWhenFrozen")
public void testUnfreezeParticipant() throws Exception {
Message unfreezeMessage = MessageUtil
.createStatusChangeMessage(LiveInstance.LiveInstanceStatus.FROZEN,
LiveInstance.LiveInstanceStatus.NORMAL, _manager.getInstanceName(),
_manager.getSessionId(), _instanceName, _participants[0].getSessionId());
List<PropertyKey> keys = Collections
.singletonList(_keyBuilder.message(unfreezeMessage.getTgtName(), unfreezeMessage.getId()));
boolean[] success = _accessor.createChildren(keys, Collections.singletonList(unfreezeMessage));
Assert.assertTrue(success[0]);
// Live instance status is NORMAL, but set to null value in both memory and zk.
// After live instance status is updated, the process is completed.
verifyLiveInstanceStatus(_participants[0], LiveInstance.LiveInstanceStatus.NORMAL);
// Unfreeze message is correctly deleted
Assert.assertNull(
_accessor.getProperty(_keyBuilder.message(_instanceName, unfreezeMessage.getId())));
// current state is carried over
List<CurrentState> curStates = _accessor
.getChildValues(_keyBuilder.currentStates(_instanceName, _participants[0].getSessionId()),
false);
Assert.assertFalse(curStates.isEmpty());
// The original current states are deleted.
Assert.assertFalse(
_gZkClient.exists(_keyBuilder.currentStates(_instanceName, _originSession).getPath()));
// current states should be the same as the original current states
// with CS carry-over when unfreezing
Assert.assertTrue(verifyCurrentStates(_originCurStates, curStates));
}
private void verifyLiveInstanceStatus(MockParticipantManager participant,
LiveInstance.LiveInstanceStatus status) throws Exception {
// Verify live instance status in both memory and zk
Assert.assertTrue(TestHelper.verify(() -> {
LiveInstance.LiveInstanceStatus inMemoryLiveInstanceStatus =
((DefaultMessagingService) participant.getMessagingService()).getExecutor()
.getLiveInstanceStatus();
return inMemoryLiveInstanceStatus == status;
}, TestHelper.WAIT_DURATION));
Assert.assertTrue(TestHelper.verify(() -> {
LiveInstance liveInstance =
_accessor.getProperty(_keyBuilder.liveInstance(participant.getInstanceName()));
return liveInstance.getStatus() == status;
}, TestHelper.WAIT_DURATION));
}
private boolean verifyCurrentStates(List<CurrentState> originCurStates,
List<CurrentState> curStates) {
for (CurrentState ocs : originCurStates) {
for (CurrentState cs : curStates) {
if (cs.getId().equals(ocs.getId())
&& !cs.getPartitionStateMap().equals(ocs.getPartitionStateMap())) {
return false;
}
}
}
return true;
}
private void freezeParticipant(MockParticipantManager participant) throws Exception {
Message freezeMessage = MessageUtil
.createStatusChangeMessage(LiveInstance.LiveInstanceStatus.NORMAL,
LiveInstance.LiveInstanceStatus.FROZEN, _manager.getInstanceName(),
_manager.getSessionId(), participant.getInstanceName(), participant.getSessionId());
List<PropertyKey> keys = Collections
.singletonList(_keyBuilder.message(freezeMessage.getTgtName(), freezeMessage.getId()));
boolean[] success = _accessor.createChildren(keys, Collections.singletonList(freezeMessage));
Assert.assertTrue(success[0]);
// Live instance status is frozen in both memory and zk
verifyLiveInstanceStatus(participant, LiveInstance.LiveInstanceStatus.FROZEN);
// Freeze message is correctly deleted
Assert.assertTrue(TestHelper.verify(() -> !_gZkClient.exists(
_keyBuilder.message(participant.getInstanceName(), freezeMessage.getId()).getPath()),
TestHelper.WAIT_DURATION));
}
}
| 9,569 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestParticipantNameCollision.java
|
package org.apache.helix.integration.paticipant;
/*
* 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.TestHelper;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
public class TestParticipantNameCollision extends ZkStandAloneCMTestBase {
private static Logger logger = LoggerFactory.getLogger(TestParticipantNameCollision.class);
@Test()
public void testParticiptantNameCollision() throws Exception {
logger.info("RUN TestParticipantNameCollision() at " + new Date(System.currentTimeMillis()));
MockParticipantManager newParticipant = null;
for (int i = 0; i < 1; i++) {
String instanceName = "localhost_" + (START_PORT + i);
try {
// the call fails on getClusterManagerForParticipant()
// no threads start
newParticipant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
newParticipant.syncStart();
} catch (Exception e) {
e.printStackTrace();
}
}
Thread.sleep(30000);
TestHelper.verifyWithTimeout("verifyNotConnected", 30 * 1000, newParticipant);
logger.info("STOP TestParticipantNameCollision() at " + new Date(System.currentTimeMillis()));
}
}
| 9,570 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/CustomCloudInstanceInformationProcessor.java
|
package org.apache.helix.integration.paticipant;
/*
* 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.Collections;
import java.util.List;
import org.apache.helix.HelixCloudProperty;
import org.apache.helix.api.cloud.CloudInstanceInformation;
import org.apache.helix.api.cloud.CloudInstanceInformationProcessor;
/**
* This is a custom implementation of CloudInstanceInformationProcessor.
* It is used to test the functionality of Helix node auto-registration.
*/
public class CustomCloudInstanceInformationProcessor implements CloudInstanceInformationProcessor<String> {
public CustomCloudInstanceInformationProcessor(HelixCloudProperty helixCloudProperty) {
}
@Override
public List<String> fetchCloudInstanceInformation() {
return Collections.singletonList("response");
}
@Override
public CloudInstanceInformation parseCloudInstanceInformation(List<String> responses) {
return new CustomCloudInstanceInformation();
}
}
| 9,571 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/paticipant/TestStateTransitionAppFailureHandling.java
|
package org.apache.helix.integration.paticipant;
/*
* 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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixDefinedState;
import org.apache.helix.HelixException;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.controller.stages.MessageGenerationPhase;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.mock.participant.MockMSStateModel;
import org.apache.helix.mock.participant.MockTransition;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.Message;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.apache.helix.util.MessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestStateTransitionAppFailureHandling extends ZkStandAloneCMTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestStateTransitionAppFailureHandling.class);
private final static int REPLICAS = 3;
@Override
@BeforeClass
public void beforeClass() throws Exception {
super.beforeClass();
// Clean up the resource that is created in the super cluster beforeClass method.
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, TEST_DB);
_clusterVerifier.verifyByPolling();
}
public static class RetryStateModelFactory extends StateModelFactory<MockMSStateModel> {
int _retryCountUntilSucceed;
public RetryStateModelFactory(int retryCountUntilSucceed) {
_retryCountUntilSucceed = retryCountUntilSucceed;
}
public int getRemainingRetryCountUntilSucceed() {
return _retryCountUntilSucceed;
}
@Override
public MockMSStateModel createNewStateModel(String resource, String stateUnitKey) {
if (_retryCountUntilSucceed > 0) {
_retryCountUntilSucceed--;
throw new HelixException("You Shall Not PASS!!!");
} else {
return new MockMSStateModel(new MockTransition());
}
}
}
@Test
public void testSTHandlerInitFailureRetry() throws Exception {
int retryCountUntilSucceed =
Integer.MAX_VALUE; // ensure the retry count is large so the message retry will fail.
Map<String, RetryStateModelFactory> retryFactoryMap = resetParticipants(retryCountUntilSucceed);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, REPLICAS);
HelixDataAccessor accessor = _controller.getHelixDataAccessor();
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
// Verify and wait until all messages have been retried and failed.
Map<String, List<Message>> partitionMessageMap = new HashMap<>();
Assert.assertTrue(TestHelper.verify(() -> {
int totalMessageCount = 0;
for (int i = 0; i < NODE_NR; i++) {
String instanceName = _participants[i].getInstanceName();
List<Message> messageList = accessor.getProperty(
accessor.getChildNames(keyBuilder.messages(instanceName)).stream()
.map(childName -> keyBuilder.message(instanceName, childName))
.collect(Collectors.toList()), true);
for (Message message : messageList) {
if (message == null || message.getMsgState() != Message.MessageState.UNPROCESSABLE) {
return false;
}
}
partitionMessageMap.put(instanceName, messageList);
totalMessageCount += messageList.size();
}
return totalMessageCount == _PARTITIONS * REPLICAS;
}, TestHelper.WAIT_DURATION));
// Verify that the correct numbers of retry has been done on each node.
for (String instanceName : partitionMessageMap.keySet()) {
List<Message> instanceMessages = partitionMessageMap.get(instanceName);
for (Message message : instanceMessages) {
Assert.assertTrue(message.getRetryCount() <= 0);
Assert.assertEquals(message.getMsgState(), Message.MessageState.UNPROCESSABLE);
}
// Check if the factory has tried enough times before fail the message.
Assert.assertEquals(retryCountUntilSucceed - retryFactoryMap.get(instanceName)
.getRemainingRetryCountUntilSucceed(), instanceMessages.size()
* MessageUtil.DEFAULT_STATE_TRANSITION_MESSAGE_RETRY_COUNT);
}
// Verify that the partition is not initialized.
for (int i = 0; i < NODE_NR; i++) {
String instanceName = _participants[i].getInstanceName();
String sessionId = _participants[i].getSessionId();
List<CurrentState> currentStates = accessor.getProperty(
accessor.getChildNames(keyBuilder.currentStates(instanceName, sessionId)).stream()
.map(childName -> keyBuilder.currentState(instanceName, sessionId, childName))
.collect(Collectors.toList()), true);
for (CurrentState currentState : currentStates) {
Assert.assertTrue(currentState.getPartitionStateMap().isEmpty());
}
}
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, TEST_DB);
}
@Test(dependsOnMethods = "testSTHandlerInitFailureRetry")
public void testSTHandlerInitFailureRetrySucceed() {
// Make the mock StateModelFactory return handler before last retry. So it will successfully
// finish handler initialization.
int retryCountUntilSucceed =
MessageUtil.DEFAULT_STATE_TRANSITION_MESSAGE_RETRY_COUNT - 1;
Map<String, RetryStateModelFactory> retryFactoryMap = resetParticipants(retryCountUntilSucceed);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, REPLICAS);
HelixDataAccessor accessor = _controller.getHelixDataAccessor();
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
// Verify and wait until all messages have been processed and the cluster is stable.
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// Verify that the partition is not in error state. And all messages has been completed.
for (int i = 0; i < NODE_NR; i++) {
String instanceName = _participants[i].getInstanceName();
String sessionId = _participants[i].getSessionId();
List<Message> messageList = accessor.getProperty(
accessor.getChildNames(keyBuilder.messages(instanceName)).stream()
.map(childName -> keyBuilder.message(instanceName, childName))
.collect(Collectors.toList()), true);
Assert.assertTrue(messageList.isEmpty());
List<CurrentState> currentStates = accessor.getProperty(
accessor.getChildNames(keyBuilder.currentStates(instanceName, sessionId)).stream()
.map(childName -> keyBuilder.currentState(instanceName, sessionId, childName))
.collect(Collectors.toList()), true);
for (CurrentState currentState : currentStates) {
Assert.assertTrue(currentState.getPartitionStateMap().values().stream()
.allMatch(state -> !state.equals(HelixDefinedState.ERROR.name())));
}
// The factory should has 0 remaining "retryCountUntilSucceed".
Assert
.assertEquals(retryFactoryMap.get(instanceName).getRemainingRetryCountUntilSucceed(), 0);
}
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, TEST_DB);
}
private Map<String, RetryStateModelFactory> resetParticipants(int retryCountUntilSucceed) {
Map<String, RetryStateModelFactory> retryFactoryMap = new HashMap<>();
for (int i = 0; i < NODE_NR; i++) {
if (_participants[i] != null && _participants[i].isConnected()) {
_participants[i].syncStop();
}
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
RetryStateModelFactory factory = new RetryStateModelFactory(retryCountUntilSucceed);
retryFactoryMap.put(instanceName, factory);
_participants[i].getStateMachineEngine().registerStateModelFactory("MasterSlave", factory);
_participants[i].syncStart();
}
return retryFactoryMap;
}
}
| 9,572 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestControllerHistory.java
|
package org.apache.helix.integration.controller;
/*
* 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.List;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.PropertyKey;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.model.ControllerHistory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestControllerHistory extends ZkStandAloneCMTestBase {
@Test()
public void testControllerLeaderHistory() throws Exception {
HelixManager manager = HelixManagerFactory
.getZKHelixManager(CLUSTER_NAME, "admin", InstanceType.ADMINISTRATOR, ZK_ADDR);
manager.connect();
PropertyKey.Builder keyBuilder = new PropertyKey.Builder(CLUSTER_NAME);
PropertyKey propertyKey = keyBuilder.controllerLeaderHistory();
ControllerHistory controllerHistory = manager.getHelixDataAccessor().getProperty(propertyKey);
Assert.assertNotNull(controllerHistory);
List<String> list = controllerHistory.getRecord().getListField("HISTORY");
Assert.assertEquals(list.size(), 1);
for (int i = 0; i <= 12; i++) {
_controller.syncStop();
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, "Controller-" + i);
_controller.syncStart();
}
controllerHistory = manager.getHelixDataAccessor().getProperty(propertyKey);
Assert.assertNotNull(controllerHistory);
list = controllerHistory.getRecord().getListField("HISTORY");
Assert.assertEquals(list.size(), 10);
manager.disconnect();
}
}
| 9,573 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestWatcherLeakageOnController.java
|
package org.apache.helix.integration.controller;
/*
* 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.List;
import java.util.Map;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkTestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestWatcherLeakageOnController extends ZkTestBase {
private final String CLASS_NAME = getShortClassName();
private final String TEST_RESOURCE = "TestResource";
private final String CLUSTER_NAME = "TestCluster-" + CLASS_NAME;
private ZkHelixClusterVerifier _clusterVerifier;
@BeforeClass
public void beforeClass() throws Exception {
super.beforeClass();
_clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
_gSetupTool.addCluster(CLUSTER_NAME, true);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, "TestInstance");
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_RESOURCE, 10, "MasterSlave");
}
@AfterClass
public void afterClass() {
deleteCluster(CLUSTER_NAME);
}
@Test
public void testWatcherOnResourceDeletion() throws Exception {
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, "TestController");
controller.syncStart();
Map<String, List<String>> zkWatches = ZkTestHelper.getZkWatch(controller.getZkClient());
List<String> dataWatchesBefore = zkWatches.get("dataWatches");
_gSetupTool.dropResourceFromCluster(CLUSTER_NAME, TEST_RESOURCE);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
zkWatches = ZkTestHelper.getZkWatch(controller.getZkClient());
List<String> dataWatchesAfter = zkWatches.get("dataWatches");
Assert.assertEquals(dataWatchesBefore.size() - dataWatchesAfter.size(), 1);
dataWatchesBefore.removeAll(dataWatchesAfter);
// The data watch on [/TestCluster-TestWatcherLeakageOnController/IDEALSTATES/TestResource] should be removed
Assert.assertTrue(dataWatchesBefore.get(0).contains(TEST_RESOURCE));
controller.syncStop();
}
@Test
public void testWatcherOnResourceAddition() throws Exception {
String tmpResource = "tmpResource";
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, "TestController");
controller.syncStart();
Map<String, List<String>> zkWatches = ZkTestHelper.getZkWatch(controller.getZkClient());
List<String> dataWatchesBefore = zkWatches.get("dataWatches");
_gSetupTool.addResourceToCluster(CLUSTER_NAME, tmpResource, 10, "MasterSlave");
Assert.assertTrue(_clusterVerifier.verifyByPolling());
zkWatches = ZkTestHelper.getZkWatch(controller.getZkClient());
List<String> dataWatchesAfter = zkWatches.get("dataWatches");
Assert.assertEquals(dataWatchesAfter.size() - dataWatchesBefore.size(), 1);
dataWatchesAfter.removeAll(dataWatchesBefore);
// The data watch on [/TestCluster-TestWatcherLeakageOnController/IDEALSTATES/tmpResource] should be added
Assert.assertTrue(dataWatchesAfter.get(0).contains(tmpResource));
controller.syncStop();
}
}
| 9,574 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestGenericHelixControllerThreading.java
|
package org.apache.helix.integration.controller;
/*
* 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.Set;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.controller.GenericHelixController;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestGenericHelixControllerThreading extends ZkUnitTestBase {
private static final String EVENT_PROCESS_THREAD_NAME_PREFIX =
"GerenricHelixController-event_process";
// Temporarily disabling the test as it's not stable when running under the entire mvn test suite.
// Some other crashed tests might cause this one to fail as controllers might not be gracefully
// shutdown
@Test(enabled = false)
public void testGenericHelixControllerThreadCount() throws Exception {
System.out.println("testGenericHelixControllerThreadCount STARTs");
final int numControllers = 100;
ArrayList<GenericHelixController> controllers = createHelixControllers(numControllers);
Assert.assertEquals(getThreadCountByNamePrefix(EVENT_PROCESS_THREAD_NAME_PREFIX), numControllers * 2);
int remainingExpectedEventProcessThreadsCount = numControllers * 2;
for (GenericHelixController ctrl : controllers) {
ctrl.shutdown();
remainingExpectedEventProcessThreadsCount -= 2;
Assert.assertEquals(getThreadCountByNamePrefix(EVENT_PROCESS_THREAD_NAME_PREFIX),
remainingExpectedEventProcessThreadsCount);
}
System.out.println("testGenericHelixControllerThreadCount ENDs");
}
private ArrayList<GenericHelixController> createHelixControllers(int count) {
ArrayList<GenericHelixController> ret = new ArrayList<>();
for (int i = 0; i < count; i++) {
ret.add(new GenericHelixController());
}
return ret;
}
private int getThreadCountByNamePrefix(String threadNamePrefix) {
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
int eventThreadCount = 0;
for (Thread t : threadSet) {
if (t.getName().startsWith(threadNamePrefix)) {
eventThreadCount += 1;
}
}
return eventThreadCount;
}
}
| 9,575 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestClusterFreezeMode.java
|
package org.apache.helix.integration.controller;
/*
* 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.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import org.apache.helix.HelixConstants;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.NotificationContext;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.api.status.ClusterManagementMode;
import org.apache.helix.api.status.ClusterManagementModeRequest;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.integration.manager.ClusterControllerManager;
import org.apache.helix.integration.manager.ClusterManager;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.mock.participant.ErrTransition;
import org.apache.helix.mock.participant.MockTransition;
import org.apache.helix.model.ClusterStatus;
import org.apache.helix.model.ControllerHistory;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.Message;
import org.apache.helix.model.PauseSignal;
import org.apache.helix.model.Resource;
import org.apache.helix.model.StateModelDefinition;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.util.MessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestClusterFreezeMode extends ZkTestBase {
private HelixManager _manager;
private HelixDataAccessor _accessor;
private String _clusterName;
private int _numNodes;
private MockParticipantManager[] _participants;
private ClusterControllerManager _controller;
@BeforeClass
public void beforeClass() throws Exception {
_numNodes = 3;
_clusterName = "CLUSTER_" + TestHelper.getTestClassName();
_participants = new MockParticipantManager[_numNodes];
TestHelper.setupCluster(_clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
2, // partitions per resource
_numNodes, // number of nodes
3, // replicas
"MasterSlave", true);
_manager = HelixManagerFactory
.getZKHelixManager(_clusterName, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR);
_manager.connect();
_accessor = _manager.getHelixDataAccessor();
// start controller
_controller = new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
_controller.syncStart();
Map<String, Set<String>> errPartitions = new HashMap<String, Set<String>>() {
{
put("OFFLINE-SLAVE", TestHelper.setOf("TestDB0_0"));
}
};
// start participants
for (int i = 0; i < _numNodes; i++) {
String instanceName = "localhost_" + (12918 + i);
_participants[i] = new MockParticipantManager(ZK_ADDR, _clusterName, instanceName);
if (i == 0) {
// Make TestDB0_0 be error state on participant_0
_participants[i].setTransition(new ErrTransition(errPartitions));
}
_participants[i].syncStart();
}
boolean result = ClusterStateVerifier.verifyByZkCallback(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName));
Assert.assertTrue(result);
}
@AfterClass
public void afterClass() {
_manager.disconnect();
_controller.syncStop();
Arrays.stream(_participants).forEach(ClusterManager::syncStop);
deleteCluster(_clusterName);
}
/*
* Tests below scenarios:
* 1. cluster is in progress to freeze mode if there is a pending state transition message;
* 2. after state transition is completed, cluster freeze mode is completed
*
* Also tests cluster status and management mode history recording.
*/
@Test
public void testEnableFreezeMode() throws Exception {
String methodName = TestHelper.getTestMethodName();
// Not in freeze mode
PropertyKey.Builder keyBuilder = _accessor.keyBuilder();
PauseSignal pauseSignal = _accessor.getProperty(keyBuilder.pause());
Assert.assertNull(pauseSignal);
// Block state transition for participants[1]
CountDownLatch latch = new CountDownLatch(1);
_participants[1].setTransition(new BlockingTransition(latch));
// Send a state transition message to participants[1]
Resource resource = new Resource("TestDB0");
resource.setStateModelFactoryName(HelixConstants.DEFAULT_STATE_MODEL_FACTORY);
Message message = MessageUtil
.createStateTransitionMessage(_manager.getInstanceName(), _manager.getSessionId(), resource,
"TestDB0_1", _participants[1].getInstanceName(), "SLAVE", "OFFLINE",
_participants[1].getSessionId(), "MasterSlave");
Assert.assertTrue(_accessor
.updateProperty(keyBuilder.message(message.getTgtName(), message.getMsgId()), message));
// Freeze cluster
ClusterManagementModeRequest request = ClusterManagementModeRequest.newBuilder()
.withClusterName(_clusterName)
.withMode(ClusterManagementMode.Type.CLUSTER_FREEZE)
.withReason(methodName)
.build();
_gSetupTool.getClusterManagementTool().setClusterManagementMode(request);
// Wait for all live instances are marked as frozen
verifyLiveInstanceStatus(_participants, LiveInstance.LiveInstanceStatus.FROZEN);
// Pending ST message exists
Assert.assertTrue(
_gZkClient.exists(keyBuilder.message(message.getTgtName(), message.getMsgId()).getPath()));
// Even live instance status is marked as frozen, Cluster is in progress to cluster freeze
// because there is a pending state transition message
ClusterStatus expectedClusterStatus = new ClusterStatus();
expectedClusterStatus.setManagementMode(ClusterManagementMode.Type.CLUSTER_FREEZE);
expectedClusterStatus.setManagementModeStatus(ClusterManagementMode.Status.IN_PROGRESS);
verifyClusterStatus(expectedClusterStatus);
// Verify management mode history is empty
ControllerHistory controllerHistory =
_accessor.getProperty(_accessor.keyBuilder().controllerLeaderHistory());
List<String> managementHistory = controllerHistory.getManagementModeHistory();
Assert.assertTrue(managementHistory.isEmpty());
// Unblock to finish state transition and delete the ST message
latch.countDown();
// Verify live instance status and cluster status
verifyLiveInstanceStatus(_participants, LiveInstance.LiveInstanceStatus.FROZEN);
expectedClusterStatus = new ClusterStatus();
expectedClusterStatus.setManagementMode(ClusterManagementMode.Type.CLUSTER_FREEZE);
expectedClusterStatus.setManagementModeStatus(ClusterManagementMode.Status.COMPLETED);
verifyClusterStatus(expectedClusterStatus);
// Verify management mode history
Assert.assertTrue(TestHelper.verify(() -> {
ControllerHistory tmpControllerHistory =
_accessor.getProperty(keyBuilder.controllerLeaderHistory());
List<String> tmpManagementHistory = tmpControllerHistory.getManagementModeHistory();
if (tmpManagementHistory == null || tmpManagementHistory.isEmpty()) {
return false;
}
// Should not have duplicate entries
if (tmpManagementHistory.size() > 1) {
return false;
}
String lastHistory = tmpManagementHistory.get(0);
return lastHistory.contains("MODE=" + ClusterManagementMode.Type.CLUSTER_FREEZE)
&& lastHistory.contains("STATUS=" + ClusterManagementMode.Status.COMPLETED)
&& lastHistory.contains("REASON=" + methodName);
}, TestHelper.WAIT_DURATION));
}
@Test(dependsOnMethods = "testEnableFreezeMode")
public void testNewLiveInstanceAddedWhenFrozen() throws Exception {
// Add a new live instance. Simulate an instance is rebooted and back to online
String newInstanceName = "localhost_" + (12918 + _numNodes + 1);
_gSetupTool.addInstancesToCluster(_clusterName, new String[]{newInstanceName});
MockParticipantManager newParticipant =
new MockParticipantManager(ZK_ADDR, _clusterName, newInstanceName);
newParticipant.syncStart();
// The new participant/live instance should be frozen by controller
verifyLiveInstanceStatus(new MockParticipantManager[]{newParticipant},
LiveInstance.LiveInstanceStatus.FROZEN);
newParticipant.syncStop();
}
// Simulates instance is restarted and the in-memory status is gone.
// When instance comes back alive, it'll reset state model, carry over
// and set current state to init state.
@Test(dependsOnMethods = "testNewLiveInstanceAddedWhenFrozen")
public void testRestartParticipantWhenFrozen() throws Exception {
String instanceName = _participants[1].getInstanceName();
PropertyKey.Builder keyBuilder = _accessor.keyBuilder();
List<CurrentState> originCurStates = _accessor
.getChildValues(keyBuilder.currentStates(instanceName, _participants[1].getSessionId()),
false);
String oldSession = _participants[1].getSessionId();
// Restart participants[1]
_participants[1].syncStop();
_participants[1] = new MockParticipantManager(ZK_ADDR, _participants[1].getClusterName(),
instanceName);
_participants[1].syncStart();
Assert.assertTrue(TestHelper.verify(() ->
_gZkClient.exists(keyBuilder.liveInstance(instanceName).getPath()),
TestHelper.WAIT_DURATION));
LiveInstance liveInstance = _accessor.getProperty(keyBuilder.liveInstance(instanceName));
// New live instance ephemeral node
Assert.assertEquals(liveInstance.getEphemeralOwner(), _participants[1].getSessionId());
// Status is frozen because controller sends a freeze message.
verifyLiveInstanceStatus(new MockParticipantManager[]{_participants[1]},
LiveInstance.LiveInstanceStatus.FROZEN);
// Old session current state is deleted because of current state carry-over
Assert.assertTrue(TestHelper.verify(
() -> !_gZkClient.exists(keyBuilder.currentStates(instanceName, oldSession).getPath()),
TestHelper.WAIT_DURATION));
// Current states are set to init states (OFFLINE)
List<CurrentState> curStates = _accessor
.getChildValues(keyBuilder.currentStates(instanceName, _participants[1].getSessionId()),
false);
Assert.assertEquals(curStates.size(), 1);
Assert.assertTrue(TestHelper.verify(() -> {
for (CurrentState cs : originCurStates) {
String stateModelDefRef = cs.getStateModelDefRef();
for (String partition : cs.getPartitionStateMap().keySet()) {
StateModelDefinition stateModelDef =
_accessor.getProperty(keyBuilder.stateModelDef(stateModelDefRef));
String initState = stateModelDef.getInitialState();
if (!initState.equals(curStates.get(0).getPartitionStateMap().get(partition))) {
return false;
}
}
}
return true;
}, TestHelper.WAIT_DURATION));
}
// Partition reset is allowed when cluster is frozen
@Test(dependsOnMethods = "testRestartParticipantWhenFrozen")
public void testResetPartitionWhenFrozen() throws Exception {
String instanceName = _participants[0].getInstanceName();
// Remove errTransition
_participants[0].setTransition(null);
_gSetupTool.getClusterManagementTool().resetPartition(_clusterName, instanceName, "TestDB0",
Collections.singletonList("TestDB0_0"));
// Error partition is reset: ERROR -> OFFLINE
Assert.assertTrue(TestHelper.verify(() -> {
CurrentState currentState = _accessor.getProperty(_accessor.keyBuilder()
.currentState(instanceName, _participants[0].getSessionId(), "TestDB0"));
return "OFFLINE".equals(currentState.getPartitionStateMap().get("TestDB0_0"));
}, TestHelper.WAIT_DURATION));
}
@Test(dependsOnMethods = "testResetPartitionWhenFrozen")
public void testCreateResourceWhenFrozen() {
// Add a new resource
_gSetupTool.addResourceToCluster(_clusterName, "TestDB1", 2, "MasterSlave");
_gSetupTool.rebalanceStorageCluster(_clusterName, "TestDB1", 3);
// TestDB1 external view is empty
TestHelper.verifyWithTimeout("verifyEmptyCurStateAndExtView", 1000, _clusterName, "TestDB1",
TestHelper.setOf("localhost_12918", "localhost_12919", "localhost_12920"), ZK_ADDR);
}
@Test(dependsOnMethods = "testCreateResourceWhenFrozen")
public void testUnfreezeCluster() throws Exception {
String methodName = TestHelper.getTestMethodName();
// Unfreeze cluster
ClusterManagementModeRequest request = ClusterManagementModeRequest.newBuilder()
.withClusterName(_clusterName)
.withMode(ClusterManagementMode.Type.NORMAL)
.withReason(methodName)
.build();
_gSetupTool.getClusterManagementTool().setClusterManagementMode(request);
verifyLiveInstanceStatus(_participants, LiveInstance.LiveInstanceStatus.NORMAL);
ClusterStatus expectedClusterStatus = new ClusterStatus();
expectedClusterStatus.setManagementMode(ClusterManagementMode.Type.NORMAL);
expectedClusterStatus.setManagementModeStatus(ClusterManagementMode.Status.COMPLETED);
verifyClusterStatus(expectedClusterStatus);
// Verify management mode history: NORMAL + COMPLETED
Assert.assertTrue(TestHelper.verify(() -> {
ControllerHistory history =
_accessor.getProperty(_accessor.keyBuilder().controllerLeaderHistory());
List<String> managementHistory = history.getManagementModeHistory();
if (managementHistory == null || managementHistory.isEmpty()) {
return false;
}
String lastHistory = managementHistory.get(managementHistory.size() - 1);
return lastHistory.contains("MODE=" + ClusterManagementMode.Type.NORMAL)
&& lastHistory.contains("STATUS=" + ClusterManagementMode.Status.COMPLETED);
}, TestHelper.WAIT_DURATION));
// Verify cluster's normal rebalance ability after unfrozen.
Assert.assertTrue(ClusterStateVerifier.verifyByZkCallback(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName)));
}
private void verifyLiveInstanceStatus(MockParticipantManager[] participants,
LiveInstance.LiveInstanceStatus status) throws Exception {
final PropertyKey.Builder keyBuilder = _accessor.keyBuilder();
Assert.assertTrue(TestHelper.verify(() -> {
for (MockParticipantManager participant : participants) {
String instanceName = participant.getInstanceName();
LiveInstance liveInstance = _accessor.getProperty(keyBuilder.liveInstance(instanceName));
if (status != liveInstance.getStatus()) {
return false;
}
}
return true;
}, TestHelper.WAIT_DURATION));
}
private void verifyClusterStatus(ClusterStatus expectedMode) throws Exception {
final PropertyKey statusPropertyKey = _accessor.keyBuilder().clusterStatus();
TestHelper.verify(() -> {
ClusterStatus clusterStatus = _accessor.getProperty(statusPropertyKey);
return clusterStatus != null
&& expectedMode.getManagementMode().equals(clusterStatus.getManagementMode())
&& expectedMode.getManagementModeStatus().equals(clusterStatus.getManagementModeStatus());
}, TestHelper.WAIT_DURATION);
}
private static class BlockingTransition extends MockTransition {
private static final Logger LOG = LoggerFactory.getLogger(BlockingTransition.class);
private final CountDownLatch _countDownLatch;
private BlockingTransition(CountDownLatch countDownLatch) {
_countDownLatch = countDownLatch;
}
@Override
public void doTransition(Message message, NotificationContext context)
throws InterruptedException {
LOG.info("Transition is blocked");
_countDownLatch.await();
LOG.info("Transition is completed");
}
}
}
| 9,576 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestRedundantDroppedMessage.java
|
package org.apache.helix.integration.controller;
/*
* 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.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
import org.apache.helix.controller.stages.AttributeName;
import org.apache.helix.controller.stages.BestPossibleStateCalcStage;
import org.apache.helix.controller.stages.ClusterEvent;
import org.apache.helix.controller.stages.ClusterEventType;
import org.apache.helix.controller.stages.CurrentStateComputationStage;
import org.apache.helix.controller.stages.IntermediateStateCalcStage;
import org.apache.helix.controller.stages.MessageGenerationPhase;
import org.apache.helix.controller.stages.MessageOutput;
import org.apache.helix.controller.stages.MessageSelectionStage;
import org.apache.helix.controller.stages.ResourceComputationStage;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.Partition;
import org.apache.helix.task.TaskSynchronizedTestBase;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestRedundantDroppedMessage extends TaskSynchronizedTestBase {
@BeforeClass
public void beforeClass() throws Exception {
_numNodes = 2;
_numReplicas = 1;
_numDbs = 1;
_numPartitions = 1;
super.beforeClass();
}
@Test
public void testNoRedundantDropMessage() throws Exception {
String resourceName = "TEST_RESOURCE";
_gSetupTool.getClusterManagementTool().addResource(CLUSTER_NAME, resourceName, 1, "MasterSlave",
IdealState.RebalanceMode.CUSTOMIZED.name());
String partitionName = "P_0";
ClusterEvent event = new ClusterEvent(CLUSTER_NAME, ClusterEventType.Unknown, "ID");
ResourceControllerDataProvider cache = new ResourceControllerDataProvider(CLUSTER_NAME);
cache.refresh(_manager.getHelixDataAccessor());
IdealState idealState = cache.getIdealState(resourceName);
idealState.setReplicas("2");
Map<String, String> stateMap = new HashMap<>();
stateMap.put(_participants[0].getInstanceName(), "SLAVE");
stateMap.put(_participants[1].getInstanceName(), "DROPPED");
idealState.setInstanceStateMap(partitionName, stateMap);
cache.setIdealStates(Arrays.asList(idealState));
cache.setCachedIdealMapping(idealState.getResourceName(), idealState.getRecord());
event.addAttribute(AttributeName.ControllerDataProvider.name(), cache);
event.addAttribute(AttributeName.helixmanager.name(), _manager);
runStage(event, new ResourceComputationStage());
runStage(event, new CurrentStateComputationStage());
runStage(event, new BestPossibleStateCalcStage());
Assert.assertEquals(cache.getCachedIdealMapping().size(), 1);
runStage(event, new MessageGenerationPhase());
runStage(event, new MessageSelectionStage());
runStage(event, new IntermediateStateCalcStage());
MessageOutput messageOutput = event.getAttribute(AttributeName.MESSAGES_SELECTED.name());
Assert
.assertEquals(messageOutput.getMessages(resourceName, new Partition(partitionName)).size(),
1);
Assert.assertEquals(cache.getCachedIdealMapping().size(), 0);
}
}
| 9,577 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestControllerLiveLock.java
|
package org.apache.helix.integration.controller;
/*
* 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 java.util.Map;
import java.util.Random;
import org.apache.helix.BaseDataAccessor;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkUnitTestBase;
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.ExternalView;
import org.apache.helix.model.IdealState.RebalanceMode;
import org.apache.helix.tools.ClusterStateVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* This is for testing Helix controller livelock @see Helix-541
* The test has a high probability to reproduce the problem
*/
public class TestControllerLiveLock extends ZkUnitTestBase {
private static final Logger LOG = LoggerFactory.getLogger(TestControllerLiveLock.class);
@Test
public void test() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
int n = 12;
final int p = 256;
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
final HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
final PropertyKey.Builder keyBuilder = accessor.keyBuilder();
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
p, // partitions per resource
n, // number of nodes
1, // replicas
"LeaderStandby", RebalanceMode.FULL_AUTO, true); // do rebalance
enablePersistBestPossibleAssignment(_gZkClient, clusterName, true);
// start participants
Random random = new Random();
MockParticipantManager[] participants = new MockParticipantManager[n];
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
Thread.sleep(Math.abs(random.nextInt()) % 500 + 500);
}
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller_0");
controller.syncStart();
BestPossibleExternalViewVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
boolean result = verifier.verifyByPolling();
Assert.assertTrue(result);
// make sure all partitions are assigned and no partitions is assigned to STANDBY state
result = TestHelper.verify(new TestHelper.Verifier() {
@Override
public boolean verify() throws Exception {
ExternalView extView = accessor.getProperty(keyBuilder.externalView("TestDB0"));
for (int i = 0; i < p; i++) {
String partition = "TestDB0_" + i;
Map<String, String> map = extView.getRecord().getMapField(partition);
if (map == null || map.size() != 1) {
return false;
}
}
return true;
}
}, 10 * 1000);
if (!result) {
ExternalView extView = accessor.getProperty(keyBuilder.externalView("TestDB0"));
for (int i = 0; i < p; i++) {
String partition = "TestDB0_" + i;
Map<String, String> map = extView.getRecord().getMapField(partition);
if (map == null || map.size() != 1) {
LOG.error(partition + ": " + map);
}
}
}
Assert.assertTrue(result);
// clean up
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
TestHelper.dropCluster(clusterName, _gZkClient);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,578 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestClusterMaintenanceMode.java
|
package org.apache.helix.integration.controller;
/*
* 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.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.google.common.collect.ImmutableMap;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.controller.rebalancer.strategy.CrushEdRebalanceStrategy;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.integration.task.TaskTestBase;
import org.apache.helix.integration.task.WorkflowGenerator;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ControllerHistory;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.MaintenanceSignal;
import org.apache.helix.monitoring.mbeans.MonitorDomainNames;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.apache.helix.monitoring.mbeans.ClusterStatusMonitor.CLUSTER_DN_KEY;
public class TestClusterMaintenanceMode extends TaskTestBase {
private static final long TIMEOUT = 180 * 1000L;
private MockParticipantManager _newInstance;
private String newResourceAddedDuringMaintenanceMode =
String.format("%s_%s", WorkflowGenerator.DEFAULT_TGT_DB, 1);
private HelixDataAccessor _dataAccessor;
private PropertyKey.Builder _keyBuilder;
@BeforeClass
public void beforeClass() throws Exception {
_numDbs = 1;
_numNodes = 3;
_numReplicas = 3;
_numPartitions = 5;
super.beforeClass();
_dataAccessor = _manager.getHelixDataAccessor();
_keyBuilder = _dataAccessor.keyBuilder();
}
@AfterClass
public void afterClass() throws Exception {
if (_newInstance != null && _newInstance.isConnected()) {
_newInstance.syncStop();
}
super.afterClass();
}
@Test
public void testNotInMaintenanceMode() {
boolean isInMaintenanceMode =
_gSetupTool.getClusterManagementTool().isInMaintenanceMode(CLUSTER_NAME);
Assert.assertFalse(isInMaintenanceMode);
}
@Test(dependsOnMethods = "testNotInMaintenanceMode")
public void testInMaintenanceMode() {
_gSetupTool.getClusterManagementTool().enableMaintenanceMode(CLUSTER_NAME, true, TestHelper.getTestMethodName());
boolean isInMaintenanceMode = _gSetupTool.getClusterManagementTool().isInMaintenanceMode(CLUSTER_NAME);
Assert.assertTrue(isInMaintenanceMode);
}
@Test(dependsOnMethods = "testInMaintenanceMode")
public void testMaintenanceModeAddNewInstance() {
_gSetupTool.getClusterManagementTool().enableMaintenanceMode(CLUSTER_NAME, true, TestHelper.getTestMethodName());
ExternalView prevExternalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + 10);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, instanceName);
_newInstance = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
_newInstance.syncStart();
_gSetupTool.getClusterManagementTool().rebalance(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB,
3);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
ExternalView newExternalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
Assert.assertEquals(prevExternalView.getRecord().getMapFields(),
newExternalView.getRecord().getMapFields());
}
@Test(dependsOnMethods = "testMaintenanceModeAddNewInstance")
public void testMaintenanceModeAddNewResource() {
_gSetupTool.getClusterManagementTool().addResource(CLUSTER_NAME,
newResourceAddedDuringMaintenanceMode, 7, "MasterSlave",
IdealState.RebalanceMode.FULL_AUTO.name(), CrushEdRebalanceStrategy.class.getName());
_gSetupTool.getClusterManagementTool().rebalance(CLUSTER_NAME,
newResourceAddedDuringMaintenanceMode, 3);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
ExternalView externalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, newResourceAddedDuringMaintenanceMode);
Assert.assertNull(externalView);
}
@Test(dependsOnMethods = "testMaintenanceModeAddNewResource")
public void testMaintenanceModeInstanceDown() {
_participants[0].syncStop();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
ExternalView externalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
for (Map<String, String> stateMap : externalView.getRecord().getMapFields().values()) {
Assert.assertTrue(stateMap.values().contains("MASTER"));
}
}
@Test(dependsOnMethods = "testMaintenanceModeInstanceDown")
public void testMaintenanceModeInstanceBack() {
_participants[0] =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _participants[0].getInstanceName());
_participants[0].syncStart();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
ExternalView externalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
for (Map<String, String> stateMap : externalView.getRecord().getMapFields().values()) {
if (stateMap.containsKey(_participants[0].getInstanceName())) {
Assert.assertEquals(stateMap.get(_participants[0].getInstanceName()), "SLAVE");
}
}
}
@Test(dependsOnMethods = "testMaintenanceModeInstanceBack")
public void testExitMaintenanceModeNewResourceRecovery() {
_gSetupTool.getClusterManagementTool().enableMaintenanceMode(CLUSTER_NAME, false);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
ExternalView externalView = _gSetupTool.getClusterManagementTool()
.getResourceExternalView(CLUSTER_NAME, newResourceAddedDuringMaintenanceMode);
Assert.assertEquals(externalView.getRecord().getMapFields().size(), 7);
for (Map<String, String> stateMap : externalView.getRecord().getMapFields().values()) {
Assert.assertTrue(stateMap.values().contains("MASTER"));
}
}
/**
* Test that the auto-exit functionality works.
*/
@Test(dependsOnMethods = "testExitMaintenanceModeNewResourceRecovery")
public void testAutoExitMaintenanceMode() throws Exception {
// Set the config for auto-exiting maintenance mode
ClusterConfig clusterConfig = _manager.getConfigAccessor().getClusterConfig(CLUSTER_NAME);
clusterConfig.setMaxOfflineInstancesAllowed(2);
clusterConfig.setNumOfflineInstancesForAutoExit(1);
_manager.getConfigAccessor().setClusterConfig(CLUSTER_NAME, clusterConfig);
// Kill 3 instances
for (int i = 0; i < 3; i++) {
_participants[i].syncStop();
}
TestHelper.verify(() -> _dataAccessor.getChildNames(_keyBuilder.liveInstances()).size() == 0, 2000L);
// Check that the cluster is in maintenance
MaintenanceSignal maintenanceSignal = _dataAccessor.getProperty(_keyBuilder.maintenance());
Assert.assertNotNull(maintenanceSignal);
// Now bring up 2 instances
for (int i = 0; i < 2; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i);
_participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
_participants[i].syncStart();
}
TestHelper.verify(() -> _dataAccessor.getChildNames(_keyBuilder.liveInstances()).size() == 3, 2000L);
// Check that the cluster is no longer in maintenance (auto-recovered)
maintenanceSignal = _dataAccessor.getProperty(_keyBuilder.maintenance());
Assert.assertNull(maintenanceSignal);
}
@Test(dependsOnMethods = "testAutoExitMaintenanceMode")
public void testNoAutoExitWhenManuallyPutInMaintenance() throws Exception {
// Manually put the cluster in maintenance
_gSetupTool.getClusterManagementTool().manuallyEnableMaintenanceMode(CLUSTER_NAME, true, null,
null);
// Kill 2 instances, which makes it a total of 3 down instances
for (int i = 0; i < 2; i++) {
_participants[i].syncStop();
}
TestHelper.verify(() -> _dataAccessor.getChildNames(_keyBuilder.liveInstances()).size() == 0, 2000L);
// Now bring up all instances
for (int i = 0; i < 3; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i);
_participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
_participants[i].syncStart();
}
TestHelper.verify(() -> _dataAccessor.getChildNames(_keyBuilder.liveInstances()).size() == 3, 2000L);
// The cluster should still be in maintenance because it was enabled manually
MaintenanceSignal maintenanceSignal = _dataAccessor.getProperty(_keyBuilder.maintenance());
Assert.assertNotNull(maintenanceSignal);
}
/**
* Test that manual triggering of maintenance mode overrides auto-enabled maintenance.
* @throws InterruptedException
*/
@Test(dependsOnMethods = "testNoAutoExitWhenManuallyPutInMaintenance")
public void testManualEnablingOverridesAutoEnabling() throws Exception {
// Exit maintenance mode manually
_gSetupTool.getClusterManagementTool().manuallyEnableMaintenanceMode(CLUSTER_NAME, false, null,
null);
// Kill 3 instances, which would put cluster in maintenance automatically
for (int i = 0; i < 3; i++) {
_participants[i].syncStop();
}
TestHelper.verify(() -> _dataAccessor.getChildNames(_keyBuilder.liveInstances()).size() == 0, 2000L);
// Check that maintenance signal was triggered by Controller
MaintenanceSignal maintenanceSignal = _dataAccessor.getProperty(_keyBuilder.maintenance());
Assert.assertNotNull(maintenanceSignal);
Assert.assertEquals(maintenanceSignal.getTriggeringEntity(),
MaintenanceSignal.TriggeringEntity.CONTROLLER);
// Manually enable maintenance mode with customFields
Map<String, String> customFields = ImmutableMap.of("LDAP", "hulee", "JIRA", "HELIX-999",
"TRIGGERED_BY", "SHOULD NOT BE RECORDED");
_gSetupTool.getClusterManagementTool().manuallyEnableMaintenanceMode(CLUSTER_NAME, true, null,
customFields);
TestHelper.verify(() -> _dataAccessor.getProperty(_keyBuilder.maintenance()) != null, 2000L);
// Check that maintenance mode has successfully overwritten with the right TRIGGERED_BY field
maintenanceSignal = _dataAccessor.getProperty(_keyBuilder.maintenance());
Assert.assertEquals(maintenanceSignal.getTriggeringEntity(),
MaintenanceSignal.TriggeringEntity.USER);
for (Map.Entry<String, String> entry : customFields.entrySet()) {
if (entry.getKey().equals("TRIGGERED_BY")) {
Assert.assertEquals(maintenanceSignal.getRecord().getSimpleField(entry.getKey()), "USER");
} else {
Assert.assertEquals(maintenanceSignal.getRecord().getSimpleField(entry.getKey()),
entry.getValue());
}
}
}
/**
* Test that maxNumPartitionPerInstance still applies (if any Participant has more replicas than
* the threshold, the cluster should not auto-exit maintenance mode).
* @throws InterruptedException
*/
@Test(dependsOnMethods = "testManualEnablingOverridesAutoEnabling")
public void testMaxPartitionLimit() throws Exception {
// Manually exit maintenance mode
_gSetupTool.getClusterManagementTool().manuallyEnableMaintenanceMode(CLUSTER_NAME, false, null,
null);
TestHelper.verify(() -> _dataAccessor.getProperty(_keyBuilder.maintenance()) != null, 2000L);
// Since 3 instances are missing, the cluster should have gone back under maintenance
// automatically
MaintenanceSignal maintenanceSignal = _dataAccessor.getProperty(_keyBuilder.maintenance());
Assert.assertNotNull(maintenanceSignal);
Assert.assertEquals(maintenanceSignal.getTriggeringEntity(),
MaintenanceSignal.TriggeringEntity.CONTROLLER);
Assert.assertEquals(maintenanceSignal.getAutoTriggerReason(),
MaintenanceSignal.AutoTriggerReason.MAX_OFFLINE_INSTANCES_EXCEEDED);
// Bring up all instances
for (int i = 0; i < 3; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i);
_participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
_participants[i].syncStart();
}
TestHelper.verify(() -> _dataAccessor.getChildNames(_keyBuilder.liveInstances()).size() == 3, 2000L);
// Check that the cluster exited maintenance
maintenanceSignal = _dataAccessor.getProperty(_keyBuilder.maintenance());
Assert.assertNull(maintenanceSignal);
// Kill 3 instances, which would put cluster in maintenance automatically
for (int i = 0; i < 3; i++) {
_participants[i].syncStop();
}
TestHelper.verify(() -> _dataAccessor.getChildNames(_keyBuilder.liveInstances()).size() == 0, 2000L);
// Check that cluster is back under maintenance
maintenanceSignal = _dataAccessor.getProperty(_keyBuilder.maintenance());
Assert.assertNotNull(maintenanceSignal);
Assert.assertEquals(maintenanceSignal.getTriggeringEntity(),
MaintenanceSignal.TriggeringEntity.CONTROLLER);
Assert.assertEquals(maintenanceSignal.getAutoTriggerReason(),
MaintenanceSignal.AutoTriggerReason.MAX_OFFLINE_INSTANCES_EXCEEDED);
// Set the cluster config for auto-exiting maintenance mode
ClusterConfig clusterConfig = _manager.getConfigAccessor().getClusterConfig(CLUSTER_NAME);
// Setting MaxPartitionsPerInstance to 1 will prevent the cluster from exiting maintenance mode
// automatically because the instances currently have more than 1
clusterConfig.setMaxPartitionsPerInstance(1);
_manager.getConfigAccessor().setClusterConfig(CLUSTER_NAME, clusterConfig);
TestHelper.verify(
() -> ((ClusterConfig) _dataAccessor.getProperty(_keyBuilder.clusterConfig())).getMaxPartitionsPerInstance() == 1,
2000L);
// Now bring up all instances
for (int i = 0; i < 3; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + i);
_participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
_participants[i].syncStart();
}
TestHelper.verify(() -> _dataAccessor.getChildNames(_keyBuilder.liveInstances()).size() == 3, 2000L);
// Check that the cluster is still in maintenance (should not have auto-exited because it would
// fail the MaxPartitionsPerInstance check)
maintenanceSignal = _dataAccessor.getProperty(_keyBuilder.maintenance());
Assert.assertNotNull(maintenanceSignal);
Assert.assertEquals(maintenanceSignal.getTriggeringEntity(),
MaintenanceSignal.TriggeringEntity.CONTROLLER);
Assert.assertEquals(maintenanceSignal.getAutoTriggerReason(),
MaintenanceSignal.AutoTriggerReason.MAX_PARTITION_PER_INSTANCE_EXCEEDED);
// Check if failed rebalance counter is updated
boolean result = TestHelper.verify(() -> {
try {
Long value =
(Long) _server.getAttribute(getMbeanName(CLUSTER_NAME), "RebalanceFailureCounter");
return value != null && (value > 0);
} catch (Exception e) {
return false;
}
}, TIMEOUT);
Assert.assertTrue(result);
// Check failed continuous task rebalance counter is not updated
result = TestHelper.verify(() -> {
try {
Long value = (Long) _server
.getAttribute(getMbeanName(CLUSTER_NAME), "ContinuousTaskRebalanceFailureCount");
return value != null && (value == 0);
} catch (Exception e) {
return false;
}
}, TIMEOUT);
Assert.assertTrue(result);
// Check if failed continuous resource rebalance counter is updated
result = TestHelper.verify(() -> {
try {
Long value = (Long) _server
.getAttribute(getMbeanName(CLUSTER_NAME), "ContinuousResourceRebalanceFailureCount");
return value != null && (value > 0);
} catch (Exception e) {
return false;
}
}, TIMEOUT);
Assert.assertTrue(result);
}
private ObjectName getMbeanName(String clusterName) throws MalformedObjectNameException {
String clusterBeanName = String.format("%s=%s", CLUSTER_DN_KEY, clusterName);
return new ObjectName(
String.format("%s:%s", MonitorDomainNames.ClusterStatus.name(), clusterBeanName));
}
/**
* Test that the Controller correctly records maintenance history in various situations.
* @throws InterruptedException
*/
@Test(dependsOnMethods = "testMaxPartitionLimit")
public void testMaintenanceHistory() throws Exception {
// In maintenance mode, by controller, for MAX_PARTITION_PER_INSTANCE_EXCEEDED
ControllerHistory history = _dataAccessor.getProperty(_keyBuilder.controllerLeaderHistory());
Map<String, String> lastHistoryEntry = convertStringToMap(
history.getMaintenanceHistoryList().get(history.getMaintenanceHistoryList().size() - 1));
// **The KV pairs are hard-coded in here for the ease of reading!**
Assert.assertEquals(lastHistoryEntry.get("OPERATION_TYPE"), "ENTER");
Assert.assertEquals(lastHistoryEntry.get("TRIGGERED_BY"), "CONTROLLER");
Assert.assertEquals(lastHistoryEntry.get("AUTO_TRIGGER_REASON"),
"MAX_PARTITION_PER_INSTANCE_EXCEEDED");
// Remove the maxPartitionPerInstance config
ClusterConfig clusterConfig = _manager.getConfigAccessor().getClusterConfig(CLUSTER_NAME);
clusterConfig.setMaxPartitionsPerInstance(-1);
_manager.getConfigAccessor().setClusterConfig(CLUSTER_NAME, clusterConfig);
TestHelper.verify(() -> _dataAccessor.getProperty(_keyBuilder.maintenance()) == null, 2000L);
// Now check that the cluster exited maintenance
// EXIT, CONTROLLER, for MAX_PARTITION_PER_INSTANCE_EXCEEDED
history = _dataAccessor.getProperty(_keyBuilder.controllerLeaderHistory());
lastHistoryEntry = convertStringToMap(
history.getMaintenanceHistoryList().get(history.getMaintenanceHistoryList().size() - 1));
Assert.assertEquals(lastHistoryEntry.get("OPERATION_TYPE"), "EXIT");
Assert.assertEquals(lastHistoryEntry.get("TRIGGERED_BY"), "CONTROLLER");
Assert.assertEquals(lastHistoryEntry.get("AUTO_TRIGGER_REASON"),
"MAX_PARTITION_PER_INSTANCE_EXCEEDED");
// Manually put the cluster in maintenance with a custom field
Map<String, String> customFieldMap = ImmutableMap.of("k1", "v1", "k2", "v2");
_gSetupTool.getClusterManagementTool()
.manuallyEnableMaintenanceMode(CLUSTER_NAME, true, TestHelper.getTestMethodName(), customFieldMap);
TestHelper.verify(() -> _dataAccessor.getProperty(_keyBuilder.maintenance()) != null, 2000L);
// ENTER, USER, for reason TEST, no internalReason
history = _dataAccessor.getProperty(_keyBuilder.controllerLeaderHistory());
lastHistoryEntry =
convertStringToMap(history.getMaintenanceHistoryList().get(history.getMaintenanceHistoryList().size() - 1));
Assert.assertEquals(lastHistoryEntry.get("OPERATION_TYPE"), "ENTER");
Assert.assertEquals(lastHistoryEntry.get("TRIGGERED_BY"), "USER");
Assert.assertEquals(lastHistoryEntry.get("REASON"), TestHelper.getTestMethodName());
Assert.assertNull(lastHistoryEntry.get("AUTO_TRIGGER_REASON"));
}
/**
* Convert a String representation of a Map into a Map object for verification purposes.
* @param value
* @return
*/
private static Map<String, String> convertStringToMap(String value) throws IOException {
return new ObjectMapper().readValue(value,
TypeFactory.defaultInstance().constructMapType(HashMap.class, String.class, String.class));
}
}
| 9,579 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestSkipBestPossibleCalculation.java
|
package org.apache.helix.integration.controller;
/*
* 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 org.apache.helix.HelixConstants;
import org.apache.helix.TestHelper;
import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
import org.apache.helix.controller.stages.AttributeName;
import org.apache.helix.controller.stages.BestPossibleStateCalcStage;
import org.apache.helix.controller.stages.ClusterEvent;
import org.apache.helix.controller.stages.ClusterEventType;
import org.apache.helix.controller.stages.CurrentStateComputationStage;
import org.apache.helix.controller.stages.ResourceComputationStage;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.model.IdealState;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestSkipBestPossibleCalculation extends ZkStandAloneCMTestBase {
@Test()
public void test() throws Exception {
int numResource = 5;
for (int i = 0; i < numResource; i++) {
String dbName = "TestDB_" + i;
_gSetupTool.addResourceToCluster(CLUSTER_NAME, dbName, _PARTITIONS, STATE_MODEL,
IdealState.RebalanceMode.CUSTOMIZED.name());
_gSetupTool.rebalanceResource(CLUSTER_NAME, dbName, 3);
}
ResourceControllerDataProvider cache =
new ResourceControllerDataProvider("CLUSTER_" + TestHelper.getTestClassName());
cache.refresh(_manager.getHelixDataAccessor());
ClusterEvent event = new ClusterEvent(CLUSTER_NAME, ClusterEventType.IdealStateChange);
event.addAttribute(AttributeName.ControllerDataProvider.name(), cache);
runStage(_manager, event, new ResourceComputationStage());
runStage(_manager, event, new CurrentStateComputationStage());
Assert.assertEquals(cache.getCachedResourceAssignments().size(), 0);
runStage(_manager, event, new BestPossibleStateCalcStage());
Assert.assertEquals(cache.getCachedResourceAssignments().size(), numResource);
cache.notifyDataChange(HelixConstants.ChangeType.INSTANCE_CONFIG);
cache.refresh(_manager.getHelixDataAccessor());
Assert.assertEquals(cache.getCachedResourceAssignments().size(), 0);
runStage(_manager, event, new BestPossibleStateCalcStage());
Assert.assertEquals(cache.getCachedResourceAssignments().size(), numResource);
cache.notifyDataChange(HelixConstants.ChangeType.IDEAL_STATE);
cache.refresh(_manager.getHelixDataAccessor());
Assert.assertEquals(cache.getCachedResourceAssignments().size(), 0);
runStage(_manager, event, new BestPossibleStateCalcStage());
Assert.assertEquals(cache.getCachedResourceAssignments().size(), numResource);
cache.notifyDataChange(HelixConstants.ChangeType.LIVE_INSTANCE);
cache.refresh(_manager.getHelixDataAccessor());
Assert.assertEquals(cache.getCachedResourceAssignments().size(), 0);
runStage(_manager, event, new BestPossibleStateCalcStage());
Assert.assertEquals(cache.getCachedResourceAssignments().size(), numResource);
cache.requireFullRefresh();
cache.refresh(_manager.getHelixDataAccessor());
Assert.assertEquals(cache.getCachedResourceAssignments().size(), 0);
runStage(_manager, event, new BestPossibleStateCalcStage());
Assert.assertEquals(cache.getCachedResourceAssignments().size(), numResource);
cache.notifyDataChange(HelixConstants.ChangeType.CURRENT_STATE);
cache.refresh(_manager.getHelixDataAccessor());
Assert.assertEquals(cache.getCachedResourceAssignments().size(), numResource);
cache.notifyDataChange(HelixConstants.ChangeType.RESOURCE_CONFIG);
cache.refresh(_manager.getHelixDataAccessor());
Assert.assertEquals(cache.getCachedResourceAssignments().size(), 0);
}
}
| 9,580 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestOfflineNodeTimeoutDuringMaintenanceMode.java
|
package org.apache.helix.integration.controller;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
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.model.ClusterConfig;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.ParticipantHistory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestOfflineNodeTimeoutDuringMaintenanceMode extends ZkTestBase {
private static final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + TestHelper.getTestClassName();
private HelixDataAccessor _helixDataAccessor;
private PropertyKey.Builder _keyBuilder;
private ClusterControllerManager _controller;
@BeforeClass
@Override
public void beforeClass() throws Exception {
super.beforeClass();
_gSetupTool.addCluster(CLUSTER_NAME, true);
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
_helixDataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
_keyBuilder = _helixDataAccessor.keyBuilder();
}
@Test
public void testOfflineNodeTimeoutDuringMaintenanceMode() throws Exception {
// 1st case: an offline node that comes live during maintenance, should be timed-out
String instance1 = "Instance1";
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, instance1);
MockParticipantManager participant1 =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instance1);
participant1.syncStart();
// 2nd case: an offline node that comes live before maintenance, shouldn't be timed-out
String instance2 = "Instance2";
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, instance2);
MockParticipantManager participant2 =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instance2);
participant2.syncStart();
// New instance case: a new node that comes live after maintenance, shouldn't be timed-out
String newInstance = "NewInstance";
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, newInstance);
String dbName = "TestDB_1";
_gSetupTool.addResourceToCluster(CLUSTER_NAME, dbName, 5, "MasterSlave");
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, 3);
// Set timeout window to be 0 millisecond, causing any node that goes offline to time out
ClusterConfig clusterConfig = _helixDataAccessor.getProperty(_keyBuilder.clusterConfig());
clusterConfig.setOfflineNodeTimeOutForMaintenanceMode(0L);
_helixDataAccessor.setProperty(_keyBuilder.clusterConfig(), clusterConfig);
Assert.assertNotNull(_helixDataAccessor.getProperty(_keyBuilder.liveInstance(instance1)));
Assert.assertNotNull(_helixDataAccessor.getProperty(_keyBuilder.liveInstance(instance2)));
// Start and stop the instance, simulating a node offline situation
participant1.syncStop();
Assert.assertNull(_helixDataAccessor.getProperty(_keyBuilder.liveInstance(instance1)));
participant2.syncStop();
Assert.assertNull(_helixDataAccessor.getProperty(_keyBuilder.liveInstance(instance2)));
// Enable maintenance mode; restart instance2 before and instance 1 after
participant2 = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instance2);
participant2.syncStart();
Assert.assertNotNull(_helixDataAccessor.getProperty(_keyBuilder.liveInstance(instance2)));
_gSetupTool.getClusterManagementTool()
.manuallyEnableMaintenanceMode(CLUSTER_NAME, true, "Test", Collections.emptyMap());
participant1 = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instance1);
participant1.syncStart();
Assert.assertNotNull(_helixDataAccessor.getProperty(_keyBuilder.liveInstance(instance1)));
MockParticipantManager newParticipant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, newInstance);
newParticipant.syncStart();
// Only includes instance 2
ExternalView externalView = _helixDataAccessor.getProperty(_keyBuilder.externalView(dbName));
for (String partition : externalView.getPartitionSet()) {
Assert.assertEquals(externalView.getStateMap(partition).keySet(), Collections.singletonList(instance2));
}
// History wise, all instances should still be treated as online
ParticipantHistory history1 =
_helixDataAccessor.getProperty(_keyBuilder.participantHistory(instance1));
Assert.assertEquals(history1.getLastOfflineTime(), ParticipantHistory.ONLINE);
ParticipantHistory history2 =
_helixDataAccessor.getProperty(_keyBuilder.participantHistory(instance2));
Assert.assertEquals(history2.getLastOfflineTime(), ParticipantHistory.ONLINE);
// Exit the maintenance mode, and the instance should be included in liveInstanceCache again
_gSetupTool.getClusterManagementTool()
.manuallyEnableMaintenanceMode(CLUSTER_NAME, false, "Test", Collections.emptyMap());
// Include every instance
final ExternalView newExternalView = _helixDataAccessor.getProperty(_keyBuilder.externalView(dbName));
Set<String> allInstances = new HashSet<>();
allInstances.add(instance1);
allInstances.add(instance2);
allInstances.add(newInstance);
for (String partition : externalView.getPartitionSet()) {
TestHelper.verify(() -> newExternalView.getStateMap(partition).keySet().equals(allInstances),
12000);
}
}
@Test(dependsOnMethods = "testOfflineNodeTimeoutDuringMaintenanceMode")
// Testing with mocked timestamps, instead of full integration
public void testOfflineNodeTimeoutDuringMaintenanceModeTimestampsMock()
throws InterruptedException {
// Timeout window is set as 10 milliseconds. Let maintenance mode start time be denoted as T
List<String> instanceList = new ArrayList<>();
// 3rd case:
// Online: [T-10, T+5, T+20]
// Offline: [T+1, T+9]
// Expected: Timed-out
String instance3 = "Instance3";
instanceList.add(instance3);
// 4th case:
// Online: [T-10, T+12]
// Offline: [T+1, T+6]
// Expected: Timed-out
String instance4 = "Instance4";
instanceList.add(instance4);
// 5th case:
// Online: [T-10, T+6, T+12]
// Offline: [T+1]
// Expected: Not timed-out
String instance5 = "Instance5";
instanceList.add(instance5);
// 6th case: (X denoting malformed timestamps)
// Online: [T-10, X, X, T+12]
// Offline: [T+1, X, X]
// Expected: Timed-out
String instance6 = "Instance6";
instanceList.add(instance6);
// 7th case: (X denoting malformed timestamps)
// Online: [T-10, T+1, X, X]
// Offline: [X, X, T+10]
// Expected: Timed-out (by waiting until current time to be at least T+20)
String instance7 = "Instance7";
instanceList.add(instance7);
// 8th case:
// Online: [T-10, T+3, T+4, T+8, T+9, T+10]
// Offline: [T+1, T+2, T+5, T+6, T+7]
// Expected: Not timed-out
String instance8 = "Instance8";
instanceList.add(instance8);
ClusterConfig clusterConfig = _helixDataAccessor.getProperty(_keyBuilder.clusterConfig());
clusterConfig.setOfflineNodeTimeOutForMaintenanceMode(10L);
_helixDataAccessor.setProperty(_keyBuilder.clusterConfig(), clusterConfig);
for (String instance : instanceList) {
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, instance);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instance);
participant.syncStart();
}
_gSetupTool.getClusterManagementTool()
.manuallyEnableMaintenanceMode(CLUSTER_NAME, true, "Test", Collections.emptyMap());
long currentTime = System.currentTimeMillis();
addTimestampsToParticipantHistory(instance3, new long[]{currentTime + 5, currentTime + 20},
new long[]{currentTime + 1, currentTime + 9});
addTimestampsToParticipantHistory(instance4, new long[]{currentTime + 12},
new long[]{currentTime + 1, currentTime + 6});
addTimestampsToParticipantHistory(instance5, new long[]{currentTime + 6, currentTime + 12},
new long[]{currentTime + 1});
addTimestampsToParticipantHistory(instance6, new long[]{-1, -1, currentTime + 12},
new long[]{currentTime + 1, -1, -1});
addTimestampsToParticipantHistory(instance7, new long[]{currentTime + 1, -1, -1},
new long[]{-1, -1, currentTime + 10});
addTimestampsToParticipantHistory(instance8, new long[]{
currentTime + 3, currentTime + 4, currentTime + 8, currentTime + 9, currentTime + 10},
new long[]{
currentTime + 1, currentTime + 2, currentTime + 5, currentTime + 6, currentTime + 7});
// Sleep to make instance7 timed out. This ensures the refresh time to be at least
// currentTime + 10 (last offline timestamp) + 10 (timeout window).
long timeToSleep = currentTime + 20 - System.currentTimeMillis();
if (timeToSleep > 0) {
Thread.sleep(timeToSleep);
}
ResourceControllerDataProvider resourceControllerDataProvider =
new ResourceControllerDataProvider(CLUSTER_NAME);
resourceControllerDataProvider.refresh(_helixDataAccessor);
Assert
.assertFalse(resourceControllerDataProvider.getLiveInstances().containsKey(instance3));
Assert
.assertFalse(resourceControllerDataProvider.getLiveInstances().containsKey(instance4));
Assert.assertTrue(resourceControllerDataProvider.getLiveInstances().containsKey(instance5));
Assert
.assertFalse(resourceControllerDataProvider.getLiveInstances().containsKey(instance6));
Assert
.assertFalse(resourceControllerDataProvider.getLiveInstances().containsKey(instance7));
Assert.assertTrue(resourceControllerDataProvider.getLiveInstances().containsKey(instance8));
}
/**
* Add timestamps to an instance's ParticipantHistory; pass -1 to insert malformed strings instead
*/
private void addTimestampsToParticipantHistory(String instanceName, long[] onlineTimestamps,
long[] offlineTimestamps) {
ParticipantHistory history =
_helixDataAccessor.getProperty(_keyBuilder.participantHistory(instanceName));
List<String> historyList = history.getRecord().getListField("HISTORY");
Map<String, String> historySample =
ParticipantHistory.sessionHistoryStringToMap(historyList.get(0));
for (long onlineTimestamp : onlineTimestamps) {
if (onlineTimestamp >= 0) {
historySample.put("TIME", Long.toString(onlineTimestamp));
} else {
historySample.put("TIME", "MalformedString");
}
historyList.add(historySample.toString());
}
List<String> offlineList = history.getRecord().getListField("OFFLINE");
if (offlineList == null) {
offlineList = new ArrayList<>();
history.getRecord().setListField("OFFLINE", offlineList);
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
for (long offlineTimestamp : offlineTimestamps) {
if (offlineTimestamp >= 0) {
offlineList.add(df.format(new Date(offlineTimestamp)));
} else {
offlineList.add("MalformedString");
}
}
_helixDataAccessor.setProperty(_keyBuilder.participantHistory(instanceName), history);
}
}
| 9,581 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestTargetExternalView.java
|
package org.apache.helix.integration.controller;
/*
* 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.List;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.TestHelper;
import org.apache.helix.integration.task.TaskTestBase;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestTargetExternalView extends TaskTestBase {
private ConfigAccessor _configAccessor;
private HelixDataAccessor _accessor;
@BeforeClass
public void beforeClass() throws Exception {
_numDbs = 3;
_numPartitions = 8;
_numNodes = 4;
_numReplicas = 2;
super.beforeClass();
_configAccessor = new ConfigAccessor(_gZkClient);
_accessor = _manager.getHelixDataAccessor();
}
@Test
public void testTargetExternalViewEnable() throws InterruptedException {
// Before enable target external view
Assert.assertFalse(_gZkClient.exists(_accessor.keyBuilder().targetExternalViews().getPath()));
ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
clusterConfig.enableTargetExternalView(true);
clusterConfig.setPersistIntermediateAssignment(true);
_configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
_gSetupTool.getClusterManagementTool().rebalance(CLUSTER_NAME, _testDbs.get(0), 3);
ZkHelixClusterVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
Assert.assertEquals(
_accessor.getChildNames(_accessor.keyBuilder().targetExternalViews()).size(), 3);
List<ExternalView> targetExternalViews =
_accessor.getChildValues(_accessor.keyBuilder().externalViews(), true);
List<IdealState> idealStates =
_accessor.getChildValues(_accessor.keyBuilder().idealStates(), true);
for (int i = 0; i < idealStates.size(); i++) {
Assert.assertEquals(targetExternalViews.get(i).getRecord().getMapFields(),
idealStates.get(i).getRecord().getMapFields());
Assert.assertEquals(targetExternalViews.get(i).getRecord().getListFields(),
idealStates.get(i).getRecord().getListFields());
}
// Disable one instance to see whether the target external views changes.
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
_participants[0].getInstanceName(), false);
Assert.assertTrue(verifier.verifyByPolling());
Thread.sleep(1000);
targetExternalViews = _accessor.getChildValues(_accessor.keyBuilder().externalViews(), true);
idealStates = _accessor.getChildValues(_accessor.keyBuilder().idealStates(), true);
for (int i = 0; i < idealStates.size(); i++) {
Assert.assertEquals(targetExternalViews.get(i).getRecord().getMapFields(),
idealStates.get(i).getRecord().getMapFields());
Assert.assertEquals(targetExternalViews.get(i).getRecord().getListFields(),
idealStates.get(i).getRecord().getListFields());
}
}
}
| 9,582 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestControllerDataProviderSelectiveUpdate.java
|
package org.apache.helix.integration.controller;
/*
* 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 org.apache.helix.HelixConstants;
import org.apache.helix.PropertyType;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
import org.apache.helix.integration.task.WorkflowGenerator;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.mock.MockZkHelixDataAccessor;
import org.apache.helix.task.JobConfig;
import org.apache.helix.task.TaskDriver;
import org.apache.helix.task.Workflow;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestControllerDataProviderSelectiveUpdate extends ZkStandAloneCMTestBase {
@Test()
public void testUpdateOnNotification() throws Exception {
MockZkHelixDataAccessor accessor =
new MockZkHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
ResourceControllerDataProvider cache =
new ResourceControllerDataProvider("CLUSTER_" + TestHelper.getTestClassName());
cache.refresh(accessor);
Assert.assertEquals(accessor.getReadCount(PropertyType.IDEALSTATES), 1);
Assert.assertEquals(accessor.getReadCount(PropertyType.EXTERNALVIEW), 1);
Assert.assertEquals(accessor.getReadCount(PropertyType.LIVEINSTANCES), NODE_NR);
Assert.assertEquals(accessor.getReadCount(PropertyType.CURRENTSTATES), NODE_NR);
Assert.assertEquals(accessor.getReadCount(PropertyType.CONFIGS), NODE_NR + 2);
accessor.clearReadCounters();
// refresh again should read nothing
cache.refresh(accessor);
Assert.assertEquals(accessor.getReadCount(PropertyType.IDEALSTATES), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.EXTERNALVIEW), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.LIVEINSTANCES), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.CURRENTSTATES), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.CONFIGS), 0);
accessor.clearReadCounters();
// refresh again should read nothing as ideal state is same
cache.notifyDataChange(HelixConstants.ChangeType.IDEAL_STATE);
cache.refresh(accessor);
Assert.assertEquals(accessor.getReadCount(PropertyType.IDEALSTATES), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.EXTERNALVIEW), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.LIVEINSTANCES), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.CURRENTSTATES), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.CONFIGS), 0);
accessor.clearReadCounters();
cache.notifyDataChange(HelixConstants.ChangeType.LIVE_INSTANCE);
cache.refresh(accessor);
Assert.assertEquals(accessor.getReadCount(PropertyType.IDEALSTATES), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.EXTERNALVIEW), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.LIVEINSTANCES), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.CURRENTSTATES), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.CONFIGS), 0);
}
@Test(dependsOnMethods = {"testUpdateOnNotification"})
public void testSelectiveUpdates() throws Exception {
MockZkHelixDataAccessor accessor =
new MockZkHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
ResourceControllerDataProvider cache =
new ResourceControllerDataProvider("CLUSTER_" + TestHelper.getTestClassName());
cache.refresh(accessor);
Assert.assertEquals(accessor.getReadCount(PropertyType.IDEALSTATES), 1);
Assert.assertEquals(accessor.getReadCount(PropertyType.EXTERNALVIEW), 1);
Assert.assertEquals(accessor.getReadCount(PropertyType.LIVEINSTANCES), NODE_NR);
Assert.assertEquals(accessor.getReadCount(PropertyType.CURRENTSTATES), NODE_NR);
Assert.assertEquals(accessor.getReadCount(PropertyType.CONFIGS), NODE_NR + 2);
accessor.clearReadCounters();
// refresh again should read nothing
cache.refresh(accessor);
Assert.assertEquals(accessor.getReadCount(PropertyType.IDEALSTATES), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.EXTERNALVIEW), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.LIVEINSTANCES), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.CURRENTSTATES), 0);
Assert.assertEquals(accessor.getReadCount(PropertyType.CONFIGS), 0);
// add a new resource
_gSetupTool.addResourceToCluster(CLUSTER_NAME, "TestDB_1", _PARTITIONS, STATE_MODEL);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "TestDB_1", _replica);
Thread.sleep(100);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
accessor.clearReadCounters();
// refresh again should read only new current states and new idealstate
cache.notifyDataChange(HelixConstants.ChangeType.IDEAL_STATE);
cache.refresh(accessor);
Assert.assertEquals(accessor.getReadCount(PropertyType.CURRENTSTATES), NODE_NR);
Assert.assertEquals(accessor.getReadCount(PropertyType.IDEALSTATES), 1);
Assert.assertEquals(accessor.getReadCount(PropertyType.EXTERNALVIEW), 0);
// Add more resources
accessor.clearReadCounters();
_gSetupTool.addResourceToCluster(CLUSTER_NAME, "TestDB_2", _PARTITIONS, STATE_MODEL);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "TestDB_2", _replica);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, "TestDB_3", _PARTITIONS, STATE_MODEL);
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "TestDB_3", _replica);
// Totally four resources. Two of them are newly added.
cache.notifyDataChange(HelixConstants.ChangeType.IDEAL_STATE);
cache.refresh(accessor);
Assert.assertEquals(accessor.getReadCount(PropertyType.IDEALSTATES), 2);
Assert.assertEquals(accessor.getReadCount(PropertyType.EXTERNALVIEW), 0);
// Test WorkflowConfig/JobConfigs
TaskDriver driver = new TaskDriver(_manager);
Workflow.Builder workflow = WorkflowGenerator.generateSingleJobWorkflowBuilder("Job",
new JobConfig.Builder().setCommand("ReIndex").setTargetResource("TestDB_2"));
driver.start(workflow.build());
Thread.sleep(100);
accessor.clearReadCounters();
cache.notifyDataChange(HelixConstants.ChangeType.RESOURCE_CONFIG);
cache.refresh(accessor);
// 2 Resource Config Changes
Assert.assertEquals(accessor.getReadCount(PropertyType.CONFIGS), 2);
}
}
| 9,583 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestControllerLeadershipChange.java
|
package org.apache.helix.integration.controller;
/*
* 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.lang.management.ManagementFactory;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.helix.AccessOption;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixException;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.PropertyPathBuilder;
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.CallbackHandler;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.monitoring.mbeans.MonitorDomainNames;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.apache.helix.zookeeper.api.client.RealmAwareZkClient;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.zookeeper.zkclient.DataUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Integration test on controller leadership on several phases given the test cluster:
* 1. When a standalone controller becomes the leader
* 2. When a standalone leader relinquishes the leadership
* 3. When the leader node relinquishes the leadership and the other controller takes it over
*/
public class TestControllerLeadershipChange extends ZkTestBase {
private static final Logger LOG = LoggerFactory.getLogger(TestControllerLeadershipChange.class);
private final String CLASS_NAME = getShortClassName();
private final String CLUSTER_NAME = "TestCluster-" + CLASS_NAME;
@BeforeClass
public void beforeClass() throws Exception {
super.beforeClass();
_gSetupTool.addCluster(CLUSTER_NAME, true);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, "TestInstance");
_gSetupTool.addResourceToCluster(CLUSTER_NAME, "TestResource", 10, "MasterSlave");
}
@AfterClass
public void afterClass() {
deleteCluster(CLUSTER_NAME);
}
@Test
public void testControllerCleanUpClusterConfig() {
ZkBaseDataAccessor baseDataAccessor = new ZkBaseDataAccessor(_gZkClient);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, "DISABLED_Instance");
_gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, "DISABLED_Instance", false);
baseDataAccessor.update(PropertyPathBuilder.clusterConfig(CLUSTER_NAME),new DataUpdater<ZNRecord>() {
@Override
public ZNRecord update(ZNRecord currentData) {
if (currentData == null) {
throw new HelixException("Cluster: " + CLUSTER_NAME + ": cluster config is null");
}
ClusterConfig clusterConfig = new ClusterConfig(currentData);
Map<String, String> disabledInstances = new TreeMap<>(clusterConfig.getDisabledInstances());
disabledInstances.put("DISABLED_Instance", "HELIX_ENABLED_DISABLE_TIMESTAMP=1652338376608");
clusterConfig.setDisabledInstances(disabledInstances);
return clusterConfig.getRecord();
}
}, AccessOption.PERSISTENT);
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, "TestController");
controller.syncStart();
verifyControllerIsLeader(controller);
// Create cluster verifier
ZkHelixClusterVerifier clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
// Wait for rebalanced
Assert.assertTrue(clusterVerifier.verifyByPolling());
ZKHelixDataAccessor helixDataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, baseDataAccessor);
ClusterConfig cls = helixDataAccessor.getProperty(helixDataAccessor.keyBuilder().clusterConfig());
Assert.assertFalse(cls.getRecord().getMapFields()
.containsKey(ClusterConfig.ClusterConfigProperty.DISABLED_INSTANCES.name()));
controller.syncStop();
verifyControllerIsNotLeader(controller);
verifyZKDisconnected(controller);
}
@Test
public void testControllerConnectThenDisconnect() {
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, "TestController");
long start = System.currentTimeMillis();
controller.syncStart();
verifyControllerIsLeader(controller);
LOG.info(System.currentTimeMillis() - start + "ms spent on becoming the leader");
start = System.currentTimeMillis();
controller.syncStop();
verifyControllerIsNotLeader(controller);
verifyZKDisconnected(controller);
LOG.info(
System.currentTimeMillis() - start + "ms spent on becoming the standby node from leader");
}
@Test(description = "If the cluster has a controller, the second controller cannot take its leadership")
public void testWhenControllerAlreadyExists() {
// when the controller0 already takes over the leadership
ClusterControllerManager firstController =
new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, "FirstController");
firstController.syncStart();
verifyControllerIsLeader(firstController);
ClusterControllerManager secondController =
new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, "SecondController");
secondController.syncStart();
// The second controller cannot acquire the leadership from existing controller
verifyControllerIsNotLeader(secondController);
// but the zkClient is still connected
Assert.assertFalse(secondController.getZkClient().isClosed());
// stop the controllers
firstController.syncStop();
secondController.syncStop();
}
@Test
public void testWhenLeadershipSwitch() {
ClusterControllerManager firstController =
new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, "FirstController");
ClusterControllerManager secondController =
new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, "SecondController");
firstController.syncStart();
verifyControllerIsLeader(firstController);
firstController.syncStop();
verifyControllerIsNotLeader(firstController);
long start = System.currentTimeMillis();
// the second controller is started after the first controller is stopped
secondController.syncStart();
verifyControllerIsLeader(secondController);
verifyZKDisconnected(firstController);
long end = System.currentTimeMillis();
LOG.info(end - start + "ms spent on the leadership switch");
secondController.syncStop();
}
/**
* If the controller is not the leader of a cluster,
* 1. The LEADER node in ZK reflects the leadership of the controller
* 2. All the callback handlers are ready (successfully registered)
* 3. Controller Timer tasks are scheduled
*/
private void verifyControllerIsLeader(ClusterControllerManager controller) {
// check against the leader node
Assert.assertTrue(controller.isLeader());
// check the callback handlers are correctly registered
List<CallbackHandler> callbackHandlers = controller.getHandlers();
Assert.assertTrue(callbackHandlers.size() > 0);
callbackHandlers.forEach(callbackHandler -> Assert.assertTrue(callbackHandler.isReady()));
// check the zk connection is open
RealmAwareZkClient zkClient = controller.getZkClient();
Assert.assertFalse(zkClient.isClosed());
Long sessionId = zkClient.getSessionId();
Assert.assertNotNull(sessionId);
// check the controller related timer tasks are all active
//TODO: currently no good way to check if controller timer tasks are all stopped without
// adding a public method only for test purpose
// Assert.assertTrue(controller.getControllerTimerTasks().size() > 0);
}
/**
* When the controller is not the leader of a cluster, none of the properties
* {@link #verifyControllerIsLeader(ClusterControllerManager)} will hold
* NOTE: it's possible the ZKConnection is open while the controller is not the leader
*/
private void verifyControllerIsNotLeader(ClusterControllerManager controller) {
// check against the leader node
Assert.assertFalse(controller.isLeader());
// check no callback handler is leaked
Assert.assertTrue(controller.getHandlers().isEmpty());
// check the controller related timer tasks are all disabled
// Assert.assertTrue(controller.getControllerTimerTasks().isEmpty());
}
private void verifyZKDisconnected(ClusterControllerManager controller) {
// If the ZK connection is closed, it also means all ZK watchers of the session
// will be deleted on ZK servers
Assert.assertTrue(controller.getZkClient().isClosed());
}
@Test
public void testMissingTopStateDurationMonitoring() throws Exception {
String clusterName = "testCluster-TestControllerLeadershipChange";
String instanceName = clusterName + "-participant";
String resourceName = "testResource";
int numPartition = 1;
int numReplica = 1;
int simulatedTransitionDelayMs = 100;
String stateModel = "LeaderStandby";
ObjectName resourceMBeanObjectName = getResourceMonitorObjectName(clusterName, resourceName);
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
// Create cluster
_gSetupTool.addCluster(clusterName, true);
// Create cluster verifier
ZkHelixClusterVerifier clusterVerifier =
new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
// Create participant
_gSetupTool.addInstanceToCluster(clusterName, instanceName);
MockParticipantManager participant =
new MockParticipantManager(ZK_ADDR, clusterName, instanceName, simulatedTransitionDelayMs);
participant.syncStart();
// Create controller, since this is the only controller, it will be the leader
HelixManager manager1 = HelixManagerFactory
.getZKHelixManager(clusterName, clusterName + "-manager1", InstanceType.CONTROLLER,
ZK_ADDR);
manager1.connect();
Assert.assertTrue(manager1.isLeader());
// Create resource
_gSetupTool.addResourceToCluster(clusterName, resourceName, numPartition, stateModel,
IdealState.RebalanceMode.SEMI_AUTO.name());
// Rebalance Resource
_gSetupTool.rebalanceResource(clusterName, resourceName, numReplica);
// Wait for rebalance
Assert.assertTrue(clusterVerifier.verifyByPolling());
// Trigger missing top state in manager1
participant.syncStop();
Thread.sleep(1000);
// Starting manager2
HelixManager manager2 = HelixManagerFactory
.getZKHelixManager(clusterName, clusterName + "-manager2", InstanceType.CONTROLLER,
ZK_ADDR);
manager2.connect();
// Set leader to manager2
setLeader(manager2);
Assert.assertFalse(manager1.isLeader());
Assert.assertTrue(manager2.isLeader());
// Wait for rebalance
Assert.assertTrue(clusterVerifier.verify());
Thread.sleep(1000);
// The moment before manager1 regain leadership. The topstateless duration will start counting.
long start = System.currentTimeMillis();
setLeader(manager1);
Assert.assertTrue(manager1.isLeader());
Assert.assertFalse(manager2.isLeader());
// Make resource top state to come back by restarting participant
participant = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participant.syncStart();
_gSetupTool.rebalanceResource(clusterName, resourceName, numReplica);
Assert.assertTrue(clusterVerifier.verifyByPolling());
// The moment that partition top state has been recovered. The topstateless duration stopped counting.
long end = System.currentTimeMillis();
// Resource lost top state, and manager1 lost leadership for 2000ms, because manager1 will
// clean monitoring cache after re-gaining leadership, so max value of hand off duration should
// not have such a large value
long duration = (long) beanServer
.getAttribute(resourceMBeanObjectName, "PartitionTopStateHandoffDurationGauge.Max");
long controllerOpDuration = end - start;
Assert.assertTrue(duration >= simulatedTransitionDelayMs && duration <= controllerOpDuration,
String.format(
"The recorded TopState-less duration is %d. But the controller operation duration is %d.",
duration, controllerOpDuration));
participant.syncStop();
manager1.disconnect();
manager2.disconnect();
deleteCluster(clusterName);
}
private void setLeader(HelixManager manager) throws Exception {
HelixDataAccessor accessor = manager.getHelixDataAccessor();
final LiveInstance leader = new LiveInstance(manager.getInstanceName());
leader.setLiveInstance(ManagementFactory.getRuntimeMXBean().getName());
leader.setSessionId(manager.getSessionId());
leader.setHelixVersion(manager.getVersion());
// Delete the current controller leader node so it will trigger leader election
while (!manager.isLeader()) {
accessor.getBaseDataAccessor()
.remove(PropertyPathBuilder.controllerLeader(manager.getClusterName()),
AccessOption.EPHEMERAL);
Thread.sleep(50);
}
}
private ObjectName getResourceMonitorObjectName(String clusterName, String resourceName)
throws Exception {
return new ObjectName(String
.format("%s:cluster=%s,resourceName=%s", MonitorDomainNames.ClusterStatus.name(),
clusterName, resourceName));
}
}
| 9,584 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/controller/TestPipelinePerformance.java
|
package org.apache.helix.integration.controller;
/*
* 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 com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.management.ObjectName;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.TestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.rebalancer.waged.WagedRebalancer;
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.model.ClusterConfig;
import org.apache.helix.model.IdealState;
import org.apache.helix.tools.ClusterVerifiers.StrictMatchExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.apache.helix.model.BuiltInStateModelDefinitions.*;
public class TestPipelinePerformance extends ZkTestBase {
private static final int NUM_NODE = 6;
private static final int START_PORT = 12918;
private static final int REPLICA = 3;
private static final int PARTITIONS = 20;
private static final String RESOURCE_NAME = "Test_WAGED_Resource";
private String _clusterName;
private ClusterControllerManager _controller;
private ZkHelixClusterVerifier _clusterVerifier;
private List<MockParticipantManager> _participants = new ArrayList<>();
@BeforeClass
public void beforeClass() throws Exception {
_clusterName = String.format("CLUSTER_%s_%s", RandomStringUtils.randomAlphabetic(5), getShortClassName());
_gSetupTool.addCluster(_clusterName, true);
createResourceWithDelayedRebalance(_clusterName, RESOURCE_NAME, MasterSlave.name(), PARTITIONS, REPLICA, REPLICA, -1);
for (int i = 0; i < NUM_NODE; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(_clusterName, instanceName);
// start participants
MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, _clusterName, instanceName);
participant.syncStart();
_participants.add(participant);
}
// start controller
_controller = new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
_controller.syncStart();
enablePersistBestPossibleAssignment(_gZkClient, _clusterName, true);
_clusterVerifier = new StrictMatchExternalViewVerifier.Builder(_clusterName)
.setZkClient(_gZkClient)
.setDeactivatedNodeAwareness(true)
.setResources(Sets.newHashSet(RESOURCE_NAME))
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
// Set test instance capacity and partition weights
HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(_clusterName, _baseAccessor);
ClusterConfig clusterConfig = dataAccessor.getProperty(dataAccessor.keyBuilder().clusterConfig());
String testCapacityKey = "TestCapacityKey";
clusterConfig.setInstanceCapacityKeys(Collections.singletonList(testCapacityKey));
clusterConfig.setDefaultInstanceCapacityMap(Collections.singletonMap(testCapacityKey, 100));
clusterConfig.setDefaultPartitionWeightMap(Collections.singletonMap(testCapacityKey, 1));
dataAccessor.setProperty(dataAccessor.keyBuilder().clusterConfig(), clusterConfig);
}
@AfterClass
private void windDownTest() {
_controller.syncStop();
_participants.forEach(MockParticipantManager::syncStop);
deleteCluster(_clusterName);
}
@Test(enabled = false)
public void testWagedInstanceCapacityCalculationPerformance() throws Exception {
ObjectName currentStateMbeanObjectName = new ObjectName(
String.format("ClusterStatus:cluster=%s,eventName=ClusterEvent,phaseName=CurrentStateComputationStage",
_clusterName));
Assert.assertTrue(_server.isRegistered(currentStateMbeanObjectName));
long initialValue = (Long) _server.getAttribute(currentStateMbeanObjectName, "TotalDurationCounter");
/************************************************************************************************************
* Round 1:
* Enable WAGED on existing resource (this will trigger computation of WagedInstanceCapacity for first time)
************************************************************************************************************/
IdealState currentIdealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(_clusterName, RESOURCE_NAME);
currentIdealState.setRebalancerClassName(WagedRebalancer.class.getName());
_gSetupTool.getClusterManagementTool().setResourceIdealState(_clusterName, RESOURCE_NAME, currentIdealState);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
long withComputationValue = (Long) _server.getAttribute(currentStateMbeanObjectName, "TotalDurationCounter");
long durationWithComputation = withComputationValue - initialValue;
/************************************************************************************************************
* Round 2:
* Perform ideal state change, this wil not cause re-computation of WagedInstanceCapacity
************************************************************************************************************/
currentIdealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(_clusterName, RESOURCE_NAME);
currentIdealState.setInstanceGroupTag("Test");
_gSetupTool.getClusterManagementTool().setResourceIdealState(_clusterName, RESOURCE_NAME, currentIdealState);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
long withoutComputationValue = (Long) _server.getAttribute(currentStateMbeanObjectName, "TotalDurationCounter");
long durationWithoutComputation = withoutComputationValue - durationWithComputation;
double pctDecrease = (durationWithComputation - durationWithoutComputation) * 100 / durationWithComputation;
System.out.println(String.format("durationWithComputation: %s, durationWithoutComputation: %s, pctDecrease: %s",
durationWithComputation, durationWithoutComputation, pctDecrease));
Assert.assertTrue(durationWithComputation > durationWithoutComputation);
Assert.assertTrue(pctDecrease > 75.0);
}
}
| 9,585 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/ZkTestManager.java
|
package org.apache.helix.integration.manager;
/*
* 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.List;
import org.apache.helix.manager.zk.CallbackHandler;
import org.apache.helix.zookeeper.api.client.RealmAwareZkClient;
public interface ZkTestManager {
RealmAwareZkClient getZkClient();
List<CallbackHandler> getHandlers();
String getInstanceName();
String getClusterName();
}
| 9,586 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/ClusterControllerManager.java
|
package org.apache.helix.integration.manager;
/*
* 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 org.apache.helix.HelixManagerProperty;
import org.apache.helix.InstanceType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The standalone cluster controller class
*/
public class ClusterControllerManager extends ClusterManager {
private static Logger LOG = LoggerFactory.getLogger(ClusterControllerManager.class);
public ClusterControllerManager(String zkAddr, String clusterName) {
this(zkAddr, clusterName, "controller");
}
public ClusterControllerManager(String zkAddr, String clusterName, String controllerName) {
super(zkAddr, clusterName, controllerName, InstanceType.CONTROLLER);
}
public ClusterControllerManager(String clusterName, HelixManagerProperty helixManagerProperty) {
super(clusterName, "controller", InstanceType.CONTROLLER, null, null, helixManagerProperty);
}
@Override
public void finalize() {
super.finalize();
}
}
| 9,587 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/TestHelixDataAccessor.java
|
package org.apache.helix.integration.manager;
/*
* 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.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.helix.BaseDataAccessor;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixProperty;
import org.apache.helix.PropertyKey;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.api.exceptions.HelixMetaDataAccessException;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.mock.MockZkClient;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestHelixDataAccessor extends ZkTestBase {
private MockZkClient _zkClient;
private HelixDataAccessor accessor;
private List<PropertyKey> propertyKeys;
@BeforeClass
public void beforeClass() {
_zkClient = new MockZkClient(ZK_ADDR);
BaseDataAccessor<ZNRecord> baseDataAccessor = new ZkBaseDataAccessor<>(_zkClient);
accessor = new ZKHelixDataAccessor("HELIX", baseDataAccessor);
Map<String, HelixProperty> paths = new TreeMap<>();
propertyKeys = new ArrayList<>();
for (int i = 0; i < 5; i++) {
PropertyKey key = accessor.keyBuilder().idealStates("RESOURCE" + i);
propertyKeys.add(key);
paths.put(key.getPath(), new HelixProperty("RESOURCE" + i));
accessor.setProperty(key, paths.get(key.getPath()));
}
List<HelixProperty> data = accessor.getProperty(new ArrayList<>(propertyKeys), true);
Assert.assertEquals(data.size(), 5);
PropertyKey key = accessor.keyBuilder().idealStates("RESOURCE6");
propertyKeys.add(key);
_zkClient.putData(key.getPath(), null);
}
@AfterClass
public void afterClass() {
_zkClient.deleteRecursively("/HELIX");
}
@Test
public void testHelixDataAccessorReadData() {
accessor.getProperty(new ArrayList<>(propertyKeys), false);
try {
accessor.getProperty(new ArrayList<>(propertyKeys), true);
Assert.fail();
} catch (HelixMetaDataAccessException ignored) {
}
PropertyKey idealStates = accessor.keyBuilder().idealStates();
accessor.getChildValues(idealStates, false);
try {
accessor.getChildValues(idealStates, true);
Assert.fail();
} catch (HelixMetaDataAccessException ignored) {
}
accessor.getChildValuesMap(idealStates, false);
try {
accessor.getChildValuesMap(idealStates, true);
Assert.fail();
} catch (HelixMetaDataAccessException ignored) {
}
}
@Test(expectedExceptions = {
HelixMetaDataAccessException.class
})
public void testDataProviderRefresh() {
ResourceControllerDataProvider cache = new ResourceControllerDataProvider("MyCluster");
cache.refresh(accessor);
}
}
| 9,588 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/TestParticipantManager.java
|
package org.apache.helix.integration.manager;
/*
* 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.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import org.apache.helix.AccessOption;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.InstanceType;
import org.apache.helix.NotificationContext;
import org.apache.helix.PropertyKey;
import org.apache.helix.PropertyPathBuilder;
import org.apache.helix.SystemPropertyKeys;
import org.apache.helix.TestHelper;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.ParticipantHistory;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkTestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZKHelixManager;
import org.apache.helix.manager.zk.ZNRecordSerializer;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.mock.participant.MockMSModelFactory;
import org.apache.helix.mock.participant.MockTransition;
import org.apache.helix.model.Message;
import org.apache.helix.monitoring.mbeans.HelixCallbackMonitor;
import org.apache.helix.monitoring.mbeans.MBeanRegistrar;
import org.apache.helix.monitoring.mbeans.MonitorDomainNames;
import org.apache.helix.monitoring.mbeans.MonitorLevel;
import org.apache.helix.monitoring.mbeans.ZkClientMonitor;
import org.apache.helix.monitoring.mbeans.ZkClientPathMonitor;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.testng.Assert;
import org.testng.ITestContext;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
public class TestParticipantManager extends ZkTestBase {
private final MBeanServer _server = ManagementFactory.getPlatformMBeanServer();
private final String _clusterName = TestHelper.getTestClassName();
private final ExecutorService _executor = Executors.newFixedThreadPool(1);
static {
System.setProperty(SystemPropertyKeys.STATEUPDATEUTIL_ERROR_PERSISTENCY_ENABLED, "true");
}
@AfterMethod
public void afterMethod(Method testMethod, ITestContext testContext) {
deleteCluster(_clusterName);
}
@AfterClass
public void afterClass() {
System.clearProperty(SystemPropertyKeys.STATEUPDATEUTIL_ERROR_PERSISTENCY_ENABLED);
}
@Test
public void simpleIntegrationTest() throws Exception {
TestHelper.setupCluster(_clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
4, // partitions per resource
1, // number of nodes
1, // replicas
"MasterSlave", true); // do rebalance
String instanceName = "localhost_12918";
HelixManager participant =
new ZKHelixManager(_clusterName, instanceName, InstanceType.PARTICIPANT, ZK_ADDR);
participant.getStateMachineEngine().registerStateModelFactory("MasterSlave",
new MockMSModelFactory());
participant.connect();
HelixManager controller =
new ZKHelixManager(_clusterName, "controller_0", InstanceType.CONTROLLER, ZK_ADDR);
controller.connect();
verifyHelixManagerMetrics(InstanceType.PARTICIPANT, MonitorLevel.DEFAULT,
participant.getInstanceName());
verifyHelixManagerMetrics(InstanceType.CONTROLLER, MonitorLevel.DEFAULT,
controller.getInstanceName());
BestPossibleExternalViewVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
ParticipantHistory history = accessor.getProperty(keyBuilder.participantHistory(instanceName));
Assert.assertNotNull(history);
long historyModifiedTime = history.getRecord().getModifiedTime();
// cleanup
controller.disconnect();
participant.disconnect();
// verify all live-instances and leader nodes are gone
Assert.assertNull(accessor.getProperty(keyBuilder.liveInstance(instanceName)));
Assert.assertNull(accessor.getProperty(keyBuilder.controllerLeader()));
Assert.assertTrue(
historyModifiedTime <
accessor.getProperty(keyBuilder.participantHistory(instanceName)).getRecord().getModifiedTime());
}
@Test(invocationCount = 5)
public void testParticipantHistoryWithInstanceDrop() throws Exception {
TestHelper.setupCluster(_clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
4, // partitions per resource
1, // number of nodes
1, // replicas
"MasterSlave", true); // do rebalance
String instanceName = "localhost_12918";
HelixManager participant =
new ZKHelixManager(_clusterName, instanceName, InstanceType.PARTICIPANT, ZK_ADDR);
participant.getStateMachineEngine().registerStateModelFactory("MasterSlave",
new MockMSModelFactory());
participant.connect();
HelixManager controller =
new ZKHelixManager(_clusterName, "controller_0", InstanceType.CONTROLLER, ZK_ADDR);
controller.connect();
BestPossibleExternalViewVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
ParticipantHistory history = accessor.getProperty(keyBuilder.participantHistory(instanceName));
Assert.assertNotNull(history);
Future instanceDrop = _executor.submit(() -> {
boolean succeed = false;
while (!succeed) {
try {
// simulate instance drop
succeed = _baseAccessor.remove(keyBuilder.instance(instanceName).toString(), AccessOption.PERSISTENT);
} catch (Exception e) {
try {
Thread.sleep(100);
} catch (Exception ex) { }
}
}
});
// cleanup
controller.disconnect();
participant.disconnect();
instanceDrop.get(1000, TimeUnit.MILLISECONDS);
// ensure the history node is never created after instance drop
Assert.assertNull(accessor.getProperty(keyBuilder.participantHistory(instanceName)));
}
@Test
public void simpleIntegrationTestNeg() throws Exception {
TestHelper.setupCluster(_clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
4, // partitions per resource
1, // number of nodes
1, // replicas
"MasterSlave", true); // do rebalance
ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
ClusterConfig clusterConfig = configAccessor.getClusterConfig(_clusterName);
clusterConfig.getRecord()
.setListField(ClusterConfig.ClusterConfigProperty.INSTANCE_CAPACITY_KEYS.name(),
new ArrayList<>());
clusterConfig.setTopologyAwareEnabled(true);
clusterConfig.setTopology("/Rack/Sub-Rack/Host/Instance");
clusterConfig.setFaultZoneType("Host");
configAccessor.setClusterConfig(_clusterName, clusterConfig);
String instanceName = "localhost_12918";
HelixManager participant =
new ZKHelixManager(_clusterName, instanceName , InstanceType.PARTICIPANT, ZK_ADDR);
participant.getStateMachineEngine().registerStateModelFactory("MasterSlave",
new MockMSModelFactory());
// We are expecting an IllegalArgumentException since the domain is not set.
try {
participant.connect();
Assert.fail(); // connect will throw exception. The assertion will never be reached.
} catch (IllegalArgumentException expected) {
Assert.assertEquals(expected.getMessage(),
"Domain for instance localhost_12918 is not set, fail the topology-aware placement!");
}
// verify there is no live-instances created
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
Assert.assertNull(accessor.getProperty(keyBuilder.liveInstance(instanceName)));
Assert.assertNull(accessor.getProperty(keyBuilder.controllerLeader()));
}
@Test // (dependsOnMethods = "simpleIntegrationTest")
public void testMonitoringLevel() throws Exception {
int n = 1;
TestHelper.setupCluster(_clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
4, // partitions per resource
n, // number of nodes
1, // replicas
"MasterSlave", true); // do rebalance
System.setProperty(SystemPropertyKeys.MONITOR_LEVEL, MonitorLevel.ALL.name());
HelixManager participant;
try {
participant =
new ZKHelixManager(_clusterName, "localhost_12918", InstanceType.PARTICIPANT, ZK_ADDR);
} finally {
System.clearProperty(SystemPropertyKeys.MONITOR_LEVEL);
}
participant.getStateMachineEngine().registerStateModelFactory("MasterSlave",
new MockMSModelFactory());
participant.connect();
verifyHelixManagerMetrics(InstanceType.PARTICIPANT, MonitorLevel.ALL,
participant.getInstanceName());
// cleanup
participant.disconnect();
}
private void verifyHelixManagerMetrics(InstanceType type, MonitorLevel monitorLevel,
String instanceName) throws MalformedObjectNameException {
// check HelixCallback Monitor
Set<ObjectInstance> objs =
_server.queryMBeans(buildCallbackMonitorObjectName(type, _clusterName, instanceName), null);
Assert.assertEquals(objs.size(), 19);
// check HelixZkClient Monitors
objs =
_server.queryMBeans(buildZkClientMonitorObjectName(type, _clusterName, instanceName), null);
Assert.assertEquals(objs.size(), 1);
objs = _server.queryMBeans(buildZkClientPathMonitorObjectName(type, _clusterName, instanceName),
null);
int expectedZkPathMonitor;
switch (monitorLevel) {
case ALL:
expectedZkPathMonitor = 10;
break;
case AGGREGATED_ONLY:
expectedZkPathMonitor = 1;
break;
default:
expectedZkPathMonitor =
type == InstanceType.CONTROLLER || type == InstanceType.CONTROLLER_PARTICIPANT ? 10 : 1;
}
Assert.assertEquals(objs.size(), expectedZkPathMonitor);
}
private ObjectName buildCallbackMonitorObjectName(InstanceType type, String cluster,
String instance) throws MalformedObjectNameException {
return MBeanRegistrar.buildObjectName(MonitorDomainNames.HelixCallback.name(),
HelixCallbackMonitor.MONITOR_TYPE, type.name(), HelixCallbackMonitor.MONITOR_KEY,
cluster + "." + instance, HelixCallbackMonitor.MONITOR_CHANGE_TYPE, "*");
}
private ObjectName buildZkClientMonitorObjectName(InstanceType type, String cluster,
String instance) throws MalformedObjectNameException {
return MBeanRegistrar.buildObjectName(MonitorDomainNames.HelixZkClient.name(),
ZkClientMonitor.MONITOR_TYPE, type.name(), ZkClientMonitor.MONITOR_KEY,
cluster + "." + instance);
}
private ObjectName buildZkClientPathMonitorObjectName(InstanceType type, String cluster,
String instance) throws MalformedObjectNameException {
return MBeanRegistrar.buildObjectName(MonitorDomainNames.HelixZkClient.name(),
ZkClientMonitor.MONITOR_TYPE, type.name(), ZkClientMonitor.MONITOR_KEY,
cluster + "." + instance, ZkClientPathMonitor.MONITOR_PATH, "*");
}
@Test
public void simpleSessionExpiryTest() throws Exception {
int n = 1;
MockParticipantManager[] participants = new MockParticipantManager[n];
TestHelper.setupCluster(_clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
1, // partitions per resource
n, // number of nodes
1, // replicas
"MasterSlave", true); // do rebalance
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
controller.syncStart();
// start participants
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, _clusterName, instanceName);
participants[i].syncStart();
}
BestPossibleExternalViewVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
String oldSessionId = participants[0].getSessionId();
// expire zk-connection on localhost_12918
ZkTestHelper.expireSession(participants[0].getZkClient());
// wait until session expiry callback happens
TimeUnit.MILLISECONDS.sleep(100);
Assert.assertTrue(verifier.verifyByPolling());
String newSessionId = participants[0].getSessionId();
Assert.assertNotSame(newSessionId, oldSessionId);
// cleanup
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
}
class SessionExpiryTransition extends MockTransition {
private final AtomicBoolean _done = new AtomicBoolean();
private final CountDownLatch _startCountdown;
private final CountDownLatch _endCountdown;
public SessionExpiryTransition(CountDownLatch startCountdown, CountDownLatch endCountdown) {
_startCountdown = startCountdown;
_endCountdown = endCountdown;
}
@Override
public void doTransition(Message message, NotificationContext context)
throws InterruptedException {
String instance = message.getTgtName();
String partition = message.getPartitionName();
if (instance.equals("localhost_12918") && partition.equals("TestDB0_0")
&& !_done.getAndSet(true)) {
_startCountdown.countDown();
// this await will be interrupted since we cancel the task during handleNewSession
_endCountdown.await();
}
}
}
@Test
public void testSessionExpiryInTransition() throws Exception {
int n = 1;
CountDownLatch startCountdown = new CountDownLatch(1);
CountDownLatch endCountdown = new CountDownLatch(1);
MockParticipantManager[] participants = new MockParticipantManager[n];
TestHelper.setupCluster(_clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
1, // partitions per resource
n, // number of nodes
1, // replicas
"MasterSlave", true); // do rebalance
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, _clusterName, "controller_0");
controller.syncStart();
// start participants
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, _clusterName, instanceName);
participants[i].setTransition(new SessionExpiryTransition(startCountdown, endCountdown));
participants[i].syncStart();
}
// wait transition happens to trigger session expiry
startCountdown.await();
String oldSessionId = participants[0].getSessionId();
ZkTestHelper.expireSession(participants[0].getZkClient());
BestPossibleExternalViewVerifier verifier =
new BestPossibleExternalViewVerifier.Builder(_clusterName).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(verifier.verifyByPolling());
String newSessionId = participants[0].getSessionId();
Assert.assertNotSame(newSessionId, oldSessionId);
// assert interrupt exception error in old session
String errPath = PropertyPathBuilder.instanceError(_clusterName, "localhost_12918", oldSessionId,
"TestDB0", "TestDB0_0");
ZNRecord error = _gZkClient.readData(errPath);
Assert.assertNotNull(error,
"InterruptedException should happen in old session since task is being cancelled during handleNewSession");
String errString = new String(new ZNRecordSerializer().serialize(error));
Assert.assertTrue(errString.contains("InterruptedException"));
// cleanup
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
}
}
| 9,589 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/TestConsecutiveZkSessionExpiry.java
|
package org.apache.helix.integration.manager;
/*
* 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 java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.PreConnectCallback;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.ZkTestHelper;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.manager.zk.CallbackHandler;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.mock.participant.MockMSModelFactory;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestConsecutiveZkSessionExpiry extends ZkUnitTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestConsecutiveZkSessionExpiry.class);
/**
* make use of PreConnectCallback to insert session expiry during HelixManager#handleNewSession()
*/
class PreConnectTestCallback implements PreConnectCallback {
final String instanceName;
final CountDownLatch startCountDown;
final CountDownLatch endCountDown;
int count = 0;
public PreConnectTestCallback(String instanceName, CountDownLatch startCountdown,
CountDownLatch endCountdown) {
this.instanceName = instanceName;
this.startCountDown = startCountdown;
this.endCountDown = endCountdown;
}
@Override
public void onPreConnect() {
// TODO Auto-generated method stub
LOG.info("handleNewSession for instance: " + instanceName + ", count: " + count);
if (count++ == 1) {
startCountDown.countDown();
LOG.info("wait session expiry to happen");
try {
endCountDown.await();
} catch (Exception e) {
LOG.error("interrupted in waiting", e);
}
}
}
}
@Test
public void testParticipant() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
final int n = 2;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
32, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
// start controller
final ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// start participants
CountDownLatch startCountdown = new CountDownLatch(1);
CountDownLatch endCountdown = new CountDownLatch(1);
MockParticipantManager[] participants = new MockParticipantManager[n];
for (int i = 0; i < n; i++) {
final String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
if (i == 0) {
participants[i].addPreConnectCallback(new PreConnectTestCallback(instanceName,
startCountdown, endCountdown));
}
participants[i].syncStart();
}
boolean result =
ClusterStateVerifier
.verifyByZkCallback(
new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
Assert.assertTrue(result);
// expire the session of participant
LOG.info("1st Expiring participant session...");
String oldSessionId = participants[0].getSessionId();
ZkTestHelper.asyncExpireSession(participants[0].getZkClient());
String newSessionId = participants[0].getSessionId();
LOG.info("Expried participant session. oldSessionId: " + oldSessionId + ", newSessionId: "
+ newSessionId);
// expire zk session again during HelixManager#handleNewSession()
startCountdown.await();
LOG.info("2nd Expiring participant session...");
oldSessionId = participants[0].getSessionId();
ZkTestHelper.asyncExpireSession(participants[0].getZkClient());
newSessionId = participants[0].getSessionId();
LOG.info("Expried participant session. oldSessionId: " + oldSessionId + ", newSessionId: "
+ newSessionId);
endCountdown.countDown();
result =
ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
ZK_ADDR, clusterName));
Assert.assertTrue(result);
// clean up
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void testDistributedController() throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
int n = 2;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
4, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
ClusterDistributedController[] distributedControllers = new ClusterDistributedController[n];
CountDownLatch startCountdown = new CountDownLatch(1);
CountDownLatch endCountdown = new CountDownLatch(1);
for (int i = 0; i < n; i++) {
String contrllerName = "localhost_" + (12918 + i);
distributedControllers[i] =
new ClusterDistributedController(ZK_ADDR, clusterName, contrllerName);
distributedControllers[i].getStateMachineEngine().registerStateModelFactory("MasterSlave",
new MockMSModelFactory());
if (i == 0) {
distributedControllers[i].addPreConnectCallback(new PreConnectTestCallback(contrllerName,
startCountdown, endCountdown));
}
distributedControllers[i].connect();
}
boolean result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// expire the session of distributedController
LOG.info("1st Expiring distributedController session...");
String oldSessionId = distributedControllers[0].getSessionId();
ZkTestHelper.asyncExpireSession(distributedControllers[0].getZkClient());
String newSessionId = distributedControllers[0].getSessionId();
LOG.info("Expried distributedController session. oldSessionId: " + oldSessionId
+ ", newSessionId: " + newSessionId);
// expire zk session again during HelixManager#handleNewSession()
startCountdown.await();
LOG.info("2nd Expiring distributedController session...");
oldSessionId = distributedControllers[0].getSessionId();
ZkTestHelper.asyncExpireSession(distributedControllers[0].getZkClient());
newSessionId = distributedControllers[0].getSessionId();
LOG.info("Expried distributedController session. oldSessionId: " + oldSessionId
+ ", newSessionId: " + newSessionId);
endCountdown.countDown();
result =
ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
ZK_ADDR, clusterName));
Assert.assertTrue(result);
// verify leader changes to localhost_12919
HelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
Assert.assertNotNull(pollForProperty(LiveInstance.class, accessor,
keyBuilder.liveInstance("localhost_12918"), true));
LiveInstance leader =
pollForProperty(LiveInstance.class, accessor, keyBuilder.controllerLeader(), true);
Assert.assertNotNull(leader);
Assert.assertEquals(leader.getId(), "localhost_12919");
// check localhost_12918 has 2 handlers: message and data-accessor
LOG.debug("handlers: " + TestHelper.printHandlers(distributedControllers[0]));
List<CallbackHandler> handlers = distributedControllers[0].getHandlers();
Assert
.assertEquals(
handlers.size(),
1,
"Distributed controller should have 1 handler (message) after lose leadership, but was "
+ handlers.size());
// clean up
distributedControllers[0].disconnect();
distributedControllers[1].disconnect();
Assert.assertNull(pollForProperty(LiveInstance.class, accessor,
keyBuilder.liveInstance("localhost_12918"), false));
Assert.assertNull(pollForProperty(LiveInstance.class, accessor,
keyBuilder.liveInstance("localhost_12919"), false));
Assert.assertNull(pollForProperty(LiveInstance.class, accessor, keyBuilder.controllerLeader(),
false));
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,590 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/ClusterManager.java
|
package org.apache.helix.integration.manager;
/*
* 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.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.helix.HelixManagerProperty;
import org.apache.helix.InstanceType;
import org.apache.helix.manager.zk.CallbackHandler;
import org.apache.helix.manager.zk.HelixManagerStateListener;
import org.apache.helix.manager.zk.ZKHelixManager;
import org.apache.helix.zookeeper.api.client.RealmAwareZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClusterManager extends ZKHelixManager implements Runnable, ZkTestManager {
private static Logger LOG = LoggerFactory.getLogger(ClusterControllerManager.class);
private static final int DISCONNECT_WAIT_TIME_MS = 3000;
private static AtomicLong UID = new AtomicLong(10000);
private long _uid;
private final String _clusterName;
private final String _instanceName;
private final InstanceType _type;
protected CountDownLatch _startCountDown = new CountDownLatch(1);
protected CountDownLatch _stopCountDown = new CountDownLatch(1);
protected CountDownLatch _waitStopFinishCountDown = new CountDownLatch(1);
protected boolean _started = false;
protected Thread _watcher;
protected ClusterManager(String zkAddr, String clusterName, String instanceName,
InstanceType type) {
super(clusterName, instanceName, type, zkAddr);
_clusterName = clusterName;
_instanceName = instanceName;
_type = type;
_uid = UID.getAndIncrement();
}
protected ClusterManager(String clusterName, String instanceName, InstanceType instanceType,
String zkAddress, HelixManagerStateListener stateListener,
HelixManagerProperty helixManagerProperty) {
super(clusterName, instanceName, instanceType, zkAddress, stateListener, helixManagerProperty);
_clusterName = clusterName;
_instanceName = instanceName;
_type = instanceType;
_uid = UID.getAndIncrement();
}
public void syncStop() {
_stopCountDown.countDown();
try {
_waitStopFinishCountDown.await();
_started = false;
} catch (InterruptedException e) {
LOG.error("Interrupted waiting for finish", e);
}
}
// This should not be called more than once because HelixManager.connect() should not be called more than once.
public void syncStart() {
if (_started) {
throw new RuntimeException(
"Helix Controller already started. Do not call syncStart() more than once.");
} else {
_started = true;
}
_watcher = new Thread(this);
_watcher.setName(String
.format("ClusterManager_Watcher_%s_%s_%s_%d", _clusterName, _instanceName, _type.name(), _uid));
LOG.debug("ClusterManager_watcher_{}_{}_{}_{} started, stacktrace {}", _clusterName, _instanceName, _type.name(), _uid, Thread.currentThread().getStackTrace());
_watcher.start();
try {
_startCountDown.await();
} catch (InterruptedException e) {
LOG.error("Interrupted waiting for start", e);
}
}
@Override
public void run() {
try {
connect();
_startCountDown.countDown();
_stopCountDown.await();
} catch (Exception e) {
LOG.error("exception running controller-manager", e);
} finally {
_startCountDown.countDown();
disconnect();
_waitStopFinishCountDown.countDown();
}
}
@Override
public RealmAwareZkClient getZkClient() {
return _zkclient;
}
@Override
public List<CallbackHandler> getHandlers() {
return _handlers;
}
@Override
public void finalize() {
_watcher.interrupt();
try {
_watcher.join(DISCONNECT_WAIT_TIME_MS);
} catch (InterruptedException e) {
LOG.error("ClusterManager watcher cleanup in the finalize method was interrupted.", e);
} finally {
if (isConnected()) {
LOG.warn(
"The HelixManager ({}-{}-{}) is still connected after {} ms wait. This is a potential resource leakage!",
_clusterName, _instanceName, _type.name(), DISCONNECT_WAIT_TIME_MS);
}
}
}
}
| 9,591 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/TestZkHelixAdmin.java
|
package org.apache.helix.integration.manager;
/*
* 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.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.TestHelper;
import org.apache.helix.integration.task.MockTask;
import org.apache.helix.integration.task.TaskTestBase;
import org.apache.helix.integration.task.WorkflowGenerator;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.model.IdealState;
import org.apache.helix.task.JobConfig;
import org.apache.helix.task.JobContext;
import org.apache.helix.task.TaskPartitionState;
import org.apache.helix.task.TaskUtil;
import org.apache.helix.task.Workflow;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestZkHelixAdmin extends TaskTestBase {
private HelixAdmin _admin;
private ConfigAccessor _configAccessor;
@BeforeClass
public void beforeClass() throws Exception {
_numDbs = 1;
_numNodes = 2;
_numPartitions = 3;
_numReplicas = 2;
_partitionVary = false;
_admin = new ZKHelixAdmin(_gZkClient);
_configAccessor = new ConfigAccessor(_gZkClient);
super.beforeClass();
}
@Test
public void testEnableDisablePartitions() throws InterruptedException {
_admin.enablePartition(false, CLUSTER_NAME, (PARTICIPANT_PREFIX + "_" + _startPort),
WorkflowGenerator.DEFAULT_TGT_DB, Arrays.asList(new String[] { "TestDB_0", "TestDB_2" }));
_admin.enablePartition(false, CLUSTER_NAME, (PARTICIPANT_PREFIX + "_" + (_startPort + 1)),
WorkflowGenerator.DEFAULT_TGT_DB, Arrays.asList(new String[] { "TestDB_0", "TestDB_2" }));
IdealState idealState =
_admin.getResourceIdealState(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
List<String> preferenceList =
Arrays.asList(new String[] { "localhost_12919", "localhost_12918" });
for (String partitionName : idealState.getPartitionSet()) {
idealState.setPreferenceList(partitionName, preferenceList);
}
idealState.setRebalanceMode(IdealState.RebalanceMode.SEMI_AUTO);
_admin.setResourceIdealState(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB, idealState);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
String workflowName = TestHelper.getTestMethodName();
Workflow.Builder builder = new Workflow.Builder(workflowName);
JobConfig.Builder jobBuilder =
new JobConfig.Builder().setWorkflow(workflowName).setCommand(MockTask.TASK_COMMAND)
.setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB)
.setTargetPartitionStates(Collections.singleton("SLAVE"));
builder.addJob("JOB", jobBuilder);
_driver.start(builder.build());
Thread.sleep(2000L);
JobContext jobContext =
_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB"));
int n = idealState.getNumPartitions();
for ( int i = 0; i < n; i++) {
String targetPartition = jobContext.getTargetForPartition(i);
if (targetPartition.equals("TestDB_0") || targetPartition.equals("TestDB_2")) {
Assert.assertEquals(jobContext.getPartitionState(i), null);
} else {
Assert.assertEquals(jobContext.getPartitionState(i), TaskPartitionState.COMPLETED);
}
}
}
}
| 9,592 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/TestControllerManager.java
|
package org.apache.helix.integration.manager;
/*
* 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 java.util.concurrent.TimeUnit;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkTestHelper;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestControllerManager extends ZkUnitTestBase {
@Test
public void testMultipleControllersOfSameName() throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
int n = 5;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
16, // partitions per resource
n, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
// start multiple controllers of same name
int m = 3;
ClusterControllerManager[] controllers = new ClusterControllerManager[m];
for (int i = 0; i < m; i++) {
controllers[i] = new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controllers[i].syncStart();
}
// assert that only one is leader
int leaderCnt = 0;
for (int i = 0; i < m; i++) {
if (controllers[i].isLeader()) {
leaderCnt++;
}
}
Assert.assertEquals(leaderCnt, 1, "Should have only 1 leader but was " + leaderCnt);
MockParticipantManager[] participants = new MockParticipantManager[n];
for (int i = 0; i < n; i++) {
final String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
boolean result =
ClusterStateVerifier
.verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// cleanup
for (int i = 0; i < m; i++) {
controllers[i].syncStop();
}
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
@Test
public void simpleSessionExpiryTest() throws Exception {
// Logger.getRootLogger().setLevel(Level.WARN);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
final String clusterName = className + "_" + methodName;
int n = 5;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
MockParticipantManager[] participants = new MockParticipantManager[n];
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
16, // partitions per resource
n, // number of nodes
3, // replicas
"MasterSlave", true); // do rebalance
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
// start participants
for (int i = 0; i < n; i++) {
String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
boolean result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
String oldSessionId = controller.getSessionId();
// expire zk-connection on localhost_12918
ZkTestHelper.expireSession(controller.getZkClient());
// wait until session expiry callback happens
TimeUnit.MILLISECONDS.sleep(100);
result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
String newSessionId = controller.getSessionId();
Assert.assertNotSame(newSessionId, oldSessionId);
// cleanup
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,593 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/ClusterSpectatorManager.java
|
package org.apache.helix.integration.manager;
/*
* 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 org.apache.helix.InstanceType;
public class ClusterSpectatorManager extends ClusterManager {
public ClusterSpectatorManager(String zkAddr, String clusterName) {
this(zkAddr, clusterName, "spectator");
}
public ClusterSpectatorManager(String zkAddr, String clusterName, String spectatorName) {
super(zkAddr, clusterName, spectatorName, InstanceType.SPECTATOR);
}
@Override
public void finalize() {
super.finalize();
}
}
| 9,594 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/MockParticipantManager.java
|
package org.apache.helix.integration.manager;
/*
* 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.List;
import java.util.concurrent.CountDownLatch;
import org.apache.helix.HelixCloudProperty;
import org.apache.helix.HelixManagerProperty;
import org.apache.helix.HelixPropertyFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.manager.zk.CallbackHandler;
import org.apache.helix.mock.participant.DummyProcess.DummyLeaderStandbyStateModelFactory;
import org.apache.helix.mock.participant.DummyProcess.DummyOnlineOfflineStateModelFactory;
import org.apache.helix.mock.participant.MockMSModelFactory;
import org.apache.helix.mock.participant.MockSchemataModelFactory;
import org.apache.helix.mock.participant.MockTransition;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.participant.StateMachineEngine;
import org.apache.helix.zookeeper.api.client.RealmAwareZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MockParticipantManager extends ClusterManager {
private static final Logger LOG = LoggerFactory.getLogger(MockParticipantManager.class);
protected int _transDelay = 10;
protected MockMSModelFactory _msModelFactory;
protected DummyLeaderStandbyStateModelFactory _lsModelFactory;
protected DummyOnlineOfflineStateModelFactory _ofModelFactory;
protected HelixCloudProperty _helixCloudProperty;
public MockParticipantManager(String zkAddr, String clusterName, String instanceName) {
this(zkAddr, clusterName, instanceName, 10);
}
public MockParticipantManager(String zkAddr, String clusterName, String instanceName,
int transDelay) {
this(zkAddr, clusterName, instanceName, transDelay, null);
}
public MockParticipantManager(String zkAddr, String clusterName, String instanceName,
int transDelay, HelixCloudProperty helixCloudProperty) {
this(zkAddr, clusterName, instanceName, transDelay, helixCloudProperty,
HelixPropertyFactory.getInstance().getHelixManagerProperty(zkAddr, clusterName));
}
public MockParticipantManager(String zkAddr, String clusterName, String instanceName,
int transDelay, HelixCloudProperty helixCloudProperty,
HelixManagerProperty helixManagerProperty) {
super(clusterName, instanceName, InstanceType.PARTICIPANT, zkAddr, null, helixManagerProperty);
_transDelay = transDelay;
_msModelFactory = new MockMSModelFactory(null);
_lsModelFactory = new DummyLeaderStandbyStateModelFactory(_transDelay);
_ofModelFactory = new DummyOnlineOfflineStateModelFactory(_transDelay);
_helixCloudProperty = helixCloudProperty;
}
public MockParticipantManager(String clusterName, String instanceName,
HelixManagerProperty helixManagerProperty, int transDelay,
HelixCloudProperty helixCloudProperty) {
super(clusterName, instanceName, InstanceType.PARTICIPANT, null, null, helixManagerProperty);
_transDelay = transDelay;
_msModelFactory = new MockMSModelFactory(null);
_lsModelFactory = new DummyLeaderStandbyStateModelFactory(_transDelay);
_ofModelFactory = new DummyOnlineOfflineStateModelFactory(_transDelay);
_helixCloudProperty = helixCloudProperty;
}
public void setTransition(MockTransition transition) {
_msModelFactory.setTrasition(transition);
}
/**
* This method should be called before syncStart() called after syncStop()
*/
public void reset() {
syncStop();
_startCountDown = new CountDownLatch(1);
_stopCountDown = new CountDownLatch(1);
_waitStopFinishCountDown = new CountDownLatch(1);
}
@Override
public void run() {
try {
StateMachineEngine stateMach = getStateMachineEngine();
stateMach.registerStateModelFactory(BuiltInStateModelDefinitions.MasterSlave.name(),
_msModelFactory);
stateMach.registerStateModelFactory(BuiltInStateModelDefinitions.LeaderStandby.name(),
_lsModelFactory);
stateMach.registerStateModelFactory(BuiltInStateModelDefinitions.OnlineOffline.name(),
_ofModelFactory);
MockSchemataModelFactory schemataFactory = new MockSchemataModelFactory();
stateMach.registerStateModelFactory("STORAGE_DEFAULT_SM_SCHEMATA", schemataFactory);
connect();
_startCountDown.countDown();
_stopCountDown.await();
} catch (InterruptedException e) {
String msg =
"participant: " + getInstanceName() + ", " + Thread.currentThread().getName()
+ " is interrupted";
LOG.info(msg);
} catch (Exception e) {
LOG.error("exception running participant-manager", e);
} finally {
_startCountDown.countDown();
disconnect();
_waitStopFinishCountDown.countDown();
}
}
@Override
public RealmAwareZkClient getZkClient() {
return _zkclient;
}
@Override
public List<CallbackHandler> getHandlers() {
return _handlers;
}
@Override
public void finalize() {
super.finalize();
}
}
| 9,595 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/ClusterDistributedController.java
|
package org.apache.helix.integration.manager;
/*
* 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 org.apache.helix.InstanceType;
import org.apache.helix.participant.DistClusterControllerStateModelFactory;
import org.apache.helix.participant.StateMachineEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClusterDistributedController extends ClusterManager {
private static Logger LOG = LoggerFactory.getLogger(ClusterDistributedController.class);
public ClusterDistributedController(String zkAddr, String clusterName, String controllerName) {
super(zkAddr, clusterName, controllerName, InstanceType.CONTROLLER_PARTICIPANT);
}
@Override
public void run() {
try {
StateMachineEngine stateMach = getStateMachineEngine();
DistClusterControllerStateModelFactory lsModelFactory =
new DistClusterControllerStateModelFactory(_zkAddress);
stateMach.registerStateModelFactory("LeaderStandby", lsModelFactory);
connect();
_startCountDown.countDown();
_stopCountDown.await();
} catch (Exception e) {
LOG.error("exception running controller-manager", e);
} finally {
_startCountDown.countDown();
disconnect();
_waitStopFinishCountDown.countDown();
}
}
@Override
public void finalize() {
super.finalize();
}
}
| 9,596 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/TestDistributedControllerManager.java
|
package org.apache.helix.integration.manager;
/*
* 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 java.util.List;
import org.apache.helix.HelixManager;
import org.apache.helix.InstanceType;
import org.apache.helix.PropertyKey;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkTestHelper;
import org.apache.helix.common.ZkTestBase;
import org.apache.helix.manager.zk.CallbackHandler;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZKHelixManager;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.mock.participant.MockMSModelFactory;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestDistributedControllerManager extends ZkTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestDistributedControllerManager.class);
@Test
public void simpleIntegrationTest() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
int n = 2;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
4, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
HelixManager[] distributedControllers = new HelixManager[n];
for (int i = 0; i < n; i++) {
int port = 12918 + i;
distributedControllers[i] = new ZKHelixManager(clusterName, "localhost_" + port,
InstanceType.CONTROLLER_PARTICIPANT, ZK_ADDR);
distributedControllers[i].getStateMachineEngine().registerStateModelFactory("MasterSlave",
new MockMSModelFactory());
distributedControllers[i].connect();
}
BestPossibleExternalViewVerifier verifier = new BestPossibleExternalViewVerifier
.Builder(clusterName).setZkAddress(ZK_ADDR).build();
boolean result = verifier.verifyByZkCallback();
Assert.assertTrue(result);
// disconnect first distributed-controller, and verify second takes leadership
distributedControllers[0].disconnect();
Thread.sleep(100);
// verify leader changes to localhost_12919
result = verifier.verifyByZkCallback();
Assert.assertTrue(result);
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
Assert.assertNull(accessor.getProperty(keyBuilder.liveInstance("localhost_12918")));
LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader());
Assert.assertNotNull(leader);
Assert.assertEquals(leader.getId(), "localhost_12919");
// clean up
distributedControllers[1].disconnect();
Assert.assertNull(accessor.getProperty(keyBuilder.liveInstance("localhost_12919")));
Assert.assertNull(accessor.getProperty(keyBuilder.controllerLeader()));
deleteCluster(clusterName);
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
/**
* expire a controller and make sure the other takes the leadership
* @param expireController
* @param newController
* @throws Exception
*/
private void expireController(ClusterDistributedController expireController,
ClusterDistributedController newController) throws Exception {
String clusterName = expireController.getClusterName();
LOG.info("Expiring distributedController: " + expireController.getInstanceName() + ", session: "
+ expireController.getSessionId() + " ...");
String oldSessionId = expireController.getSessionId();
ZkTestHelper.expireSession(expireController.getZkClient());
String newSessionId = expireController.getSessionId();
LOG.debug("Expired distributedController: " + expireController.getInstanceName()
+ ", oldSessionId: " + oldSessionId + ", newSessionId: " + newSessionId);
BestPossibleExternalViewVerifier verifier = new BestPossibleExternalViewVerifier
.Builder(clusterName).setZkAddress(ZK_ADDR).build();
boolean result = verifier.verifyByPolling();
Assert.assertTrue(result);
// verify leader changes to localhost_12919
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
Assert.assertNotNull(
accessor.getProperty(keyBuilder.liveInstance(expireController.getInstanceName())));
LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader());
Assert.assertNotNull(leader);
Assert.assertEquals(leader.getId(), newController.getInstanceName());
// check expired-controller has 2 handlers: message and data-accessor
LOG.debug(expireController.getInstanceName() + " handlers: "
+ TestHelper.printHandlers(expireController));
List<CallbackHandler> handlers = expireController.getHandlers();
Assert.assertEquals(handlers.size(), 1,
"Distributed controller should have 1 handler (message) after lose leadership, but was "
+ handlers.size());
}
@Test
public void simpleSessionExpiryTest() throws Exception {
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
int n = 2;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
4, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
ClusterDistributedController[] distributedControllers = new ClusterDistributedController[n];
for (int i = 0; i < n; i++) {
String contrllerName = "localhost_" + (12918 + i);
distributedControllers[i] =
new ClusterDistributedController(ZK_ADDR, clusterName, contrllerName);
distributedControllers[i].getStateMachineEngine().registerStateModelFactory("MasterSlave",
new MockMSModelFactory());
distributedControllers[i].connect();
}
BestPossibleExternalViewVerifier verifier = new BestPossibleExternalViewVerifier
.Builder(clusterName).setZkAddress(ZK_ADDR).build();
boolean result = verifier.verifyByZkCallback();
Assert.assertTrue(result);
// expire localhost_12918
expireController(distributedControllers[0], distributedControllers[1]);
// expire localhost_12919
expireController(distributedControllers[1], distributedControllers[0]);
// clean up
ZKHelixDataAccessor accessor =
new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
PropertyKey.Builder keyBuilder = accessor.keyBuilder();
for (int i = 0; i < n; i++) {
distributedControllers[i].disconnect();
Assert.assertNull(accessor
.getProperty(keyBuilder.liveInstance(distributedControllers[i].getInstanceName())));
}
Assert.assertNull(accessor.getProperty(keyBuilder.controllerLeader()));
deleteCluster(clusterName);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,597 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/manager/TestStateModelLeak.java
|
package org.apache.helix.integration.manager;
/*
* 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 java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.helix.HelixAdmin;
import org.apache.helix.TestHelper;
import org.apache.helix.ZkUnitTestBase;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.mock.participant.ErrTransition;
import org.apache.helix.participant.HelixStateMachineEngine;
import org.apache.helix.participant.statemachine.StateModel;
import org.apache.helix.participant.statemachine.StateModelFactory;
import org.apache.helix.tools.ClusterStateVerifier;
import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* test drop resource should remove state-models
*/
public class TestStateModelLeak extends ZkUnitTestBase {
private static Logger LOG = LoggerFactory.getLogger(TestStateModelLeak.class);
/**
* test drop resource should remove all state models
* @throws Exception
*/
@Test
public void testDrop() throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
int n = 2;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
4, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
MockParticipantManager[] participants = new MockParticipantManager[n];
for (int i = 0; i < n; i++) {
final String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
participants[i].syncStart();
}
boolean result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// check state-models in state-machine
HelixStateMachineEngine stateMachine =
(HelixStateMachineEngine) participants[0].getStateMachineEngine();
StateModelFactory<? extends StateModel> fty = stateMachine.getStateModelFactory("MasterSlave");
Map<String, String> expectStateModelMap = new TreeMap<String, String>();
expectStateModelMap.put("TestDB0_0", "SLAVE");
expectStateModelMap.put("TestDB0_1", "MASTER");
expectStateModelMap.put("TestDB0_2", "SLAVE");
expectStateModelMap.put("TestDB0_3", "MASTER");
checkStateModelMap(fty, expectStateModelMap);
// drop resource
HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
admin.dropResource(clusterName, "TestDB0");
result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// check state models have been dropped also
Assert.assertTrue(fty.getPartitionSet("TestDB0").isEmpty(),
"All state-models should be dropped, but was " + fty.getPartitionSet("TestDB0"));
// cleanup
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
TestHelper.dropCluster(clusterName, _gZkClient);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
/**
* test drop resource in error state should remove all state-models
* @throws Exception
*/
@Test
public void testDropErrorPartition() throws Exception {
// Logger.getRootLogger().setLevel(Level.INFO);
String className = TestHelper.getTestClassName();
String methodName = TestHelper.getTestMethodName();
String clusterName = className + "_" + methodName;
int n = 2;
System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
"localhost", // participant name prefix
"TestDB", // resource name prefix
1, // resources
4, // partitions per resource
n, // number of nodes
2, // replicas
"MasterSlave", true); // do rebalance
// start controller
ClusterControllerManager controller =
new ClusterControllerManager(ZK_ADDR, clusterName, "controller");
controller.syncStart();
MockParticipantManager[] participants = new MockParticipantManager[n];
for (int i = 0; i < n; i++) {
final String instanceName = "localhost_" + (12918 + i);
participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
if (i == 0) {
Map<String, Set<String>> errTransitionMap = new HashMap<String, Set<String>>();
Set<String> partitions = new HashSet<String>();
partitions.add("TestDB0_0");
errTransitionMap.put("OFFLINE-SLAVE", partitions);
participants[0].setTransition(new ErrTransition(errTransitionMap));
}
participants[i].syncStart();
}
Map<String, Map<String, String>> errStates = new HashMap<String, Map<String, String>>();
errStates.put("TestDB0", new HashMap<String, String>());
errStates.get("TestDB0").put("TestDB0_0", "localhost_12918");
boolean result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName, errStates));
Assert.assertTrue(result);
// check state-models in state-machine
HelixStateMachineEngine stateMachine =
(HelixStateMachineEngine) participants[0].getStateMachineEngine();
StateModelFactory<? extends StateModel> fty = stateMachine.getStateModelFactory("MasterSlave");
Map<String, String> expectStateModelMap = new TreeMap<String, String>();
expectStateModelMap.put("TestDB0_0", "ERROR");
expectStateModelMap.put("TestDB0_1", "MASTER");
expectStateModelMap.put("TestDB0_2", "SLAVE");
expectStateModelMap.put("TestDB0_3", "MASTER");
checkStateModelMap(fty, expectStateModelMap);
// drop resource
HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
admin.dropResource(clusterName, "TestDB0");
result =
ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
clusterName));
Assert.assertTrue(result);
// check state models have been dropped also
Assert.assertTrue(fty.getPartitionSet("TestDB0").isEmpty(),
"All state-models should be dropped, but was " + fty.getPartitionSet("TestDB0"));
// cleanup
controller.syncStop();
for (int i = 0; i < n; i++) {
participants[i].syncStop();
}
TestHelper.dropCluster(clusterName, _gZkClient);
System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
}
/**
* check state-model factory contains state-models same as in expect-state-model map
* @param fty
* @param expectStateModelMap
*/
static void checkStateModelMap(StateModelFactory<? extends StateModel> fty,
Map<String, String> expectStateModelMap) {
Assert.assertEquals(fty.getPartitionSet("TestDB0").size(), expectStateModelMap.size());
for (String partition : fty.getPartitionSet("TestDB0")) {
StateModel stateModel = fty.getStateModel("TestDB0", partition);
String actualState = stateModel.getCurrentState();
String expectState = expectStateModelMap.get(partition);
LOG.debug(partition + " actual state: " + actualState + ", expect state: " + expectState);
Assert.assertEquals(actualState, expectState, "partition: " + partition
+ " should be in state: " + expectState + " but was " + actualState);
}
}
}
| 9,598 |
0 |
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration
|
Create_ds/helix/helix-core/src/test/java/org/apache/helix/integration/common/ZkStandAloneCMTestBase.java
|
package org.apache.helix.integration.common;
/*
* 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.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
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.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
/**
* setup a storage cluster and start a zk-based cluster controller in stand-alone mode
* start 5 dummy participants verify the current states at end
*/
public class ZkStandAloneCMTestBase extends ZkTestBase {
protected static final int NODE_NR = 5;
protected static final int START_PORT = 12918;
protected static final String STATE_MODEL = "MasterSlave";
protected static final String TEST_DB = "TestDB";
protected static final int _PARTITIONS = 20;
protected HelixManager _manager;
protected final String CLASS_NAME = getShortClassName();
protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
protected ZkHelixClusterVerifier _clusterVerifier;
protected MockParticipantManager[] _participants = new MockParticipantManager[NODE_NR];
protected ClusterControllerManager _controller;
protected int _replica = 3;
@BeforeClass
public void beforeClass() throws Exception {
super.beforeClass();
System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
// setup storage cluster
_gSetupTool.addCluster(CLUSTER_NAME, true);
_gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL);
for (int i = 0; i < NODE_NR; i++) {
String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
}
_gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, _replica);
// start dummy participants
for (int i = 0; i < NODE_NR; i++) {
String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
_participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
_participants[i].syncStart();
}
// start controller
String controllerName = CONTROLLER_PREFIX + "_0";
_controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
_controller.syncStart();
_clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
.setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME)
.build();
Assert.assertTrue(_clusterVerifier.verifyByPolling());
// create cluster manager
_manager = HelixManagerFactory
.getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR);
_manager.connect();
}
@AfterClass
public void afterClass() throws Exception {
if (_clusterVerifier != null) {
_clusterVerifier.close();
}
/*
* shutdown order: 1) disconnect the controller 2) disconnect participants
*/
if (_controller != null && _controller.isConnected()) {
_controller.syncStop();
}
for (int i = 0; i < NODE_NR; i++) {
if (_participants[i] != null && _participants[i].isConnected()) {
_participants[i].syncStop();
}
}
if (_manager != null && _manager.isConnected()) {
_manager.disconnect();
}
deleteCluster(CLUSTER_NAME);
System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
}
}
| 9,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.